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.

The delegating lead reviews finished hand-offs (#141)

Lin (kwant bot)caac2367cd1c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c95827ab..2122bd2c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -68,6 +68,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
opened it on its own. Before a turn the browser now opens only a full `http://` or `https://` link in
the message, and a reply never moves it. A file path or `file://` address given to the browser is
refused with a note to read local files with file tools.
+- **Hand-off cards no longer pile up in Review.** When a teammate finishes a hand-off, the bot that
+ handed it out reviews the result in its next reply: a pass verifies the card, a fail sends the work
+ back to the teammate with the reason. Only that bot's review counts (the teammate still can't approve
+ its own work), and until it reviews, the card says "Waiting for <bot> to review". A bot that doesn't
+ review gets one reminder (one for all the cards of a batch); a card it never got to see (one blocked when the hand-off finished, or one
+ caught by a restart) gets its own review turn. A one-way hand-off, whose result nobody is asked about,
+ is closed ("Notice, no review needed", shown as Closed, not Verified) instead of waiting in Review. Each hand-off's card
+ is named after what was asked of that teammate, not after your message, so two hand-offs to one bot
+ no longer look like duplicates.
- **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 f9031b98..258008c8 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -633,6 +633,22 @@ A card still over its own token limit is blocked again (`blocked_reason` `budget
- A hand-off cut short by two restarts (`interrupted`) fails its card (AutoFix records it as a
`handoff` error) instead of returning it to Ready.
+### Every card in Review gets a lead review
+
+A finished hand-off's card goes to `review` with the result as evidence, and only its lead's
+`task_review` (or the person) settles it. Each time the lead is asked, a `lead_review_asked` task
+event is logged; per stay in Review it's asked at most `listener::MAX_REVIEW_ASKS` (2) times:
+
+| Path | How the lead is asked |
+| --- | --- |
+| batch results turn (also carry-ons, review send-backs, late answers, channel @mention hand-offs) | its results prompt names every card of the batch; if the turn ends with cards still unreviewed, one reminder turn lists all of them |
+| the card was blocked when the hand-off finished, then unblocked | `delegation::spawn_review_turn` right after it moves to `review`, plus the one reminder |
+| kwnt restarted before or during the lead's turn, or a turn was lost | `listener::sweep_unreviewed` (from reconcile): a card quiet for `REVIEW_GRACE` (2 min) with no turn or batch running gets a review turn |
+| `continue_lead: false` (a one-way notice; nobody is resumed with its result) | never put in Review: the card is closed (`cancelled`, never `verified`) with reason `listener::NOTICE_CLOSED` ("Notice, no review needed"); `task_json` gives it as `closed_note`, and the board labels it "Closed" |
+
+After both asks the card waits, "Waiting for <lead> to review", for the lead or the person. Cards
+from before this change (no result evidence) and cards whose lead was deleted are left for the person.
+
### Capped hand-offs: the Continue notice
One person message starts at most `routes::MAX_DELEGATIONS_PER_REQUEST` (16) hand-offs by mention,
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index c3c1e5c9..bda23b00 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -116,6 +116,7 @@ import {
type ChatPlace,
sourceLabel,
stateLabel,
+ taskStateLabel,
untilText,
upsertMission,
upsertTask,
@@ -1507,7 +1508,7 @@ export const TaskDetailBody: React.FC<{
const [reason, setReason] = useState('');
const reasonId = useId();
const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
- const st = stateLabel(t.state);
+ const st = taskStateLabel(t);
// Unblocking without a new limit would stop it again at once.
const actions = actionsFor(t).filter((a) => !(limitHit && a === 'unblock'));
const chat = sourceChat(t);
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index d20206ac..6156893e 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -110,6 +110,11 @@ export interface Task extends TaskTier {
checks_summary: ChecksSummary;
/** The task this one redoes (a fork); older servers leave it out. */
forked_from?: string | null;
+ /** Who reviews a hand-off's result: the bot that handed it out. Older servers leave it out. */
+ reviewer?: { kwant_id: string; name: string | null } | null;
+ /** Set when a one-way hand-off's card was closed without review ("Notice, no review needed"):
+ * it reads as Closed, not Cancelled. Older servers leave it out. */
+ closed_note?: string | null;
/** Set when a restore held the task: nothing claims it until `POST /api/tasks/:id/run`
* (the person's Run). Older servers leave it out. */
held_at?: string | null;
@@ -503,6 +508,14 @@ export const STATE_LABELS: Record<TaskState, { label: string; tone: Tone }> = {
export const stateLabel = (s: string): { label: string; tone: Tone } => STATE_LABELS[s as TaskState] ?? { label: humanize(s), tone: 'zinc' };
+/** The note a one-way hand-off's card is closed with: nothing to review, so not Cancelled but Closed. */
+export const NOTICE_CLOSED_NOTE = 'Notice, no review needed';
+const CLOSED = { label: 'Closed', tone: 'zinc' as Tone };
+
+/** A task's state label: a closed notice reads "Closed", everything else as its state. */
+export const taskStateLabel = (t: Pick<Task, 'state' | 'closed_note'>): { label: string; tone: Tone } =>
+ t.state === 'cancelled' && t.closed_note ? CLOSED : stateLabel(t.state);
+
export const PRIORITY_LABELS = ['Low', 'Normal', 'High', 'Urgent'];
export const priorityLabel = (p: number): string => PRIORITY_LABELS[Math.max(0, Math.min(3, Math.round(p)))] ?? 'Normal';
@@ -701,7 +714,9 @@ export function cardStatus(t: Task, names: Record<string, string> = {}, now: num
return t.needs_you[0]?.text ?? 'A bot is waiting for you';
case 'review':
if (approvalHolds(t.checks_summary)) return waitingApprovalText(t.checks_summary.required_needs_approval);
- if (t.checks_summary.status === 'not_checked') return 'Bot says done. Not checked yet';
+ if (t.checks_summary.status === 'not_checked') {
+ return t.reviewer?.name ? `Waiting for ${t.reviewer.name} to review` : 'Bot says done. Not checked yet';
+ }
// While a required check runs the card reads as checking; the grey note covers optional ones.
if (t.checks_summary.status === 'pending') return 'Bot says done. Checking';
return optionalWaitingText(optionalWaitingCount(t.checks_summary)) ?? 'Bot says done. Checking';
@@ -1312,6 +1327,7 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
case 'created':
return `${Who} added this task`;
case 'state':
+ if (e.to_state === 'cancelled' && note === NOTICE_CLOSED_NOTE) return `${Who} closed it: ${note}`;
return `${Who} moved it to ${stateLabel(e.to_state ?? '').label}${note ? `: ${note}` : ''}`;
case 'claimed':
return `${Who} took it on`;
diff --git a/frontend/tests/missions.test.mjs b/frontend/tests/missions.test.mjs
index f3ecb85f..fb05122f 100644
--- a/frontend/tests/missions.test.mjs
+++ b/frontend/tests/missions.test.mjs
@@ -97,6 +97,10 @@ test('a card shows owner, cost and an honest check chip', () => {
assert.match(html, /12\.4k of 50k tokens/);
assert.match(html, /Not checked/);
assert.match(html, /Bot says done\. Not checked yet/);
+ // A hand-off's card names the bot that handed it out, which reviews it
+ const handoff = ui.card({ task: task({ state: 'review', source_kind: 'delegation', reviewer: { kwant_id: 'k_ada', name: 'Architect' } }), names, now: NOW, onOpen: noop });
+ assert.match(handoff, /Waiting for Architect to review/);
+ assert.doesNotMatch(handoff, /Not checked yet/);
const working = ui.card({ task: task({ state: 'working', claim: { kwant_id: 'k_lin', claimed_at: '2026-10-27T11:50:00Z', expires_at: '2026-10-27T12:20:00Z' } }), names, now: NOW, onOpen: noop });
assert.match(working, /Lin started 10 min ago/);
const asks = ui.card({ task: task({ state: 'needs_you', needs_you: [{ kind: 'approval', id: 'a1', text: 'OK to publish the page?' }] }), names, now: NOW, onOpen: noop });
@@ -497,3 +501,12 @@ test('errors read plainly', () => {
assert.match(m.errorFrom(404, null).message, /doesn’t have the Mission board/);
assert.equal(m.errorFrom(400, { error: 'reason is required' }).message, 'Reason is required.');
});
+
+test('a one-way hand-off closed without review reads as Closed, not Cancelled', () => {
+ assert.deepEqual(m.taskStateLabel({ state: 'cancelled', closed_note: m.NOTICE_CLOSED_NOTE }), { label: 'Closed', tone: 'zinc' });
+ assert.equal(m.taskStateLabel({ state: 'cancelled' }).label, 'Cancelled');
+ assert.equal(m.taskStateLabel({ state: 'review', closed_note: null }).label, 'Review');
+ const ev = (reason) => ({ id: 1, task_id: 't1', mission_id: null, kind: 'state', actor: 'kwant', actor_name: null, from_state: 'working', to_state: 'cancelled', detail: { reason }, created_at: '' });
+ assert.equal(m.eventText(ev('Notice, no review needed')), 'Kwant closed it: Notice, no review needed');
+ assert.match(m.eventText(ev('the person stopped it')), /moved it to Cancelled: the person stopped it/);
+});
diff --git a/src/db/threads.rs b/src/db/threads.rs
index b05127e6..60fb910d 100644
--- a/src/db/threads.rs
+++ b/src/db/threads.rs
@@ -435,6 +435,18 @@ impl Database {
Ok(res.rows_affected() > 0)
}
+ /// Opens a completed delegation again because its lead's review sent it back.
+ pub async fn reopen_reviewed_delegation(&self, id: &str) -> Result<bool, DbError> {
+ let res = sqlx::query(
+ "UPDATE delegations SET status = 'queued', error = NULL, result_message_id = NULL, ended_at = NULL, started_at = NULL, retries = 0, followed_up = 1 \
+ WHERE id = ? AND status = 'completed'",
+ )
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected() > 0)
+ }
+
/// Parks a queued delegation until `after` (another delegation) ends.
pub async fn set_delegation_after(&self, id: &str, after: &str) -> Result<(), DbError> {
sqlx::query("UPDATE delegations SET after_delegation_id = ? WHERE id = ? AND status = 'queued'")
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 64aebd40..b56e575e 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -448,8 +448,8 @@ pub(super) fn is_parked(d: &Delegation) -> bool {
/// The background part: the specialist's turn in the thread, then the report in the origin chat.
async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead: Kwant, specialist: Kwant, how: RunAs) {
- let RunAs { retried, after_restart, carry_on } = how;
- let carried_on = carry_on.is_some();
+ let RunAs { retried, after_restart, carry_on, sent_back } = how;
+ let carried_on = carry_on.is_some() || sent_back.is_some();
let scope = match scope_for(&state, &specialist, None, Some(d.thread_id.clone()), &job, d.depth).await {
Ok(s) => s,
Err(why) => return finish(&state, &d, &specialist, Err(why), carried_on).await,
@@ -463,8 +463,16 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
}
}
});
- let opening = match &carry_on {
- Some(why) => format!(
+ let opening = match (&carry_on, &sent_back) {
+ (_, Some(note)) => format!(
+ "{lead} reviewed the result you gave for this task and sent it back: {note}\n\nFix exactly that. Your earlier \
+ work is above in this thread, so build on it instead of starting over, and don't repeat a step that can't be undone \
+ (sending, posting, deleting, paying). When you finish, your reply is posted back to {lead} and the chat it came \
+ from, so make it a complete, self-contained answer.",
+ lead = lead.name,
+ note = clip(note, 1000),
+ ),
+ (Some(why), _) => format!(
"{lead} delegated this task to you earlier, and it stopped before it was done ({why}). The person sent it \
back to you: carry on from where you stopped. Your earlier work is above in this thread, so check what is \
already done instead of starting over, and don't repeat a step that can't be undone (sending, posting, deleting, \
@@ -473,7 +481,7 @@ async fn run(state: AppState, job: super::turns::JobGuard, d: Delegation, lead:
lead = lead.name,
why = clip(why, 300),
),
- None => format!(
+ (None, None) => format!(
"{lead} delegated this task to you. Work on it here; when you finish, your reply is posted back to {lead} \
and the chat it came from, so make it a complete, self-contained answer.",
lead = lead.name,
@@ -531,6 +539,8 @@ struct RunAs {
/// The person sent an ended task back (unblocked or retried its board card): why it stopped.
/// The specialist carries on in its thread, and the lead hears the new result on its own.
carry_on: Option<String>,
+ /// The lead's review sent the finished task back: its note. Reported like a carry-on.
+ sent_back: Option<String>,
}
/// Most of the person's request, and of the origin chat's instructions, a delegated task quotes.
@@ -673,7 +683,7 @@ async fn finish(state: &AppState, d: &Delegation, specialist: &Kwant, outcome: R
}
// Its batch already went to the lead: this result goes on its own (a stop was the person's)
if done.continue_lead && status != "cancelled" {
- let opening = format!("{} carried on with the task you delegated (“{}”) after the person sent it back.", specialist.name, done.title);
+ let opening = format!("{} carried on with the task you delegated (“{}”) after it was sent back.", specialist.name, done.title);
continue_lead(state, &done, std::slice::from_ref(&done), Some(opening)).await;
}
}
@@ -843,7 +853,8 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
return;
};
let context = d.origin_context().unwrap_or(&lead.id).to_string();
- let job = state.turns.start_job([context, d.id.clone()]);
+ // Every hand-off of the batch is busy while its lead looks at it (see `sweep_unreviewed`)
+ let job = state.turns.start_job(std::iter::once(context).chain(batch.iter().map(|b| b.id.clone())).chain([d.id.clone()]));
let Ok(scope) = scope_for(state, &lead, d.origin_channel_id.clone(), d.origin_thread_id.clone(), &job, d.depth - 1).await else {
return;
};
@@ -863,6 +874,10 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
clip(&q.question, 200)
));
}
+ if let Some(review) = super::missions::listener::lead_review_note(state, b, &who).await {
+ results.push_str(&review);
+ results.push('\n');
+ }
if let Some(next) = status_guidance(&b.status) {
results.push_str(next);
results.push('\n');
@@ -901,7 +916,10 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
// The follow-up may hand on by @mention, like any lead reply: to the next teammate, or back to
// one that just reported with a correction (not a mention that only credits it), within the
// usual limits.
- if let Ok(reply) = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await {
+ let outcome = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await;
+ // Cards the lead was asked to review and didn't: one reminder for all of them (a failed turn counts too)
+ remind_review(state, batch).await;
+ if let Ok(reply) = outcome {
let mut spoken = vec![lead.id.clone()];
spoken.extend(batch.iter().map(|b| b.specialist_kwant_id.clone()));
let user_prompt = state
@@ -920,6 +938,93 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
}
}
+/// Whether another hand-off of `d`'s batch (same lead and chat, reporting back) is still open:
+/// the lead then hears about `d` with the whole batch, so nothing asks it about `d` alone.
+pub async fn batch_running(state: &AppState, d: &Delegation) -> bool {
+ state
+ .db
+ .list_delegations(Some(&d.lead_kwant_id), None, 50)
+ .await
+ .unwrap_or_default()
+ .iter()
+ .any(|s| s.id != d.id && s.continue_lead && s.origin_context() == d.origin_context() && !is_parked(s) && s.is_open())
+}
+
+/// After the lead's results turn: the cards of `batch` still in Review that the lead was asked
+/// about only once get one reminder turn now, together. Past that a card waits for the lead or
+/// the person.
+async fn remind_review(state: &AppState, batch: &[Delegation]) {
+ let mut due = Vec::new();
+ for d in batch.iter().filter(|d| d.status == "completed") {
+ let Ok(Some(t)) = state.db.task_by_source("delegation", &d.id).await else { continue };
+ let (asks, _) = super::missions::listener::review_asks(state, &t.id).await;
+ if asks > 0 && super::missions::listener::wants_lead_review(state, &t).await {
+ tracing::info!(delegation = %d.id, task_id = %t.id, "the lead didn't review a hand-off card: reminding it once");
+ due.push(d.clone());
+ }
+ }
+ if !due.is_empty() {
+ review_turn(state, &due, true).await;
+ }
+}
+
+/// [`review_turn`] in the background. The job is registered first, so a sweep in between sees
+/// the hand-off as busy and doesn't start a second one.
+pub fn spawn_review_turn(state: &AppState, d: &Delegation, reminder: bool) {
+ let state = state.clone();
+ let d = d.clone();
+ let job = state.turns.start_job([format!("review:{}", d.id), d.id.clone()]);
+ tokio::spawn(async move {
+ let one = std::slice::from_ref(&d);
+ review_turn(&state, one, reminder).await;
+ if !reminder {
+ remind_review(&state, one).await;
+ }
+ drop(job);
+ });
+}
+
+/// A turn for the lead of `batch` (hand-offs of one lead and chat) in the chat they came from,
+/// only to review their cards, all in one prompt: for a card whose lead wasn't resumed with the
+/// result (the card was blocked when the batch reported, or kwnt restarted before the lead's
+/// turn), and as the one reminder. Cards no longer waiting in Review are left out; nothing runs
+/// when none is.
+pub async fn review_turn(state: &AppState, batch: &[Delegation], reminder: bool) {
+ let Some(d) = batch.first() else { return };
+ let Ok(Some(lead)) = state.db.get_kwant(&d.lead_kwant_id).await else { return };
+ let context = d.origin_context().unwrap_or(&lead.id).to_string();
+ let job = state.turns.start_job(std::iter::once(context).chain(batch.iter().map(|b| b.id.clone())));
+ let Ok(scope) = scope_for(state, &lead, d.origin_channel_id.clone(), d.origin_thread_id.clone(), &job, d.depth - 1).await else {
+ return;
+ };
+ let mut cards = String::new();
+ let mut titles = Vec::new();
+ for b in batch {
+ let who = name_of(state, &b.specialist_kwant_id).await;
+ // Logs the ask, so it counts towards the limit even if the turn below fails
+ let Some(note) = super::missions::listener::lead_review_note(state, b, &who).await else { continue };
+ let result = clip(&result_of(state, b).await, 3000);
+ cards.push_str(&format!("{who}'s result on “{}”:\n\n{}\n\n{note}\n\n", b.title, crate::drivers::peer_message(&who, &result)));
+ titles.push(format!("“{}”", b.title));
+ }
+ if titles.is_empty() {
+ return;
+ }
+ let opening = match (reminder, titles.len()) {
+ (true, 1) => format!("Reminder: the result on {} is still waiting for your review on the board.", titles[0]),
+ (true, _) => format!("Reminder: these {} results are still waiting for your review on the board.", titles.len()),
+ (false, 1) => format!("A task you handed out ({}) is finished, and its card is waiting for your review.", titles[0]),
+ (false, _) => format!("{} tasks you handed out are finished, and their cards are waiting for your review.", titles.len()),
+ };
+ let prompt = format!(
+ "{opening}\n\n{cards}Review each one now with task_review. Then reply with one short line for the chat: what you \
+ decided and why. Don't hand anything on by @mention in this reply."
+ );
+ if let Err(e) = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await {
+ tracing::info!(delegation = %d.id, error = %e, "a lead review turn failed");
+ }
+}
+
/// How a lead hands work on from its results follow-up, so it never announces a handoff that
/// doesn't happen (Oleks's screenshot, 2026-10-24: "Handing off now: @Social …" and nothing ran).
pub fn handoff_rules() -> String {
@@ -1110,7 +1215,7 @@ async fn restart(state: &AppState, d: Delegation, retried: bool, after_restart:
};
let job = state.turns.start_job([d.id.clone(), d.thread_id.clone()]);
tracing::info!(delegation = %d.id, retried, "delegation restarted");
- tokio::spawn(run(state.clone(), job, d, lead, specialist, RunAs { retried, after_restart, carry_on: None }));
+ tokio::spawn(run(state.clone(), job, d, lead, specialist, RunAs { retried, after_restart, ..Default::default() }));
true
}
@@ -1149,6 +1254,39 @@ pub async fn carry_on(state: &AppState, d: &Delegation) -> bool {
true
}
+/// The lead's review failed a finished hand-off (its card went from review back to Ready): the
+/// specialist fixes it in the hand-off's own thread with the review's `note`, and the new result
+/// goes to the origin chat and the lead, whose review comes again. `false` when it can't (a bot
+/// is gone, or another call reopened it first).
+pub async fn send_back(state: &AppState, d: &Delegation, note: &str) -> bool {
+ if d.status != "completed" {
+ return false;
+ }
+ let (Ok(Some(lead)), Ok(Some(specialist))) =
+ (state.db.get_kwant(&d.lead_kwant_id).await, state.db.get_kwant(&d.specialist_kwant_id).await)
+ else {
+ return false;
+ };
+ if !state.db.reopen_reviewed_delegation(&d.id).await.unwrap_or(false) {
+ return false;
+ }
+ let Ok(Some(open)) = state.db.get_delegation(&d.id).await else { return false };
+ emit_delegation(state, &open);
+ post_to_origin(
+ state,
+ &open,
+ "system",
+ "kwnt",
+ format!("{} sent “{}” back to {}: {}", lead.name, open.title, specialist.name, clip(note, 300)),
+ meta("delegation_started", &open, &specialist.name),
+ )
+ .await;
+ let job = state.turns.start_job([open.id.clone(), open.thread_id.clone()]);
+ tracing::info!(delegation = %open.id, "delegation sent back by its review");
+ tokio::spawn(run(state.clone(), job, open, lead, specialist, RunAs { sent_back: Some(note.to_string()), ..Default::default() }));
+ true
+}
+
// Routes
/// `GET /api/turns?space=`: the turns running for that space's kwants. The limits are app-wide.
diff --git a/src/server/missions/listener.rs b/src/server/missions/listener.rs
index 6eb05483..6ad74329 100644
--- a/src/server/missions/listener.rs
+++ b/src/server/missions/listener.rs
@@ -78,6 +78,7 @@ pub async fn reconcile(state: &AppState) {
}
}
refresh_needs_you(state).await;
+ sweep_unreviewed(state, REVIEW_GRACE).await;
}
/// The mission a bot's own open claim is in, so a hand-off it starts joins that mission.
@@ -237,10 +238,26 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
return;
}
if status == "completed" {
+ // The lead's review failed it: the teammate fixes it in the hand-off's thread
+ if let Some(note) = sent_back_by_review(state, &t).await {
+ if !crate::server::delegation::send_back(state, &d, &note).await {
+ let change = TaskChange { reason: Some(CANT_CARRY_ON.into()), ..Default::default() };
+ let _ = transition(state, &t.id, "ready", "blocked", Actor::Kwant, "kwant", change).await;
+ }
+ return;
+ }
// It finished while the card was blocked: its result is in, so it goes to review
hold(state, &t, &d.specialist_kwant_id, &d.thread_id).await;
if let Ok(Some(t)) = state.db.get_task(&t.id).await {
- finish(state, &t, "review", "the hand-off had finished").await;
+ if !d.continue_lead {
+ finish(state, &t, "cancelled", NOTICE_CLOSED).await;
+ return;
+ }
+ attach_result(state, &t, &d).await;
+ // The lead's results turn ran while the card was blocked, so it never saw the card
+ if finish(state, &t, "review", "the hand-off had finished").await {
+ crate::server::delegation::spawn_review_turn(state, &d, false);
+ }
}
} else if !crate::server::delegation::carry_on(state, &d).await {
let change = TaskChange { reason: Some(CANT_CARRY_ON.into()), ..Default::default() };
@@ -260,7 +277,12 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
super::emit_task(state, &t).await;
}
}
+ // A one-way hand-off: nobody is resumed with its result, so nobody would review it
+ (Some(t), "completed") if !d.continue_lead => {
+ finish(state, &t, "cancelled", NOTICE_CLOSED).await;
+ }
(Some(t), "completed") => {
+ attach_result(state, &t, &d).await;
finish(state, &t, "review", "the hand-off finished").await;
}
(Some(t), "failed") => {
@@ -284,6 +306,150 @@ pub async fn on_delegation(state: &AppState, delegation_id: &str) {
}
}
+/// Label of the evidence that carries a hand-off's result (see [`attach_result`]).
+pub const RESULT_LABEL: &str = "Hand-off result";
+
+/// The finished hand-off's reply as note evidence on its card, once per finish, so the lead's
+/// review can cite it (a pass needs evidence; evidence alone never verifies).
+async fn attach_result(state: &AppState, task: &Task, d: &crate::db::threads::Delegation) {
+ if !matches!(task.state.as_str(), "working" | "needs_you") {
+ return;
+ }
+ let run = format!("{}@{}", d.id, d.ended_at.map(|t| t.timestamp_millis()).unwrap_or_default());
+ let on_task = state.db.list_evidence(&task.id).await.unwrap_or_default();
+ if on_task.iter().any(|e| e.run_id.as_deref() == Some(run.as_str())) {
+ return;
+ }
+ let text = match &d.result_message_id {
+ Some(m) => state.db.get_message(m).await.ok().flatten().map(|m| m.text),
+ None => None,
+ };
+ let e = crate::db::missions::NewEvidence {
+ task_id: task.id.clone(),
+ kind: "note".into(),
+ label: RESULT_LABEL.into(),
+ excerpt: Some(text.unwrap_or_else(|| "(The result is in the hand-off's thread.)".into()).chars().take(super::MAX_EXCERPT).collect()),
+ captured_by: d.specialist_kwant_id.clone(),
+ run_id: Some(run),
+ ..Default::default()
+ };
+ if let Err(err) = state.db.add_evidence(&e).await {
+ tracing::warn!(error = %err, task_id = %task.id, "could not attach a hand-off's result");
+ }
+}
+
+/// The note of the review that sent `task` from review back to Ready, if that was its last move.
+pub async fn sent_back_by_review(state: &AppState, task: &Task) -> Option<String> {
+ let events = state.db.task_events(&task.id, 500).await.ok()?;
+ let last = events.iter().rev().find(|e| e.to_state.is_some())?;
+ if last.from_state.as_deref() != Some("review") || last.to_state.as_deref() != Some("ready") {
+ return None;
+ }
+ let since = super::review_since(state, &task.id).await;
+ let checks = state.db.list_checks(&task.id).await.ok()?;
+ checks
+ .iter()
+ .filter(|c| c.kind == "peer_review" && c.status == "failed")
+ .filter(|c| since.is_none_or(|s| c.finished_at.is_some_and(|f| f >= s)))
+ .max_by_key(|c| c.finished_at)
+ .map(|c| c.output_excerpt.clone().unwrap_or_else(|| "it isn't done yet".into()))
+}
+
+/// For the lead's results turn: the board card of a finished hand-off `d` waiting in review, and
+/// how the lead reviews it. `None` when the board is off or the card isn't in review.
+pub async fn lead_review_note(state: &AppState, d: &crate::db::threads::Delegation, who: &str) -> Option<String> {
+ if !super::enabled(state).await || d.status != "completed" {
+ return None;
+ }
+ // The board may not have seen the end yet: its card goes to review first. Not through
+ // [`on_delegation`], whose send-back runs the hand-off, whose end comes back here.
+ let t = {
+ let _serial = SERIAL.lock().await;
+ let t = state.db.task_by_source("delegation", &d.id).await.ok().flatten()?;
+ if matches!(t.state.as_str(), "working" | "needs_you") {
+ attach_result(state, &t, d).await;
+ finish(state, &t, "review", "the hand-off finished").await;
+ }
+ state.db.get_task(&t.id).await.ok().flatten()?
+ };
+ if t.state != "review" {
+ return None;
+ }
+ let ev = state.db.list_evidence(&t.id).await.ok()?.into_iter().filter(|e| e.label == RESULT_LABEL).max_by_key(|e| e.captured_at)?;
+ let detail = serde_json::json!({"delegation_id": d.id, "lead_kwant_id": d.lead_kwant_id});
+ if let Err(e) = state.db.log_task_event(&t.id, REVIEW_ASKED, "kwant", &detail).await {
+ tracing::warn!(error = %e, task_id = %t.id, "could not log a lead review ask");
+ }
+ Some(format!(
+ "(Board card {task} is in Review and you, who handed it out, review it: {who} can't approve its own work. Call \
+ task_review with task_id \"{task}\": verdict \"pass\" with evidence_ids [\"{ev}\"] (its result) when it does what you \
+ asked, or verdict \"fail\" with a note that says exactly what is missing or wrong. A fail sends it back to {who} \
+ with your note, so don't also @mention {who} for that correction.)",
+ task = t.id,
+ ev = ev.id,
+ ))
+}
+
+/// Task event logged each time the lead is asked to review a hand-off card (its results turn,
+/// a review turn or the reminder).
+pub const REVIEW_ASKED: &str = "lead_review_asked";
+
+/// How often the lead is asked per stay in Review: its results turn and one reminder. After
+/// that the card waits ("Waiting for <lead> to review") for the lead or the person.
+pub const MAX_REVIEW_ASKS: usize = 2;
+
+/// The note on a finished one-way hand-off's card (the lead isn't resumed with its result): it is
+/// closed instead of going to Review, where nobody would look at it. It is closed, not verified;
+/// the board reads it as "Closed" (`closed_note` in the task's JSON).
+pub const NOTICE_CLOSED: &str = "Notice, no review needed";
+
+/// How long a hand-off card may sit in Review with no lead review running before
+/// [`sweep_unreviewed`] asks the lead (again): long enough for the lead's batch turn to start.
+pub const REVIEW_GRACE: std::time::Duration = std::time::Duration::from_secs(120);
+
+/// How often the lead was asked to review `task_id` since it last went to Review, and when last.
+pub async fn review_asks(state: &AppState, task_id: &str) -> (usize, Option<chrono::DateTime<chrono::Utc>>) {
+ let since = super::review_since(state, task_id).await;
+ let events = state.db.task_events(task_id, 500).await.unwrap_or_default();
+ let asks: Vec<_> = events.iter().filter(|e| e.kind == REVIEW_ASKED && since.is_none_or(|s| e.created_at >= s)).collect();
+ (asks.len(), asks.last().map(|e| e.created_at))
+}
+
+/// Whether `task` is a hand-off card in Review that its lead should still be asked about:
+/// its result is on the card (older cards, from before leads reviewed, are left alone) and the
+/// lead hasn't been asked [`MAX_REVIEW_ASKS`] times this stay.
+pub async fn wants_lead_review(state: &AppState, task: &Task) -> bool {
+ if task.state != "review" || task.source_kind != "delegation" {
+ return false;
+ }
+ let has_result = state.db.list_evidence(&task.id).await.unwrap_or_default().iter().any(|e| e.label == RESULT_LABEL);
+ has_result && review_asks(state, &task.id).await.0 < MAX_REVIEW_ASKS
+}
+
+/// Hand-off cards in Review whose lead review never came: kwnt restarted before or during the
+/// lead's turn, or the reminder was lost. Each gets a review turn once nothing has asked for
+/// `grace` and no turn for its hand-off is running; one whose batch still runs waits for it.
+/// Called from [`reconcile`] with [`REVIEW_GRACE`].
+pub async fn sweep_unreviewed(state: &AppState, grace: std::time::Duration) {
+ let now = chrono::Utc::now();
+ for t in state.db.tasks_in_state("review").await.unwrap_or_default() {
+ let Some(id) = t.source_id.as_deref().filter(|_| t.source_kind == "delegation") else { continue };
+ let Ok(Some(d)) = state.db.get_delegation(id).await else { continue };
+ if d.status != "completed" || !d.continue_lead || state.turns.has_job(&d.id) {
+ continue;
+ }
+ if !wants_lead_review(state, &t).await || crate::server::delegation::batch_running(state, &d).await {
+ continue;
+ }
+ let (asks, last) = review_asks(state, &t.id).await;
+ let quiet_since = last.or(super::review_since(state, &t.id).await).unwrap_or(t.updated_at);
+ if (now - quiet_since).to_std().unwrap_or_default() < grace {
+ continue;
+ }
+ crate::server::delegation::spawn_review_turn(state, &d, asks > 0);
+ }
+}
+
/// Why a hand-off card sent back to Ready can't go on, so it is blocked for the person instead.
pub const CANT_CARRY_ON: &str = "the hand-off can't carry on (a bot is gone or it was restarted elsewhere): ask the lead again";
diff --git a/src/server/missions/mod.rs b/src/server/missions/mod.rs
index 9d7de88f..c7a69932 100644
--- a/src/server/missions/mod.rs
+++ b/src/server/missions/mod.rs
@@ -633,10 +633,36 @@ pub async fn task_json(state: &AppState, task: &Task) -> Value {
autofix::extend_task_json(state, task, obj).await;
obj.insert("task_class".into(), json!(state.db.task_class(&task.id).await.unwrap_or_else(|_| crate::db::flight_school::DEFAULT_CLASS.into())));
obj.insert("owner_tier".into(), flight_school::owner_tier(state, task).await);
+ obj.insert("reviewer".into(), reviewer(state, task).await);
+ obj.insert("closed_note".into(), closed_note(state, task).await);
}
v
}
+/// Who reviews a task whose result came in without checks: the bot that handed out a hand-off.
+async fn reviewer(state: &AppState, task: &Task) -> Value {
+ if task.source_kind != "delegation" {
+ return Value::Null;
+ }
+ let Some(id) = task.source_id.as_deref() else { return Value::Null };
+ let Ok(Some(d)) = state.db.get_delegation(id).await else { return Value::Null };
+ json!({"kwant_id": d.lead_kwant_id, "name": name_of(state, Some(&d.lead_kwant_id)).await})
+}
+
+/// A one-way hand-off's card closed without review: its note, so the board reads it as "Closed"
+/// rather than "Cancelled".
+async fn closed_note(state: &AppState, task: &Task) -> Value {
+ if task.state != "cancelled" || task.source_kind != "delegation" {
+ return Value::Null;
+ }
+ let events = state.db.task_events(&task.id, 500).await.unwrap_or_default();
+ let Some(last) = events.iter().rev().find(|e| e.to_state.is_some()) else { return Value::Null };
+ match last.detail_value().get("reason").and_then(Value::as_str) {
+ Some(why) if last.to_state.as_deref() == Some("cancelled") && why == listener::NOTICE_CLOSED => json!(why),
+ _ => Value::Null,
+ }
+}
+
pub async fn mission_json(state: &AppState, m: &Mission) -> Value {
let mut v = serde_json::to_value(m).unwrap_or(Value::Null);
let reserved = state.db.mission_reserved(&m.id).await.unwrap_or(0);
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
index 91fbbd44..0eff9590 100644
--- a/src/server/missions/tools.rs
+++ b/src/server/missions/tools.rs
@@ -499,6 +499,17 @@ async fn review(state: &AppState, scope: &SelfScope, task: &Task, args: &Value)
if task.owner_kwant_id.as_deref() == Some(scope.kwant_id.as_str()) {
return fail("You can't review your own task; a teammate or the person does.");
}
+ // A hand-off's card is reviewed by the bot that handed it out, not by any other teammate
+ if task.source_kind == "delegation" {
+ let lead = match task.source_id.as_deref() {
+ Some(id) => state.db.get_delegation(id).await.ok().flatten().map(|d| d.lead_kwant_id),
+ None => None,
+ };
+ if let Some(lead) = lead.filter(|l| *l != scope.kwant_id) {
+ let name = state.db.get_kwant(&lead).await.ok().flatten().map(|k| k.name).unwrap_or_else(|| "the lead".into());
+ return fail(format!("Only {name}, who handed this task out, reviews it; the person can also verify it."));
+ }
+ }
if task.state != "review" {
return fail(format!("The task is {}, not in review.", task.state));
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 4314d527..f6f060a7 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1310,7 +1310,7 @@ pub(super) async fn delegate_mentions(
lead: lead.clone(),
specialist: specialist.clone(),
task: task.clone(),
- title: Some(title.clone()),
+ title: Some(handoff_title(text, &specialist.name).unwrap_or_else(|| title.clone())),
origin: super::delegation::Origin { channel_id: Some(cid.clone()), ..Default::default() },
continue_lead: true,
origin_depth: scope.delegation_depth,
@@ -1331,6 +1331,36 @@ pub(super) async fn delegate_mentions(
}
}
+/// A hand-off's title from what the lead asked `name` for: the first sentence of the line that
+/// @mentions them, without the mention. Two hand-offs from one message then read differently on
+/// the board (Oleks, 2026-10-29: four cards all named after his message). `None` when the line
+/// says nothing past the mention, or when it @mentions others too (the same words for each).
+pub fn handoff_title(text: &str, name: &str) -> Option<String> {
+ let mention = format!("@{}", name.to_lowercase());
+ let line = text.lines().find(|l| l.to_lowercase().contains(&mention))?;
+ if line.match_indices('@').filter(|&(i, _)| line[i + 1..].starts_with(char::is_alphanumeric)).count() > 1 {
+ return None;
+ }
+ let lower = line.to_lowercase();
+ // Offsets of the lowercased line match the original only when lowercasing kept every length
+ if lower.len() != line.len() {
+ return None;
+ }
+ let rest = &line[lower.find(&mention)? + mention.len()..];
+ let rest = rest.trim_start_matches(|c: char| c.is_whitespace() || matches!(c, ',' | ':' | '-' | '–' | '—' | '*' | '_' | '.'));
+ let end = rest
+ .char_indices()
+ .find(|&(i, c)| matches!(c, '.' | '!' | '?') && rest[i + c.len_utf8()..].starts_with(char::is_whitespace))
+ .map(|(i, c)| i + c.len_utf8());
+ let sentence = rest[..end.unwrap_or(rest.len())].trim().trim_end_matches(['*', '_']).trim();
+ if sentence.chars().filter(|c| c.is_alphanumeric()).count() < 3 {
+ return None;
+ }
+ let mut chars = sentence.chars();
+ let title: String = chars.next().map(|c| c.to_uppercase().collect::<String>() + chars.as_str()).unwrap_or_default();
+ Some(truncate_chars(&title, 80).to_string())
+}
+
/// Whether the teammate with `id` is among the @mentioned `targets` (indices into the teammates).
fn targets_mentioned(targets: &[usize], scope: &TurnScope, id: &str) -> bool {
targets.iter().any(|&i| scope.teammates[i].id == id)
diff --git a/tests/handoff_review_test.rs b/tests/handoff_review_test.rs
new file mode 100644
index 00000000..c534973d
--- /dev/null
+++ b/tests/handoff_review_test.rs
@@ -0,0 +1,487 @@
+//! Hand-off cards don't pile up in Review (Oleks, 2026-10-29: "many tasks in review column, who
+//! is going to check them??"). A finished hand-off's result is evidence on its card, the lead's
+//! results turn names the card and how to review it, and only the lead's review counts: a pass
+//! verifies the card, a fail sends the work back to the teammate with the note, on the same card.
+//! Every card in Review gets a lead review turn, or isn't put there: a lead that doesn't review is
+//! reminded once, a card the batch turn missed (blocked at the time, or a restart) gets its own
+//! turn, and a one-way hand-off is closed. A fake claude CLI on PATH answers every turn with
+//! "done" (so a lead never calls task_review). Its own test binary: it changes PATH.
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{missions::Task, Database},
+ router::LayaRouter,
+ server::{continuity::SelfScope, create_router, missions, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+printf '%s' "$last" > "$KWNT_TEST_PROMPTS/$$-$(date +%s%N)"
+case "$last" in
+esac
+release=$(printf '%s\n' "$last" | sed -n 's/.*LONGTASK:\([^ ]*\).*/\1/p' | head -n 1)
+if [ -n "$release" ]; then
+ i=0
+ while [ ! -f "$release" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done
+fi
+echo '{"type":"result","is_error":false,"num_turns":1,"result":"done"}'
+"#;
+
+fn prompts_dir() -> &'static PathBuf {
+ static DIR: OnceLock<PathBuf> = OnceLock::new();
+ DIR.get_or_init(|| {
+ let root = tempfile::tempdir().unwrap().keep();
+ let bin = root.join("bin");
+ let prompts = root.join("prompts");
+ std::fs::create_dir_all(&bin).unwrap();
+ std::fs::create_dir_all(&prompts).unwrap();
+ let fake = bin.join("claude");
+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ std::env::set_var("KWNT_TEST_PROMPTS", &prompts);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ prompts
+ })
+}
+
+/// Prompts the fake CLI got that contain every one of `markers`.
+fn prompts_with(markers: &[&str]) -> Vec<String> {
+ std::fs::read_dir(prompts_dir())
+ .unwrap()
+ .filter_map(|e| std::fs::read_to_string(e.unwrap().path()).ok())
+ .filter(|p| markers.iter().all(|m| p.contains(m)))
+ .collect()
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+
+struct Env {
+ app: Router,
+ state: AppState,
+ lead: String,
+ specialist: String,
+ other: String,
+}
+
+async fn setup() -> Env {
+ prompts_dir();
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ // Laya is unreachable: turns use the kwant's preferred model, the fake claude
+ let config = Config {
+ data_dir: data.clone(),
+ 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(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ let app = create_router(state.clone());
+ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;
+ let mut ids = Vec::new();
+ for k in kwants.as_array().unwrap().iter().take(3) {
+ let id = k["id"].as_str().unwrap().to_string();
+ let mut body = k.clone();
+ body.as_object_mut()
+ .unwrap()
+ .retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));
+ body["preferred_model"] = json!("claude");
+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{id}"), Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ ids.push(id);
+ }
+ let (s, v) = call(&app, "POST", "/api/settings", Some(json!({"mission_board": true}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ // The board follows hand-offs on the event bus, as the scheduler starts it in kwnt
+ missions::listener::spawn(state.clone(), tokio_util::sync::CancellationToken::new());
+ std::mem::forget(tmp);
+ Env { app, state, lead: ids[0].clone(), specialist: ids[1].clone(), other: ids[2].clone() }
+}
+
+async fn wait_for<F, Fut>(what: &str, mut check: F)
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = bool>,
+{
+ for _ in 0..300 {
+ if check().await {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("timed out waiting for {what}");
+}
+
+/// A hand-off from the lead to the specialist that reports back to the lead.
+async fn delegate(env: &Env, task: &str, title: &str) -> Value {
+ let body = json!({"lead_kwant_id": env.lead, "specialist_kwant_id": env.specialist, "task": task, "title": title, "kwant_id": env.lead});
+ let (s, d) = call(&env.app, "POST", "/api/delegations", Some(body)).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ d
+}
+
+
+async fn status_of(env: &Env, id: &str) -> String {
+ env.state.db.get_delegation(id).await.unwrap().map(|d| d.status).unwrap_or_default()
+}
+
+async fn card(env: &Env, delegation_id: &str) -> Option<Task> {
+ env.state.db.task_by_source("delegation", delegation_id).await.unwrap()
+}
+
+async fn card_state(env: &Env, delegation_id: &str) -> String {
+ card(env, delegation_id).await.map(|t| t.state).unwrap_or_default()
+}
+
+fn id(v: &Value) -> String {
+ v["id"].as_str().unwrap().to_string()
+}
+
+/// Moves of the task, as "from>to".
+async fn moves(env: &Env, task_id: &str) -> Vec<String> {
+ let events = env.state.db.task_events(task_id, 200).await.unwrap();
+ events.iter().filter_map(|e| Some(format!("{}>{}", e.from_state.as_deref()?, e.to_state.as_deref()?))).collect()
+}
+
+
+async fn review(env: &Env, by: &str, task_id: &str, verdict: &str, evidence: &[String], note: &str) -> (Value, bool) {
+ let bot = env.state.db.get_kwant(by).await.unwrap().unwrap();
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let args = json!({"task_id": task_id, "verdict": verdict, "evidence_ids": evidence, "note": note});
+ let (text, is_error) = missions::tools::call(&env.state, &scope, "task_review", &args).await;
+ (serde_json::from_str(&text).unwrap_or(Value::String(text)), is_error)
+}
+
+/// A finished hand-off waiting in review, with its result attached: (delegation id, card).
+async fn finished(env: &Env, task: &str, title: &str) -> (String, Task) {
+ let d = delegate(env, task, title).await;
+ let did = id(&d);
+ wait_for("the card to reach review", || async { card_state(env, &did).await == "review" }).await;
+ (did.clone(), card(env, &did).await.unwrap())
+}
+
+async fn result_evidence(env: &Env, task_id: &str) -> Vec<String> {
+ let ev = env.state.db.list_evidence(task_id).await.unwrap();
+ ev.iter().filter(|e| e.label == missions::listener::RESULT_LABEL).map(|e| e.id.clone()).collect()
+}
+
+/// The lead is told which card to review and how; its pass verifies the card.
+#[tokio::test]
+async fn the_lead_reviews_a_finished_hand_off_and_a_pass_verifies_it() {
+ let env = setup().await;
+ let (did, task) = finished(&env, "Check the parser PASSMARK", "Parser check").await;
+ let ev = result_evidence(&env, &task.id).await;
+ assert_eq!(ev.len(), 1, "the result is attached once");
+ wait_for("the lead's results turn", || async { !prompts_with(&["finished the task you delegated", "Parser check"]).is_empty() }).await;
+ let lead_prompt = prompts_with(&["finished the task you delegated", "Parser check"]).remove(0);
+ assert!(lead_prompt.contains(&task.id) && lead_prompt.contains("task_review") && lead_prompt.contains(&ev[0]), "{lead_prompt}");
+
+ let card_json = missions::task_json(&env.state, &task).await;
+ assert_eq!(card_json["reviewer"]["kwant_id"], json!(env.lead), "the card names its reviewer");
+
+ let (out, err) = review(&env, &env.lead, &task.id, "pass", &ev, "Parser handles the new format").await;
+ assert!(!err, "{out}");
+ assert_eq!(card_state(&env, &did).await, "verified");
+}
+
+/// A fail goes back to Ready with the lead's note and on to the teammate in the hand-off's own
+/// thread; the fixed result comes back to review on the same card, for the lead to review again.
+#[tokio::test]
+async fn a_failed_review_sends_the_work_back_to_the_teammate_with_the_reason() {
+ let env = setup().await;
+ let (did, task) = finished(&env, "Write the backend fix FAILMARK", "Backend fix").await;
+ let ev = result_evidence(&env, &task.id).await;
+ let note = "The retry path has no test NOTEMARK";
+ let (out, err) = review(&env, &env.lead, &task.id, "fail", &ev, note).await;
+ assert!(!err, "{out}");
+
+ let m = moves(&env, &task.id).await;
+ assert!(m.iter().any(|x| x == "review>ready"), "{m:?}");
+ let events = env.state.db.task_events(&task.id, 200).await.unwrap();
+ let back = events.iter().find(|e| e.from_state.as_deref() == Some("review") && e.to_state.as_deref() == Some("ready")).unwrap();
+ assert!(back.detail.contains("peer_review"), "the move gives its reason: {}", back.detail);
+
+ wait_for("the teammate's fix turn", || async { !prompts_with(&["sent it back", "NOTEMARK", "FAILMARK"]).is_empty() }).await;
+ wait_for("the fixed result back in review", || async {
+ moves(&env, &task.id).await.iter().filter(|x| *x == "working>review").count() == 2 && card_state(&env, &did).await == "review"
+ })
+ .await;
+ assert_eq!(status_of(&env, &did).await, "completed");
+ let ev = result_evidence(&env, &task.id).await;
+ assert_eq!(ev.len(), 2, "the new result is attached too");
+ wait_for("the lead's second results turn", || async { !prompts_with(&["after it was sent back", "Backend fix", "task_review"]).is_empty() }).await;
+
+ let space = env.state.db.space_of_kwant(&env.lead).await.unwrap().unwrap();
+ let cards = env.state.db.list_tasks(&space, None, None, Some("delegation"), 200).await.unwrap();
+ assert_eq!(cards.iter().filter(|t| t.source_id.as_deref() == Some(did.as_str())).count(), 1, "one hand-off, one card");
+}
+
+/// The teammate who did the work can't approve it, and neither can a bystander: only the lead.
+#[tokio::test]
+async fn only_the_lead_reviews_a_hand_off_card() {
+ let env = setup().await;
+ let (did, task) = finished(&env, "Draft the release notes OWNERMARK", "Release notes").await;
+ let ev = result_evidence(&env, &task.id).await;
+ let (out, err) = review(&env, &env.specialist, &task.id, "pass", &ev, "looks good to me").await;
+ assert!(err, "the owner's own review is refused: {out}");
+ let (out, err) = review(&env, &env.other, &task.id, "pass", &ev, "fine").await;
+ assert!(err && out.to_string().contains("who handed this task out"), "{out}");
+ assert_eq!(card_state(&env, &did).await, "review");
+ assert!(env.state.db.list_checks(&task.id).await.unwrap().is_empty(), "no review was recorded");
+}
+
+/// Prompts that asked the lead to review card `task_id` (results turn, review turn or reminder).
+fn review_asks_for(task_id: &str) -> usize {
+ prompts_with(&[&format!("task_id \"{task_id}\"")]).len()
+}
+
+async fn asks_logged(env: &Env, task_id: &str) -> usize {
+ missions::listener::review_asks(&env.state, task_id).await.0
+}
+
+/// Lets background turns that would wrongly start show up before a test counts prompts.
+async fn settle() {
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+}
+
+/// The results turn asks the lead to review; a lead that doesn't gets exactly one reminder,
+/// then the card waits, named for its reviewer, and a sweep doesn't ask again.
+#[tokio::test]
+async fn a_lead_that_doesnt_review_is_reminded_once_and_then_the_card_waits() {
+ let env = setup().await;
+ let (did, task) = finished(&env, "Tidy the logs REMINDMARK", "Log tidy").await;
+ wait_for("the reminder", || async { !prompts_with(&["Reminder:", "Log tidy", &task.id]).is_empty() }).await;
+ wait_for("both asks logged", || async { asks_logged(&env, &task.id).await == 2 }).await;
+ settle().await;
+ missions::listener::sweep_unreviewed(&env.state, Duration::ZERO).await;
+ settle().await;
+ assert_eq!(review_asks_for(&task.id), 2, "the results turn and one reminder, nothing more");
+ assert_eq!(asks_logged(&env, &task.id).await, 2);
+ assert_eq!(card_state(&env, &did).await, "review");
+ let t = card(&env, &did).await.unwrap();
+ let lead_name = env.state.db.get_kwant(&env.lead).await.unwrap().unwrap().name;
+ assert_eq!(missions::task_json(&env.state, &t).await["reviewer"]["name"], json!(lead_name));
+}
+
+/// A hand-off that doesn't report back to its lead is a one-way notice: nobody is resumed with
+/// its result, so its card is closed with a note instead of waiting in Review.
+#[tokio::test]
+async fn a_one_way_hand_off_is_closed_instead_of_left_in_review() {
+ let env = setup().await;
+ let body = json!({"lead_kwant_id": env.lead, "specialist_kwant_id": env.specialist, "task": "FYI the deploy moved NOTICEMARK",
+ "title": "Deploy notice", "kwant_id": env.lead, "continue_lead": false});
+ let (s, d) = call(&env.app, "POST", "/api/delegations", Some(body)).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ let did = id(&d);
+ wait_for("the card to close", || async { card_state(&env, &did).await == "cancelled" }).await;
+ let t = card(&env, &did).await.unwrap();
+ assert!(!moves(&env, &t.id).await.iter().any(|m| m.ends_with(">review")), "it never went to review");
+ let events = env.state.db.task_events(&t.id, 200).await.unwrap();
+ assert!(events.iter().any(|e| e.detail.contains("Notice, no review needed")), "the close says why");
+ assert_eq!(missions::task_json(&env.state, &t).await["closed_note"], json!("Notice, no review needed"), "it reads as Closed");
+ settle().await;
+ assert_eq!(review_asks_for(&t.id), 0, "nobody is asked to review a notice");
+}
+
+/// The hand-off finished while its card was blocked, so the lead's results turn didn't see the
+/// card. When the person unblocks it, it goes to Review and the lead gets a review turn for it.
+#[tokio::test]
+async fn a_card_unblocked_after_its_hand_off_finished_gets_a_review_turn() {
+ let env = setup().await;
+ let release = tempfile::tempdir().unwrap().keep().join("go");
+ let d = delegate(&env, &format!("Long job BLOCKMARK LONGTASK:{} ", release.display()), "Long job").await;
+ let did = id(&d);
+ wait_for("the card to be worked on", || async { card_state(&env, &did).await == "working" }).await;
+ let t = card(&env, &did).await.unwrap();
+ let (s, v) = call(&env.app, "POST", &format!("/api/tasks/{}/block", t.id), Some(json!({"reason": "wait for the release"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ std::fs::write(&release, "go").unwrap();
+ wait_for("the hand-off to finish", || async { status_of(&env, &did).await == "completed" }).await;
+ wait_for("the lead's results turn", || async { !prompts_with(&["finished the task you delegated", "Long job"]).is_empty() }).await;
+ settle().await;
+ assert_eq!(card_state(&env, &did).await, "blocked");
+ assert_eq!(review_asks_for(&t.id), 0, "a blocked card isn't up for review yet");
+
+ let (s, v) = call(&env.app, "POST", &format!("/api/tasks/{}/unblock", t.id), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ wait_for("the card in review", || async { card_state(&env, &did).await == "review" }).await;
+ wait_for("the lead's review turn", || async { !prompts_with(&["its card is waiting for your review", &t.id]).is_empty() }).await;
+ wait_for("the one reminder", || async { asks_logged(&env, &t.id).await == 2 }).await;
+}
+
+/// kwnt restarted after the card reached Review but before the lead's turn (here: the hand-off
+/// ended without kwant reporting it). The sweep gives the lead its review turn, plus the one
+/// reminder, and then leaves the card alone.
+#[tokio::test]
+async fn the_sweep_asks_the_lead_about_a_card_whose_review_turn_was_lost() {
+ let env = setup().await;
+ let lead = env.state.db.get_kwant(&env.lead).await.unwrap().unwrap();
+ let new = kwnt::db::threads::NewDelegation {
+ lead_kwant_id: env.lead.clone(),
+ specialist_kwant_id: env.specialist.clone(),
+ origin_channel_id: None,
+ origin_kwant_id: Some(lead.id.clone()),
+ origin_thread_id: None,
+ team_id: None,
+ task: "Rotate the keys SWEEPMARK".into(),
+ title: "Key rotation".into(),
+ continue_lead: true,
+ depth: 1,
+ follow_up_at: None,
+ };
+ let (_, d) = env.state.db.create_delegation(&new).await.unwrap();
+ assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
+ missions::listener::on_delegation(&env.state, &d.id).await;
+ assert_eq!(card_state(&env, &d.id).await, "review");
+ let t = card(&env, &d.id).await.unwrap();
+ assert_eq!(review_asks_for(&t.id), 0, "nobody asked the lead yet");
+
+ missions::listener::sweep_unreviewed(&env.state, Duration::from_secs(3600)).await;
+ settle().await;
+ assert_eq!(review_asks_for(&t.id), 0, "within the grace time the sweep waits for the batch turn");
+
+ missions::listener::sweep_unreviewed(&env.state, Duration::ZERO).await;
+ wait_for("the lead's review turn", || async { !prompts_with(&["its card is waiting for your review", &t.id]).is_empty() }).await;
+ wait_for("the one reminder", || async { asks_logged(&env, &t.id).await == 2 }).await;
+ settle().await;
+ missions::listener::sweep_unreviewed(&env.state, Duration::ZERO).await;
+ settle().await;
+ assert_eq!(review_asks_for(&t.id), 2, "asked once and reminded once, then left for the lead or the person");
+ assert_eq!(card_state(&env, &d.id).await, "review");
+}
+
+/// Each hand-off from one message is named after what the lead asked that teammate.
+#[test]
+fn a_hand_off_is_named_after_what_its_teammate_was_asked() {
+ use kwnt::server::routes::handoff_title;
+ let text = "On it.\n@QA, run the smoke tests on staging. Then report.\n@Backend: fix the rancher reconnect\n@QA please re-check the login flow!";
+ assert_eq!(handoff_title(text, "QA").as_deref(), Some("Run the smoke tests on staging."));
+ assert_eq!(handoff_title(text, "backend").as_deref(), Some("Fix the rancher reconnect"));
+ assert_eq!(handoff_title("**@Parser** — parse the new feed", "Parser").as_deref(), Some("Parse the new feed"));
+ assert_eq!(handoff_title("Thanks @QA.", "QA"), None, "nothing asked: the message's title is kept");
+ assert_eq!(handoff_title("no mention here", "QA"), None);
+ assert_eq!(handoff_title("@Social @Writer draft the launch post", "Social"), None, "one line for several teammates names none of them apart");
+}
+
+/// A lead that answers the reminder by reviewing: its pass verifies the card, and nothing asks
+/// it again. (The fake CLI can't call tools, so the test makes the lead's task_review call once
+/// the reminder has gone out, as the lead would in that turn.)
+#[tokio::test]
+async fn a_lead_that_reviews_after_the_reminder_verifies_the_card() {
+ let env = setup().await;
+ let (did, task) = finished(&env, "Check the cron entry ONREMINDMARK", "Cron check").await;
+ wait_for("the reminder", || async {
+ !prompts_with(&["Reminder:", "Cron check", &task.id]).is_empty()
+ })
+ .await;
+ wait_for("both asks logged", || async {
+ asks_logged(&env, &task.id).await == 2
+ })
+ .await;
+ let ev = result_evidence(&env, &task.id).await;
+ let (out, err) = review(
+ &env,
+ &env.lead,
+ &task.id,
+ "pass",
+ &ev,
+ "The cron entry is right",
+ )
+ .await;
+ assert!(!err, "{out}");
+ assert_eq!(card_state(&env, &did).await, "verified");
+ missions::listener::sweep_unreviewed(&env.state, Duration::ZERO).await;
+ settle().await;
+ assert_eq!(
+ review_asks_for(&task.id),
+ 2,
+ "a verified card is never asked about again"
+ );
+}
+
+/// Two hand-offs of one lead that finish together: one results prompt names both cards, and the
+/// one reminder covers both, in a single turn.
+#[tokio::test]
+async fn a_batch_of_two_cards_gets_one_prompt_and_one_reminder() {
+ let env = setup().await;
+ let release = tempfile::tempdir().unwrap().keep().join("release");
+ let mut dids = Vec::new();
+ for (who, title) in [(&env.specialist, "Batch alpha"), (&env.other, "Batch beta")] {
+ let body = json!({"lead_kwant_id": env.lead, "specialist_kwant_id": who, "title": title, "kwant_id": env.lead,
+ "task": format!("Part of the batch BATCHMARK LONGTASK:{}", release.display())});
+ let (s, d) = call(&env.app, "POST", "/api/delegations", Some(body)).await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ dids.push(id(&d));
+ }
+ std::fs::write(&release, "go").unwrap();
+ let mut ids = Vec::new();
+ for did in &dids {
+ wait_for("the card to reach review", || async {
+ card_state(&env, did).await == "review"
+ })
+ .await;
+ ids.push(card(&env, did).await.unwrap().id);
+ }
+ let both = [
+ format!("task_id \"{}\"", ids[0]),
+ format!("task_id \"{}\"", ids[1]),
+ ];
+ let both: Vec<&str> = both.iter().map(String::as_str).collect();
+ wait_for("the reminder", || async {
+ !prompts_with(&[&["Reminder:"][..], &both].concat()).is_empty()
+ })
+ .await;
+ for t in &ids {
+ wait_for("both asks logged", || async {
+ asks_logged(&env, t).await == 2
+ })
+ .await;
+ }
+ settle().await;
+ assert_eq!(
+ prompts_with(&both).len(),
+ 2,
+ "one results prompt and one reminder, each naming both cards"
+ );
+ assert_eq!(
+ prompts_with(&[&["Reminder:"][..], &both].concat()).len(),
+ 1,
+ "one reminder for the batch"
+ );
+ for t in &ids {
+ assert_eq!(review_asks_for(t), 2, "no card was asked about on its own");
+ }
+}