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.

Auditor: fast model tier by default, and no audit stays running after a restart

Lin (kwant bot)fc3d9e684eb7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 871bca1b..9b77643c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
`GET /api/tasks/:id/risks`, `GET /api/risks`, `POST /api/tasks/:id/audit`, and
`POST /api/tasks/:id/risks/:risk_id/resolve`. No screen for it yet.
+### Changed
+- **Audits run on the fast model by default.** The Swarm Auditor's challenge and rebuttal turns now use
+ the engine's cheap, fast model (for Claude, Haiku at medium effort) instead of the bot's default. The
+ new `auditor_model` setting picks `fast` (default), `balanced`, `deep`, or `bot` for the bot's usual
+ model.
+
### Fixed
+- **A restart no longer leaves an audit running.** An audit cut off mid-turn by a restart ends
+ `interrupted` and says so in the task's history; one still waiting to start runs after the restart
+ (or is skipped if the auditor was turned off).
- **"Answer in chat" works when that chat is already open.** On the Mission board, "Answer in chat" and
"Open the chat it came from" now close the board and show the chat even when it's the one already
selected underneath; before, nothing visible happened.
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 0dd78abd..34566494 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -690,7 +690,10 @@ never moves a task, never adds or runs a check and never writes a peer review; "
a pass. Design note: `phase-d/auditor.md`.
**Settings** (app-wide, like the other Mission Control settings): `auditor` = `off` (default) | `on`;
-`auditor_daily_cap` 1–50 (default 5) audits started per UTC day.
+`auditor_daily_cap` 1–50 (default 5) audits started per UTC day; `auditor_model` = `fast` (default) |
+`balanced` | `deep` | `bot`: the model tier both audit turns run on. A tier keeps the engine Laya picks
+and uses that engine's model of the tier (a pinned model of another known tier gives way; effort is at
+most medium below `deep`); where the engine has none, its default model. `bot` routes as usual.
**Trigger.** A task entering `review` with an owner, while `auditor` is on, when its priority is high or
urgent (`high_impact`) or no check that counts and isn't the owner's will judge it (`low_confidence`,
@@ -718,7 +721,12 @@ While an audit of a task is `queued`, `challenge` or `rebuttal`, its challenger
`dismissed`. Tokens of each turn (`model_usage` in the turn's window) are stored per stage.
**Ledger** (`task_events`): `audit_started`, `audit_challenge`, `audit_rebuttal`, `audit_done`,
-`audit_skipped`, `risk_resolved`. Audits left running at a restart become `interrupted`.
+`audit_skipped`, `risk_resolved`.
+
+**Restarts.** An audit is never left running. At startup, one in `challenge` or `rebuttal` becomes
+`interrupted` ("kwant restarted during the audit", logged as `audit_done`; risks already raised stay
+listed); a `queued` one runs now, or is `skipped` ("the auditor was turned off") when the auditor is
+off. A driver that stops early (a panic) ends its audit `failed`.
**API**
diff --git a/src/db/auditor.rs b/src/db/auditor.rs
index dc6a262c..e309b2a3 100644
--- a/src/db/auditor.rs
+++ b/src/db/auditor.rs
@@ -134,14 +134,27 @@ impl Database {
] {
sqlx::query(stmt).execute(&self.pool).await?;
}
- // Audits a restart cut off never finish: say so instead of leaving them running
- sqlx::query(
- "UPDATE task_audits SET status = 'interrupted', reason = 'kwant restarted during the audit', finished_at = ? \
- WHERE status IN ('queued', 'challenge', 'rebuttal')",
- )
- .bind(Utc::now())
- .execute(&self.pool)
- .await?;
+ // A restart cuts off the turn of an audit in a stage: it never finishes, so say so (on the
+ // task too) instead of leaving it running. Its risks stay listed. Queued audits had no
+ // turn yet: the server runs them again (`auditor::resume_after_restart`).
+ let cut: Vec<(String, String, String)> =
+ sqlx::query_as("SELECT id, task_id, status FROM task_audits WHERE status IN ('challenge', 'rebuttal')").fetch_all(&self.pool).await?;
+ for (id, task_id, stage) in cut {
+ let moved = sqlx::query(
+ "UPDATE task_audits SET status = 'interrupted', reason = 'kwant restarted during the audit', finished_at = ? WHERE id = ? AND status = ?",
+ )
+ .bind(Utc::now())
+ .bind(&id)
+ .bind(&stage)
+ .execute(&self.pool)
+ .await?;
+ if moved.rows_affected() == 1 {
+ let detail = serde_json::json!({"audit_id": id, "status": "interrupted", "stage": stage, "reason": "kwant restarted during the audit"});
+ if let Err(e) = self.log_task_event(&task_id, "audit_done", "kwant", &detail).await {
+ tracing::warn!(task_id, error = %e, "interrupted audit not logged");
+ }
+ }
+ }
Ok(())
}
@@ -182,6 +195,11 @@ impl Database {
Ok(sqlx::query_as::<_, Audit>("SELECT * FROM task_audits WHERE task_id = ? ORDER BY created_at, rowid").bind(task_id).fetch_all(&self.pool).await?)
}
+ /// Audits in `status`, oldest first.
+ pub async fn audits_in(&self, status: &str) -> Result<Vec<Audit>, DbError> {
+ Ok(sqlx::query_as::<_, Audit>("SELECT * FROM task_audits WHERE status = ? ORDER BY created_at, rowid").bind(status).fetch_all(&self.pool).await?)
+ }
+
pub async fn audit_of_attempt(&self, task_id: &str, attempt: i64) -> Result<Option<Audit>, DbError> {
Ok(sqlx::query_as::<_, Audit>("SELECT * FROM task_audits WHERE task_id = ? AND attempt = ?")
.bind(task_id)
@@ -384,13 +402,15 @@ mod tests {
}
#[tokio::test]
- async fn a_restart_marks_running_audits_interrupted() {
+ async fn a_restart_marks_audits_in_a_stage_interrupted_and_keeps_queued_ones() {
let (db, _t) = db().await;
let a = db.create_audit("t1", "spc_default", 0, "manual", "a", "b").await.unwrap().unwrap();
assert!(db.move_audit(&a.id, "queued", "challenge", None).await.unwrap());
+ let q = db.create_audit("t2", "spc_default", 0, "manual", "a", "b").await.unwrap().unwrap();
db.migrate_auditor().await.unwrap();
let a = db.get_audit(&a.id).await.unwrap().unwrap();
assert_eq!((a.status.as_str(), a.finished_at.is_some()), ("interrupted", true));
+ assert_eq!(db.get_audit(&q.id).await.unwrap().unwrap().status, "queued");
}
#[tokio::test]
diff --git a/src/router/mod.rs b/src/router/mod.rs
index c90b6467..c6acca04 100644
--- a/src/router/mod.rs
+++ b/src/router/mod.rs
@@ -117,6 +117,22 @@ pub fn apply_preferred_model(mut route: RouteDecision, preferred_model: &str) ->
route
}
+/// A turn kwant runs on a set tier (an audit on the fast tier): the tier picks the engine's model.
+/// A pinned model gives way only when its own tier is known and differs, so a custom or Ollama
+/// model stays the bot's own. Below the deep tier, effort is capped at medium.
+pub fn with_tier(mut route: RouteDecision, tier: crate::drivers::engines::Tier) -> RouteDecision {
+ use crate::drivers::engines::{tier_from_name, Tier};
+ route.tier = Some(tier);
+ if route.model.as_deref().and_then(tier_from_name).is_some_and(|t| t != tier) {
+ route.model = None;
+ }
+ if tier != Tier::Deep && !matches!(route.effort_level.as_str(), "low" | "medium") {
+ route.effort_level = "medium".into();
+ }
+ route.reasoning = format!("{} · {} tier for this turn", route.reasoning, tier.as_str());
+ route
+}
+
/// Parses a successful response from Laya /v1/systemone into a RouteDecision
pub fn parse_laya_response(data: &serde_json::Value) -> Option<RouteDecision> {
let answers = data.get("answers")?;
diff --git a/src/serve.rs b/src/serve.rs
index 33352206..d66aae5d 100644
--- a/src/serve.rs
+++ b/src/serve.rs
@@ -54,6 +54,8 @@ pub async fn run(config: Config, shutdown: impl Future<Output = ()>) -> Result<(
// chats say which replies it cut off
crate::server::mcp_runtime::keep_cards_after_restart(&state).await;
crate::server::routes::interrupt_running_turns(&state).await;
+ // Audits that were waiting their turn when kwant stopped run now (the cut-off ones ended)
+ crate::server::missions::auditor::resume_after_restart(&state).await;
crate::server::scheduler::spawn_background(state.clone(), cancel.clone());
crate::server::engine_routes::spawn_startup_check(state.clone());
crate::server::parallel_routes::spawn_startup_sweep(state.clone());
diff --git a/src/server/missions/auditor.rs b/src/server/missions/auditor.rs
index 996b8599..af7732c5 100644
--- a/src/server/missions/auditor.rs
+++ b/src/server/missions/auditor.rs
@@ -9,6 +9,7 @@ use crate::db::auditor::{audit_json, Answer, Audit, NewRisk};
use crate::db::missions::{OutcomeCheck, Task};
use crate::db::models::Kwant;
use crate::db::spaces::SpaceId;
+use crate::drivers::engines::Tier;
use crate::server::continuity::SelfScope;
use crate::server::routes::{scope_for, turn_once, TurnOpts};
use crate::server::spaces::Scope;
@@ -29,6 +30,11 @@ pub const MODES: [&str; 2] = ["off", "on"];
pub const CAP_SETTING: &str = "auditor_daily_cap";
pub const DEFAULT_CAP: i64 = 5;
pub const CAP_RANGE: (i64, i64) = (1, 50);
+/// The model tier audit turns run on: the engine's `fast` model by default, or `bot` for the
+/// model the bot would use anyway.
+pub const MODEL_SETTING: &str = "auditor_model";
+pub const MODEL_MODES: [&str; 4] = ["fast", "balanced", "deep", "bot"];
+pub const DEFAULT_MODEL: &str = "fast";
pub const MAX_RISKS: usize = 5;
const MAX_RISK_CHARS: usize = 500;
const MAX_EVIDENCE_CHARS: usize = 1000;
@@ -49,13 +55,31 @@ pub async fn daily_cap(state: &AppState) -> i64 {
super::int_setting(state, CAP_SETTING, CAP_RANGE, DEFAULT_CAP).await
}
-pub fn settings_error(mode: Option<&str>, cap: Option<i64>) -> Option<String> {
+pub async fn model_mode(state: &AppState) -> &'static str {
+ let saved = state.db.get_setting(MODEL_SETTING).await.ok().flatten();
+ MODEL_MODES.into_iter().find(|m| Some(*m) == saved.as_deref().map(str::trim)).unwrap_or(DEFAULT_MODEL)
+}
+
+/// The tier an audit turn runs on for `mode`; `None` (`bot`) leaves it to the usual routing.
+pub fn tier_of(mode: &str) -> Option<Tier> {
+ match mode {
+ "bot" => None,
+ "balanced" => Some(Tier::Balanced),
+ "deep" => Some(Tier::Deep),
+ _ => Some(Tier::Fast),
+ }
+}
+
+pub fn settings_error(mode: Option<&str>, cap: Option<i64>, model: Option<&str>) -> Option<String> {
if let Some(m) = mode.filter(|m| !MODES.contains(m)) {
return Some(format!("auditor must be off or on (got {m})"));
}
if let Some(n) = cap.filter(|n| !(CAP_RANGE.0..=CAP_RANGE.1).contains(n)) {
return Some(format!("auditor_daily_cap must be {}–{} (got {n})", CAP_RANGE.0, CAP_RANGE.1));
}
+ if let Some(m) = model.filter(|m| !MODEL_MODES.contains(m)) {
+ return Some(format!("auditor_model must be fast, balanced, deep or bot (got {m})"));
+ }
None
}
@@ -160,13 +184,15 @@ pub async fn start(state: &AppState, task: &Task, trigger: &str) -> Result<Audit
Ok(None) => return Err("this attempt of the task was already audited".into()),
Err(e) => return Err(e.to_string()),
};
- event(state, &task.id, "audit_started", "kwant", json!({"audit_id": audit.id, "trigger": trigger, "challenger": challenger.id})).await;
+ let model = model_mode(state).await;
+ event(state, &task.id, "audit_started", "kwant", json!({"audit_id": audit.id, "trigger": trigger, "challenger": challenger.id, "model": model})).await;
Ok(audit)
}
/// Runs an audit: the challenge turn, then the rebuttal turn if there are risks. Never moves the
/// task. Each stage that ends without its tool call ends the audit with a reason.
pub async fn drive(state: &AppState, audit: &Audit) {
+ let _unstick = Unstick(state.clone(), audit.id.clone());
let _one = ONE.lock().await;
let task = match state.db.get_task(&audit.task_id).await {
Ok(Some(t)) if matches!(t.state.as_str(), "review" | "verified") => t,
@@ -199,6 +225,50 @@ pub async fn drive(state: &AppState, audit: &Audit) {
finish(state, audit).await;
}
+/// Ends the audit failed if its driver stops while it is still live (a panic, a dropped task),
+/// so an audit never stays running; a normal end leaves a final status and this does nothing.
+struct Unstick(AppState, String);
+
+impl Drop for Unstick {
+ fn drop(&mut self) {
+ let (state, id) = (self.0.clone(), std::mem::take(&mut self.1));
+ if let Ok(rt) = tokio::runtime::Handle::try_current() {
+ rt.spawn(async move { end_if_live(&state, &id, "the audit stopped before it finished").await });
+ }
+ }
+}
+
+/// Ends audit `id` as `failed` with `reason` when it is still queued or in a stage, and logs its
+/// end on the task. False when it had already ended.
+pub async fn end_if_live(state: &AppState, id: &str, reason: &str) -> bool {
+ let Ok(Some(a)) = state.db.get_audit(id).await else { return false };
+ if !matches!(a.status.as_str(), "queued" | "challenge" | "rebuttal") {
+ return false;
+ }
+ if !state.db.move_audit(id, &a.status, "failed", Some(reason)).await.unwrap_or(false) {
+ return false;
+ }
+ tracing::warn!(audit_id = id, task_id = %a.task_id, reason, "audit ended");
+ finish(state, &a).await;
+ true
+}
+
+/// At startup, after the database marked the audits a restart cut off mid-turn `interrupted`:
+/// the ones still `queued` (no turn had started) run now, or are skipped if the auditor was
+/// turned off.
+pub async fn resume_after_restart(state: &AppState) {
+ let queued = state.db.audits_in("queued").await.unwrap_or_default();
+ let on = enabled(state).await;
+ for a in queued {
+ if on {
+ let s = state.clone();
+ tokio::spawn(async move { drive(&s, &a).await });
+ } else if state.db.move_audit(&a.id, "queued", "skipped", Some("the auditor was turned off")).await.unwrap_or(false) {
+ event(state, &a.task_id, "audit_skipped", "kwant", json!({"audit_id": a.id, "reason": "auditor_off"})).await;
+ }
+ }
+}
+
fn ended_without(stage: &str, err: Option<&str>) -> String {
let who = if stage == "challenge" { "the challenger's turn ended without a challenge" } else { "the owner's turn ended without a rebuttal" };
match err {
@@ -232,6 +302,7 @@ async fn run_stage(state: &AppState, audit: &Audit, bot: &Kwant, stage: &str, pr
Ok(scope) => {
let mut opts = TurnOpts::always_asking("Audit");
(opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));
+ opts.tier = tier_of(model_mode(state).await);
match tokio::time::timeout(TURN_TIMEOUT, turn_once(&scope, bot, prompt, opts)).await {
Ok(r) => r,
Err(_) => Err("the audit turn took longer than 20 minutes".into()),
@@ -605,10 +676,20 @@ mod tests {
#[test]
fn settings_are_checked() {
- assert!(settings_error(Some("on"), Some(5)).is_none());
- assert!(settings_error(Some("suggest"), None).is_some());
- assert!(settings_error(None, Some(0)).is_some());
- assert!(settings_error(None, Some(51)).is_some());
+ assert!(settings_error(Some("on"), Some(5), Some("fast")).is_none());
+ assert!(settings_error(Some("suggest"), None, None).is_some());
+ assert!(settings_error(None, Some(0), None).is_some());
+ assert!(settings_error(None, Some(51), None).is_some());
+ assert!(settings_error(None, None, Some("bot")).is_none());
+ assert!(settings_error(None, None, Some("haiku")).is_some());
+ }
+
+ #[test]
+ fn audit_turns_run_on_the_fast_tier_unless_told_otherwise() {
+ assert_eq!(tier_of(DEFAULT_MODEL), Some(Tier::Fast));
+ assert_eq!(tier_of("balanced"), Some(Tier::Balanced));
+ assert_eq!(tier_of("deep"), Some(Tier::Deep));
+ assert_eq!(tier_of("bot"), None);
}
#[test]
diff --git a/src/server/routes.rs b/src/server/routes.rs
index c8e42ee3..661451e4 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1495,6 +1495,8 @@ pub(super) struct TurnOpts {
pub(super) quiet_failure: bool,
/// Shown as the turn's `purpose` in `GET /api/turns` (`turns[]`).
pub(super) purpose: Option<String>,
+ /// The model tier this turn runs on whatever Laya's effort says (see [`crate::router::with_tier`]).
+ pub(super) tier: Option<crate::drivers::engines::Tier>,
}
impl TurnOpts {
@@ -1875,6 +1877,10 @@ async fn run_kwant_turn_inner(
}
}
let route = crate::router::apply_preferred_model(route, &target_kwant.preferred_model);
+ let route = match opts.tier {
+ Some(t) => crate::router::with_tier(route, t),
+ None => route,
+ };
let target_model = route.selected_model.clone();
// Flight School (D7): a task below act never runs on an engine kwant can't gate
@@ -3322,6 +3328,8 @@ pub struct SettingsResponse {
pub auditor: String,
/// Audits started per UTC day (1–50).
pub auditor_daily_cap: i64,
+ /// The model tier of audit turns: `fast` (default), `balanced`, `deep` or `bot` (its usual one).
+ pub auditor_model: String,
}
/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of
@@ -3367,6 +3375,7 @@ pub struct SaveSettingsPayload {
pub flight_school_new_bot_tier: Option<String>,
pub auditor: Option<String>,
pub auditor_daily_cap: Option<i64>,
+ pub auditor_model: Option<String>,
}
pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {
@@ -3421,6 +3430,7 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings
flight_school_new_bot_tier: super::missions::flight_school::new_bot_tier(&state.db).await.into(),
auditor: if super::missions::auditor::enabled(&state).await { "on" } else { "off" }.into(),
auditor_daily_cap: super::missions::auditor::daily_cap(&state).await,
+ auditor_model: super::missions::auditor::model_mode(&state).await.into(),
}))
}
@@ -3479,7 +3489,7 @@ pub async fn save_settings(
if let Some(e) = super::missions::flight_school::settings_error(payload.flight_school_new_bot_tier.as_deref()) {
return bad(e);
}
- if let Some(e) = super::missions::auditor::settings_error(payload.auditor.as_deref(), payload.auditor_daily_cap) {
+ if let Some(e) = super::missions::auditor::settings_error(payload.auditor.as_deref(), payload.auditor_daily_cap, payload.auditor_model.as_deref()) {
return bad(e);
}
if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {
@@ -3610,6 +3620,9 @@ pub async fn save_settings(
if let Some(n) = payload.auditor_daily_cap {
let _ = state.db.set_setting(super::missions::auditor::CAP_SETTING, &n.to_string()).await;
}
+ if let Some(m) = &payload.auditor_model {
+ let _ = state.db.set_setting(super::missions::auditor::MODEL_SETTING, m).await;
+ }
if let Some(on) = payload.agent_tools {
let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;
}
diff --git a/tests/auditor_test.rs b/tests/auditor_test.rs
index c80d21b3..474fbb5b 100644
--- a/tests/auditor_test.rs
+++ b/tests/auditor_test.rs
@@ -11,7 +11,7 @@ use kwnt::{
broker::PermissionBroker,
config::Config,
db::{
- missions::{NewCheck, NewMission, NewTask, Task},
+ missions::{NewCheck, NewMission, NewTask, Task, TaskChange},
models::{Kwant, NewKwant},
performance::NewObservation,
spaces::{SpaceId, DEFAULT_SPACE_ID},
@@ -577,7 +577,15 @@ async fn a_failed_audit_turn_leaves_the_task_alone() {
assert!(done.reason.as_deref().unwrap_or("").contains("without a challenge"), "{done:?}");
assert_eq!(verification(&e, &t.id).await, before, "an audit never moves or checks the task");
assert!(e.state.db.risks_of_audit(&a.id).await.unwrap().is_empty());
- let kinds = events(&e, &t.id).await;
+ // Its end is logged just after the status changes
+ let mut kinds = events(&e, &t.id).await;
+ for _ in 0..100 {
+ if kinds.iter().any(|k| k == "audit_done") {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ kinds = events(&e, &t.id).await;
+ }
assert!(kinds.contains(&"audit_done".to_string()), "{kinds:?}");
assert!(!kinds.iter().any(|k| k == "verified" || k == "failed" || k == "peer_review"), "{kinds:?}");
}
@@ -601,3 +609,112 @@ async fn a_queued_audit_of_a_task_sent_back_holds_nothing() {
e.state.db.move_audit(&a.id, "challenge", "failed", Some("test")).await.unwrap();
assert!(auditor::held(&e.state, &owner.id, "task_claim", &t).await.is_none());
}
+
+#[tokio::test]
+async fn audit_turns_run_on_the_fast_tier_by_default() {
+ let e = setup().await;
+ let s = person(&e, "GET", "/api/settings", None).await;
+ assert_eq!(s["auditor_model"], "fast", "{s}");
+ let (status, v) = call(&e.app, "POST", "/api/settings", None, Some(json!({"auditor_model": "haiku"}))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "only a tier or bot: {v}");
+ person(&e, "POST", "/api/settings", Some(json!({"auditor_model": "bot"}))).await;
+ assert_eq!(person(&e, "GET", "/api/settings", None).await["auditor_model"], "bot");
+ assert_eq!(auditor::tier_of(auditor::model_mode(&e.state).await), None, "bot: the usual routing");
+
+ // The audit's start says which it ran on
+ person(&e, "POST", "/api/settings", Some(json!({"auditor_model": "balanced"}))).await;
+ auditor_on(&e, 5).await;
+ let (owner, _other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
+ let t = task(&e, Some(&owner), 2, "review").await;
+ auditor::start(&e.state, &t, "manual").await.unwrap();
+ let started = e.state.db.task_events(&t.id, 50).await.unwrap().into_iter().find(|ev| ev.kind == "audit_started").unwrap();
+ assert!(started.detail.contains("\"model\":\"balanced\""), "{}", started.detail);
+}
+
+/// Opens the same data folder again, as a restarted kwant does, and runs its startup step.
+async fn restart(e: &Env) -> AppState {
+ let data = e._tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config { data_dir: data.clone(), laya_url: "http://127.0.0.1:9".into(), ..Config::default() };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ auditor::resume_after_restart(&state).await;
+ state
+}
+
+async fn ended(state: &AppState, id: &str) -> kwnt::db::auditor::Audit {
+ for _ in 0..100 {
+ let a = state.db.get_audit(id).await.unwrap().unwrap();
+ if !matches!(a.status.as_str(), "queued" | "challenge" | "rebuttal") {
+ return a;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("audit {id} is still running");
+}
+
+#[tokio::test]
+async fn a_restart_never_leaves_an_audit_running() {
+ let e = setup().await;
+ let (owner, other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
+ auditor_on(&e, 10).await;
+ // Cut off mid-challenge
+ let t1 = task(&e, Some(&owner), 2, "review").await;
+ let a1 = open_audit(&e, &t1).await;
+ // Cut off waiting for the owner's answer, with a risk raised
+ let t2 = task(&e, Some(&owner), 2, "review").await;
+ let a2 = open_audit(&e, &t2).await;
+ let risk = kwnt::db::auditor::NewRisk { risk: "The file may be empty".into(), evidence: "saw 0 bytes".into(), evidence_ids: vec![] };
+ e.state.db.record_challenge(&a2.id, &[risk]).await.unwrap().unwrap();
+ assert_eq!(e.state.db.get_audit(&a2.id).await.unwrap().unwrap().status, "rebuttal");
+ // Still queued, its task sent back meanwhile
+ let t3 = task(&e, Some(&owner), 2, "review").await;
+ let a3 = auditor::start(&e.state, &t3, "manual").await.unwrap();
+ assert!(e.state.db.move_task(&t3.id, "review", "ready", "person", &TaskChange::default()).await.unwrap());
+ let before = (verification(&e, &t1.id).await, verification(&e, &t2.id).await);
+
+ let state = restart(&e).await;
+ let a1 = ended(&state, &a1.id).await;
+ assert_eq!((a1.status.as_str(), a1.reason.as_deref()), ("interrupted", Some("kwant restarted during the audit")));
+ let a2 = ended(&state, &a2.id).await;
+ assert_eq!(a2.status, "interrupted");
+ let risks = state.db.risks_of_audit(&a2.id).await.unwrap();
+ assert!(risks.len() == 1 && risks[0].unresolved(), "a raised risk stays listed: {risks:?}");
+ // The queued one ran after the restart and saw its task had moved on
+ let a3 = ended(&state, &a3.id).await;
+ assert_eq!(a3.status, "skipped", "{a3:?}");
+
+ // Each task's history says so; nothing else changed and nothing is held any more
+ for t in [&t1, &t2] {
+ let evs = state.db.task_events(&t.id, 50).await.unwrap();
+ assert!(evs.iter().any(|ev| ev.kind == "audit_done" && ev.detail.contains("interrupted")), "{:?}", evs.iter().map(|e| &e.kind).collect::<Vec<_>>());
+ assert!(auditor::held(&state, &owner.id, "task_review", t).await.is_none());
+ assert!(auditor::held(&state, &other.id, "task_review", t).await.is_none());
+ }
+ assert_eq!((verification(&e, &t1.id).await, verification(&e, &t2.id).await), before, "a restart never moves or checks the task");
+ assert!(auditor::live_audit(&state, &t3.id).await.is_none());
+
+ // Queued while the auditor was turned off: skipped at the next start, never run
+ let t4 = task(&e, Some(&owner), 2, "review").await;
+ let a4 = auditor::start(&e.state, &t4, "manual").await.unwrap();
+ person(&e, "POST", "/api/settings", Some(json!({"auditor": "off"}))).await;
+ let state = restart(&e).await;
+ let a4 = state.db.get_audit(&a4.id).await.unwrap().unwrap();
+ assert_eq!((a4.status.as_str(), a4.reason.as_deref()), ("skipped", Some("the auditor was turned off")));
+}
+
+#[tokio::test]
+async fn an_audit_whose_driver_stopped_ends_failed() {
+ let e = setup().await;
+ let (owner, _other) = (bot(&e, "Owner").await, bot(&e, "Other").await);
+ auditor_on(&e, 5).await;
+ let t = task(&e, Some(&owner), 2, "review").await;
+ let a = open_audit(&e, &t).await;
+ let before = verification(&e, &t.id).await;
+ assert!(auditor::end_if_live(&e.state, &a.id, "the audit stopped before it finished").await);
+ let a = e.state.db.get_audit(&a.id).await.unwrap().unwrap();
+ assert_eq!((a.status.as_str(), a.finished_at.is_some()), ("failed", true));
+ assert!(!auditor::end_if_live(&e.state, &a.id, "again").await, "an ended audit stays as it ended");
+ assert!(events(&e, &t.id).await.contains(&"audit_done".to_string()));
+ assert_eq!(verification(&e, &t.id).await, before);
+ assert!(auditor::held(&e.state, &owner.id, "task_update", &t).await.is_none());
+}
diff --git a/tests/router_test.rs b/tests/router_test.rs
index 975b65c5..90d37b49 100644
--- a/tests/router_test.rs
+++ b/tests/router_test.rs
@@ -872,3 +872,42 @@ fn short_follow_up_with_attachment_does_not_get_the_deep_tier() {
let long = "please go through every line of this and compare it with last month and tell me where we are off ".repeat(2);
assert_eq!(cap(&format!("{long}{files}"), "high"), None);
}
+
+#[test]
+fn a_set_tier_picks_the_engines_model_of_that_tier() {
+ use kwnt::drivers::engines::{choose_model, claude_cli_models, Tier};
+ use kwnt::router::{apply_preferred_model, with_tier, RouteDecision};
+ let laya = || RouteDecision {
+ selected_model: "claude".into(),
+ effort_level: "high".into(),
+ confidence: 0.7,
+ provider_endpoint: None,
+ is_fallback: false,
+ tier: None,
+ model: None,
+ reasoning: "laya".into(),
+ };
+ let claude = claude_cli_models();
+ let model = |r: &RouteDecision| choose_model(&claude, r.model.as_deref(), r.tier.unwrap()).map(|c| c.id);
+
+ // Laya's high effort would run Opus; the fast tier runs Haiku at medium effort
+ let usual = apply_preferred_model(laya(), "auto");
+ assert_eq!(model(&usual).as_deref(), Some("opus"));
+ let fast = with_tier(apply_preferred_model(laya(), "auto"), Tier::Fast);
+ assert_eq!((model(&fast).as_deref(), fast.effort_level.as_str()), (Some("haiku"), "medium"));
+
+ // A pinned model of a known other tier gives way; one of the same tier stays
+ let pinned = with_tier(apply_preferred_model(laya(), "claude/opus"), Tier::Fast);
+ assert_eq!((pinned.selected_model.as_str(), model(&pinned).as_deref()), ("claude", Some("haiku")));
+ let same = with_tier(apply_preferred_model(laya(), "claude/haiku"), Tier::Fast);
+ assert_eq!(same.model.as_deref(), Some("haiku"));
+
+ // A model whose tier isn't known (a custom or local one) stays the bot's own
+ let custom = with_tier(apply_preferred_model(laya(), "custom/gpt-4.1"), Tier::Fast);
+ assert_eq!(custom.model.as_deref(), Some("gpt-4.1"));
+
+ // The deep tier keeps the effort Laya asked for; low effort is never raised
+ assert_eq!(with_tier(apply_preferred_model(laya(), "auto"), Tier::Deep).effort_level, "high");
+ let low = RouteDecision { effort_level: "low".into(), ..laya() };
+ assert_eq!(with_tier(apply_preferred_model(low, "auto"), Tier::Fast).effort_level, "low");
+}