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.

Audit: one approval card per challenge (#135)

Lin (kwant bot)21a04fed497c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2d00f4e3..a2ae3407 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -39,6 +39,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
model.
### Fixed
+- **One approval card per audit challenge.** When the auditor's call was allowed but then refused for
+ its input (usually the task's own id given as evidence), the bot's corrected call asked again, so one
+ challenge could need two cards. The corrected call now goes through on the first card (at most two
+ corrections per stage), and the task's own id is no longer refused as evidence.
- **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).
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 34566494..65290f53 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -173,6 +173,8 @@ POST /api/tasks {title, acceptance?, mission_id?, owner_kwant_id?, pr
checks?, source_kind?: "person"|"zombie", source_id?} -> Task
GET /api/tasks/:id -> TaskDetail
PATCH /api/tasks/:id {title?, acceptance?, priority?, owner_kwant_id?, budget_tokens?}
+ (`owner_kwant_id` on POST and PATCH is who should do it: it is stored as
+ `suggested_kwant_id`; the task's `owner_kwant_id` stays empty until that bot claims it)
POST /api/tasks/:id/verify {note?} -> Task (review -> verified, a `person` check)
POST /api/tasks/:id/reject {reason} -> Task (review -> ready)
POST /api/tasks/:id/block {reason} -> Task
@@ -709,11 +711,17 @@ challenges in the last 7 days, then name and id.
person; payments ask in every mode, D8), each capped at 20 minutes:
1. The challenger calls `audit_challenge {audit_id, risks: [{risk, evidence, evidence_ids?}]}` once:
- at most 5 risks, each with evidence (≤1000 chars); `evidence_ids` must be the task's. An empty list
+ at most 5 risks, each with evidence (≤1000 chars); `evidence_ids` must be ids of the task's evidence. An empty list
ends the audit `done` with "no risks raised". No call → the audit ends `failed`.
2. With risks, the owner calls `audit_rebut {audit_id, answers: [{risk_id, stance, answer, evidence?}]}`
once; `disputed` needs evidence. Unanswered risks stay `open`.
+**One card per call.** Each audit call asks the person once. If the person allows it and the tool then
+refuses its input (an evidence id that isn't the task's, a risk too long), the same bot's corrected
+call for that audit stage goes through without a new card, at most twice per stage; the tool checks it
+again as usual. The task's own id in `evidence_ids` is dropped rather than refused. Refused audit calls
+are logged with their reason.
+
While an audit of a task is `queued`, `challenge` or `rebuttal`, its challenger and owner can't use
`task_claim`, `task_update`, `task_attach_evidence`, `task_request_check` or `task_review` on it.
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 61714a85..d3cc8ed9 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -381,7 +381,12 @@ impl ToolApprover for SelfToolsApprover {
return self.inner.decide(req).await;
}
}
- if req.server == SELF_SERVER_NAME && (!self.always_ask || READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str())) {
+ // The corrected retry of an audit call the person allowed and the tool refused: one card
+ // for one challenge (see `auditor::take_retry`)
+ let free = !self.always_ask
+ || READ_ONLY_SELF_TOOLS.contains(&req.tool.as_str())
+ || super::missions::auditor::take_retry(&req.kwant_id, &req.tool, &req.arguments);
+ if req.server == SELF_SERVER_NAME && free {
// Flight School: a tier below act cards kwant's own tools that change things
if self.inner.tier_gate(&req).await.is_some() {
return self.inner.decide(req).await;
diff --git a/src/server/missions/auditor.rs b/src/server/missions/auditor.rs
index af7732c5..0e87ceb7 100644
--- a/src/server/missions/auditor.rs
+++ b/src/server/missions/auditor.rs
@@ -23,6 +23,7 @@ use axum::{
use chrono::{Duration, Utc};
use serde::Deserialize;
use serde_json::{json, Value};
+use std::collections::HashMap;
use std::sync::LazyLock;
pub const SETTING: &str = "auditor";
@@ -278,6 +279,7 @@ fn ended_without(stage: &str, err: Option<&str>) -> String {
}
async fn finish(state: &AppState, audit: &Audit) {
+ drop_retries(&audit.id);
let Ok(Some(a)) = state.db.get_audit(&audit.id).await else { return };
let risks = state.db.risks_of_audit(&a.id).await.unwrap_or_default();
let unresolved = risks.iter().filter(|r| r.unresolved()).count();
@@ -345,7 +347,7 @@ async fn challenge_prompt(state: &AppState, audit: &Audit, task: &Task, owner: &
Look for concrete reasons it may not meet its acceptance: wrong, missing, unsafe or unverifiable. \
Read what you need, but change nothing. Then call audit_challenge once with audit_id {aid} and at \
most {max} risks. Each risk needs `evidence`: what you looked at and what you saw (put ids from the \
- list above in evidence_ids when they apply). If you find no real risk, call it with an empty risks \
+ evidence list above in evidence_ids when they apply; the task's own id is not an evidence id). If you find no real risk, call it with an empty risks \
list. Don't invent risks to have something to say.",
tid = task.id,
title = task.title,
@@ -405,7 +407,7 @@ pub fn tools() -> Vec<Value> {
"properties": {
"risk": {"type": "string", "description": "What may be wrong, in a sentence."},
"evidence": {"type": "string", "description": "What you looked at and what you saw."},
- "evidence_ids": {"type": "array", "items": {"type": "string"}, "description": "Ids of the task's evidence this rests on."},
+ "evidence_ids": {"type": "array", "items": {"type": "string"}, "description": "Ids from the task's evidence list this rests on (not the task id). Leave it out when none apply."},
},
"required": ["risk", "evidence"],
},
@@ -481,13 +483,77 @@ pub async fn call(state: &AppState, scope: &SelfScope, name: &str, args: &Value)
}) else {
return fail("No such audit.");
};
- match name {
+ let res = match name {
"audit_challenge" => challenge(state, scope, &audit, args).await,
"audit_rebut" => rebut(state, scope, &audit, args).await,
_ => fail(format!("Unknown tool {name}.")),
+ };
+ if res.1 {
+ tracing::info!(audit_id = %audit.id, kwant = %scope.kwant_id, tool = name, reason = %res.0, "audit call refused");
+ // Refused input from the stage's own bot: its corrected call doesn't ask again
+ if let Ok(Some(a)) = state.db.get_audit(&audit.id).await {
+ if waits_on(&a, name, &scope.kwant_id) {
+ arm_retry(&scope.kwant_id, &a.id, name);
+ }
+ }
+ }
+ res
+}
+
+/// Whether `audit` is waiting for `tool` from `kwant_id`.
+fn waits_on(audit: &Audit, tool: &str, kwant_id: &str) -> bool {
+ match tool {
+ "audit_challenge" => audit.status == "challenge" && audit.challenger_kwant_id == kwant_id,
+ "audit_rebut" => audit.status == "rebuttal" && audit.owner_kwant_id == kwant_id,
+ _ => false,
}
}
+/// How many corrected calls a stage may make without a new card.
+const RETRIES: u8 = 2;
+
+#[derive(Default)]
+struct Retry {
+ armed: bool,
+ left: u8,
+}
+
+/// One challenge, one card: the person allows the audit call, and if the tool then refuses its
+/// input (an evidence id that isn't the task's, a risk too long), the bot's corrected call goes
+/// through without a second card. At most [`RETRIES`] per stage; the tool checks the call again
+/// as usual. Keyed by (bot, audit, tool); dropped when the audit ends.
+static RETRY_PASSES: LazyLock<std::sync::Mutex<HashMap<RetryKey, Retry>>> = LazyLock::new(Default::default);
+
+/// (bot, audit, tool).
+type RetryKey = (String, String, String);
+
+fn arm_retry(kwant_id: &str, audit_id: &str, tool: &str) {
+ let mut passes = RETRY_PASSES.lock().unwrap_or_else(|e| e.into_inner());
+ let r = passes.entry((kwant_id.into(), audit_id.into(), tool.into())).or_insert(Retry { armed: false, left: RETRIES });
+ r.armed = r.left > 0;
+}
+
+/// Uses the retry pass for this call, if a refused call of the same audit stage left one.
+pub fn take_retry(kwant_id: &str, tool: &str, args: &Value) -> bool {
+ let Some(audit_id) = args["audit_id"].as_str() else { return false };
+ if !TOOL_NAMES.contains(&tool) {
+ return false;
+ }
+ let mut passes = RETRY_PASSES.lock().unwrap_or_else(|e| e.into_inner());
+ match passes.get_mut(&(kwant_id.to_string(), audit_id.to_string(), tool.to_string())) {
+ Some(r) if r.armed => {
+ r.armed = false;
+ r.left -= 1;
+ true
+ }
+ _ => false,
+ }
+}
+
+fn drop_retries(audit_id: &str) {
+ RETRY_PASSES.lock().unwrap_or_else(|e| e.into_inner()).retain(|(_, a, _), _| a != audit_id);
+}
+
async fn challenge(state: &AppState, scope: &SelfScope, audit: &Audit, args: &Value) -> ToolResult {
if audit.challenger_kwant_id != scope.kwant_id {
return fail("You aren't this audit's challenger.");
@@ -511,9 +577,13 @@ async fn challenge(state: &AppState, scope: &SelfScope, audit: &Audit, args: &Va
Ok(s) => s,
Err(e) => return fail(format!("risk {n}: evidence {e}; say what you looked at and what you saw.")),
};
- let ids: Vec<String> = r["evidence_ids"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect()).unwrap_or_default();
+ // The task's own id names no evidence: dropped rather than refused
+ let ids: Vec<String> = r["evidence_ids"]
+ .as_array()
+ .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).filter(|id| *id != audit.task_id).collect())
+ .unwrap_or_default();
if let Some(bad) = ids.iter().find(|id| !on_task.contains(id)) {
- return fail(format!("risk {n}: evidence id {bad} isn't on this task."));
+ return fail(format!("risk {n}: evidence id {bad} isn't one of the task's evidence ids; leave it out or use an id from the evidence list."));
}
risks.push(NewRisk { risk, evidence, evidence_ids: ids });
}
diff --git a/tests/auditor_test.rs b/tests/auditor_test.rs
index 474fbb5b..c7176a16 100644
--- a/tests/auditor_test.rs
+++ b/tests/auditor_test.rs
@@ -20,13 +20,14 @@ use kwnt::{
},
router::LayaRouter,
server::{
- continuity::{SelfScope, TurnOrigin},
+ continuity::{SelfScope, SelfToolsApprover, TurnOrigin},
create_router, mcp_runtime,
missions::auditor,
AppState,
},
tools::ToolRunner,
};
+use kwnt::mcp::{FixedApprover, ToolApprovalRequest, ToolApprover, SELF_SERVER_NAME};
use serde_json::{json, Value};
use std::time::Duration;
use tempfile::{tempdir, TempDir};
@@ -413,7 +414,7 @@ async fn a_challenge_needs_evidence_and_only_the_challenger_gives_it() {
assert!(err && text.contains("At most 5"), "{text}");
let foreign = json!({"audit_id": a.id, "risks": [{"risk": "r", "evidence": "e", "evidence_ids": ["nope"]}]});
let (_, err, text) = tool(&e, &challenger, "audit_challenge", foreign).await;
- assert!(err && text.contains("isn't on this task"), "{text}");
+ assert!(err && text.contains("isn't one of the task's evidence ids"), "{text}");
// Mid-audit, neither side can review, update or add checks to the task
for (who, name, args) in [
@@ -718,3 +719,93 @@ async fn an_audit_whose_driver_stopped_ends_failed() {
assert_eq!(verification(&e, &t.id).await, before);
assert!(auditor::held(&e.state, &owner.id, "task_update", &t).await.is_none());
}
+
+/// Whether an always-ask audit turn lets `bot`'s call through without a card (the inner approver
+/// stands for the card and says no).
+async fn free_in_audit_turn(bot: &Kwant, tool: &str, args: Value) -> bool {
+ let approver = SelfToolsApprover { inner: std::sync::Arc::new(FixedApprover(false)), always_ask: true, browser: None };
+ let req = ToolApprovalRequest {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ turn_id: "t".into(),
+ tool_name: format!("mcp__{SELF_SERVER_NAME}__{tool}"),
+ server: SELF_SERVER_NAME.into(),
+ tool: tool.into(),
+ arguments: args,
+ builtin: None,
+ smart: None,
+ payment: None,
+ };
+ approver.approve(req).await
+}
+
+#[tokio::test]
+async fn one_challenge_is_one_card() {
+ let e = setup().await;
+ let owner = bot(&e, "Owner").await;
+ auditor_on(&e, 5).await;
+ let t = task(&e, Some(&owner), 2, "review").await;
+ person_check(&e, &t).await;
+ let a = open_audit(&e, &t).await;
+ let challenger = e.state.db.get_kwant(&a.challenger_kwant_id).await.unwrap().unwrap();
+ let call_args = json!({"audit_id": a.id, "risks": []});
+
+ // The first call asks the person
+ assert!(!free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await);
+
+ // Allowed, then refused for its input (live: the task's id given as an evidence id): the
+ // corrected call doesn't ask again, once per refusal
+ let bad = json!({"audit_id": a.id, "risks": [{"risk": "r", "evidence": "e", "evidence_ids": ["nope"]}]});
+ let (_, err, _) = tool(&e, &challenger, "audit_challenge", bad.clone()).await;
+ assert!(err);
+ for (who, name, args) in [
+ (&owner, "audit_challenge", call_args.clone()),
+ (&challenger, "audit_rebut", json!({"audit_id": a.id, "answers": []})),
+ (&challenger, "audit_challenge", json!({"audit_id": "other", "risks": []})),
+ (&challenger, "memory_add", json!({"audit_id": a.id, "text": "x"})),
+ ] {
+ assert!(!free_in_audit_turn(who, name, args).await, "{name} by {} still asks", who.name);
+ }
+ assert!(free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await);
+ assert!(!free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await, "one pass per refusal");
+
+ // At most two corrections without a card in a stage
+ let (_, err, _) = tool(&e, &challenger, "audit_challenge", bad.clone()).await;
+ assert!(err);
+ assert!(free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await);
+ let (_, err, _) = tool(&e, &challenger, "audit_challenge", bad).await;
+ assert!(err);
+ assert!(!free_in_audit_turn(&challenger, "audit_challenge", call_args.clone()).await, "a third try asks");
+
+ // A refusal by someone the audit isn't waiting on leaves nothing behind
+ let (_, err, _) = tool(&e, &owner, "audit_challenge", call_args.clone()).await;
+ assert!(err);
+ assert!(!free_in_audit_turn(&owner, "audit_challenge", call_args).await);
+
+ // The task's own id among the evidence ids is dropped, not refused
+ let own = json!({"audit_id": a.id, "risks": [{"risk": "No export attached", "evidence": "The brief lists no evidence.", "evidence_ids": [t.id]}]});
+ let (v, err, text) = tool(&e, &challenger, "audit_challenge", own).await;
+ assert!(!err, "{text}");
+ assert_eq!(v["risks"].as_array().unwrap().len(), 1);
+ let risks = e.state.db.risks_of_audit(&a.id).await.unwrap();
+ assert!(risks[0].evidence_ids().is_empty());
+
+ // The owner's rebuttal: same rule
+ let rebut = json!({"audit_id": a.id, "answers": []});
+ assert!(!free_in_audit_turn(&owner, "audit_rebut", rebut.clone()).await);
+ let (_, err, _) = tool(&e, &owner, "audit_rebut", json!({"audit_id": a.id, "answers": [{"risk_id": "nope", "stance": "accepted", "answer": "ok"}]})).await;
+ assert!(err);
+ assert!(free_in_audit_turn(&owner, "audit_rebut", rebut).await);
+}
+
+#[tokio::test]
+async fn a_person_assigned_owner_is_a_suggestion_until_the_claim() {
+ let e = setup().await;
+ let owner = bot(&e, "Owner").await;
+ auditor_on(&e, 5).await;
+ let t = person(&e, "POST", "/api/tasks", Some(json!({"title": "Export orders", "owner_kwant_id": owner.id, "priority": 2}))).await;
+ assert_eq!((t["owner_kwant_id"].as_str(), t["suggested_kwant_id"].as_str()), (None, Some(owner.id.as_str())), "{t}");
+ // No owner yet, so nobody to answer an audit
+ let task = e.state.db.get_task(t["id"].as_str().unwrap()).await.unwrap().unwrap();
+ assert!(auditor::start(&e.state, &task, "manual").await.is_err());
+}