Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Auditor earns its turn on routine runs, and says who and why (14a) (#641)
Oleksandr Ivanchenko19073cc6f8c5
diff --git a/docs/mission-control.md b/docs/mission-control.mdindex 6f4287ae..2346b4a5 100644--- a/docs/mission-control.md+++ b/docs/mission-control.md@@ -974,6 +974,22 @@ urgent (`high_impact`) or no check that counts and isn't the owner's will judge(`manual`). One audit per task attempt; one audit runs at a time server-wide. A skipped audit (cap,no challenger) logs `audit_skipped`.+**Routine runs (14a).** A routine run's task (`source_kind = routine`) that would be audited only as+`low_confidence` is audited on its routine's first run that reaches review, on the first run after+the routine's instructions or acceptance changed, and otherwise at most once per routine per 7 days.+Any other run logs `audit_skipped` with reason `routine_recently_checked`, `routine_id`,+`last_audit_at`, `last_audit_task_id` and `next_audit_from`. "Last audited" is the newest audit of+any run of the routine that is `queued`, in a stage or `done` (not skipped, failed or interrupted);+"changed" compares a hash of the routine's instructions and acceptance, which `audit_started`+records as `routine_fp` (an audit from before 14a has none, so the next run is audited). No column+or migration: the audits, the runs and the task events answer it. High-impact routine runs, manual+audits, hand-offs, goals and every other task are audited as before, and the daily cap still holds.++**Who and why.** `audit_started` also records `owner` and `source_kind`. An audit turn's entry in+`GET /api/turns` and its `turn_started` event carry `audit: {audit_id, task_id, task_title,+source_kind, trigger, stage, challenger_kwant_id, owner_kwant_id}`, so the app can say in one line+who is double-checking whose work and why, instead of a plain "working".+**Challenger.** A bot of the task's space other than the owner, the mission's lead and the lead thathanded the task off, that knows the kind of work. Pools, best first:diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 64924686..1cbc5c4d 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -91,6 +91,7 @@ import { browserTabDoc, createTabSignal, needsYouCount } from './tabSignal';import { recentWork, teamMembersLeadFirst, type ChatHome } from './botHome';import { approvalsDiffers } from './components/Sidebar';import { botStatuses, busyLines } from './botStatus';+import { auditShortLine, auditTurnLine } from './auditor';import { type H4Status, type HeldSend, afterRelease, applyBotStatusEvent, h4Api, heldFromReply, heldLine, heldMessages, stillHeld } from './h4Status';import { HeldLine } from './components/HeldLine';import { type BrowsingMap, expireBrowsing, globeRows, noteBrowser, ownerStillRunning, pruneBrowsing, seedBrowsing, switchEntries } from './watchLive';@@ -3571,7 +3572,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({else openTarget({ channel_id: t.context_id, kwant_id: null });}}className="inline-flex items-center gap-1.5 min-w-0 max-w-[16rem] sm:max-w-xs px-2 py-0.5 rounded-full border border-sky-500/30 bg-sky-500/10 text-[11px] text-sky-200 hover:bg-sky-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"- title={elsewhere.map((t) => describeContext(t.context_id, t.kwant_id)).join(', ')}+ title={elsewhere.map((t) => (t.audit ? auditTurnLine(t.audit, kwantNames, { subject: false }) : describeContext(t.context_id, t.kwant_id))).join(', ')}>{awaitingTurns.has(elsewhere[0].turn_id) ? (<HelpCircle size={10} className="shrink-0 text-amber-300" aria-hidden="true" />@@ -3579,8 +3580,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({<Loader2 size={10} className="shrink-0 animate-spin motion-reduce:animate-none" aria-hidden="true" />)}<span className="truncate">+ {elsewhere[0].audit && elsewhere[0].state === 'running' && !browserTurns.has(elsewhere[0].turn_id) && !awaitingTurns.has(elsewhere[0].turn_id) ? auditShortLine(elsewhere[0].audit, kwantNames) : <>{elsewhere[0].state === 'queued' ? 'Waiting to work on ' : browserTurns.has(elsewhere[0].turn_id) ? 'Needs you in the browser in ' : awaitingTurns.has(elsewhere[0].turn_id) ? 'Asked you a question in ' : 'Working on '}{describeContext(elsewhere[0].context_id, elsewhere[0].kwant_id)}+ </>}</span>{elsewhere.length > 1 && <span className="shrink-0 text-sky-300/80">+{elsewhere.length - 1} more</span>}</button>@@ -3719,7 +3722,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const vmSwitcher = switcherEntries.length >= 2 ? { entries: switcherEntries, current: activeSandboxId, onPick: watchOwner } : null;// Sidebar: what busy bots are doing, "here" for the open chat.- const busyKwants = busyLines({ turns: Object.values(turns), openCtx, awaiting: awaitingTurns, browser: browserTurns, describe: describeContext });+ const busyTitles: Record<string, string> = {};+ const busyKwants = busyLines({ turns: Object.values(turns), openCtx, awaiting: awaitingTurns, browser: browserTurns, describe: describeContext, names: kwantNames, titles: busyTitles });// A team turn waiting on one bot's question: its teammates that already replied read "Done" (UX audit #2).const doneKwants = doneLines(messages, awaitingBotHere, isChannel, (id) => botOf(id, kwants));const botStatus = botStatuses({ turns: Object.values(turns), awaiting: awaitingTurns, needsYou: needsYouByKwant });@@ -4041,6 +4045,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({isChannel={isChannel}selectedTeamId={selectedTeamId}busyKwants={busyKwants}+ busyTitles={busyTitles}doneKwants={doneKwants}browsingOwners={globes.owners}browsingBots={globes.bots}diff --git a/frontend/src/auditor.ts b/frontend/src/auditor.tsindex b2b44d99..b65819bd 100644--- a/frontend/src/auditor.ts+++ b/frontend/src/auditor.ts@@ -3,6 +3,7 @@// person closes them. An audit never marks work passed or failed; only checks do. Pure helpers,// shared by the app and the node tests.import type { AwayItem, AwayLink } from './away';+import { localClock } from './clock';export type AuditStatus = 'queued' | 'challenge' | 'rebuttal' | 'done' | 'skipped' | 'failed' | 'interrupted';export type RiskStatus = 'open' | 'disputed' | 'resolved' | 'dismissed';@@ -53,7 +54,117 @@ export interface TaskRisks {/** Shown wherever audits show: what an audit is and isn't. */export const NOT_A_PASS_TEXT = 'An audit never marks work passed or failed. Only checks do that, so “no risks raised” is not a pass.';export const SETTING_HINT =- 'On important tasks, or ones nothing outside the bot will check, a second bot challenges the work with evidence and the owner answers once. An audit never marks work passed or failed, and each audit uses tokens.';+ 'On important tasks, or ones nothing outside the bot will check, a second bot challenges the work with evidence and the owner answers once. Routine runs without a check are double-checked on their first run and then at most once a week. An audit never marks work passed or failed, and each audit uses tokens.';++/** A running audit turn, as `GET /api/turns` and the turn-started event carry it (14a). */+export interface AuditTurn {+ audit_id: string;+ task_id: string;+ task_title: string;+ source_kind: string;+ trigger: string;+ stage: string;+ challenger_kwant_id: string;+ owner_kwant_id: string;+}++/** What is being double-checked, in the person's words. */+const WORK_KIND: Record<string, string> = { routine: 'routine run', delegation: 'hand-off' };+/** Why it earned a second check. */+export const AUDIT_WHY: Record<string, string> = {+ low_confidence: 'nothing else checks it',+ high_impact: 'it’s marked high priority',+ manual: 'you asked for it',+};++export interface AuditWho {+ challenger?: string | null;+ owner?: string | null;+ /** The task's title; a routine run's "Routine: " prefix is dropped. */+ title?: string | null;+ sourceKind?: string | null;+ trigger?: string | null;+ /** `rebuttal`: the owner is answering. Anything else: the challenger is checking. */+ stage?: string | null;+}++const possessive = (n: string) => (n.endsWith('s') ? `${n}’` : `${n}’s`);++/** "routine run “Daily digest”", "hand-off", "task “Fix the footer”". */+export function auditWork(sourceKind: string | null | undefined, title: string | null | undefined): string {+ const kind = WORK_KIND[sourceKind ?? ''] ?? 'task';+ const t = (title ?? '').replace(/^Routine:\s*/, '').trim();+ return t ? `${kind} “${t}”` : kind;+}++export type AuditTense = 'now' | 'will' | 'started' | 'done';++/**+ * One plain line for who is double-checking whose work, and why (14a). `subject: false` drops the+ * first name, for places already under that bot's name (the sidebar). `tense`: `started` for the+ * activity log, `done` for a finished audit, `will` for a queued one. A missing name reads+ * "A teammate" / "a teammate’s"; the audit's internals are never named.+ */+export function auditWhyLine(w: AuditWho, opts: { subject?: boolean; tense?: AuditTense } = {}): string {+ const subject = opts.subject !== false;+ const tense = opts.tense ?? 'now';+ const challenger = w.challenger?.trim() || null;+ const owner = w.owner?.trim() || null;+ const work = auditWork(w.sourceKind, w.title);+ const why = AUDIT_WHY[w.trigger ?? ''];+ const tail = why ? `: ${why}.` : '.';+ const cap = (v: string) => v[0].toUpperCase() + v.slice(1);+ if (w.stage === 'rebuttal' && tense === 'now') {+ const by = challenger ? `${possessive(challenger)} double-check` : 'a double-check';+ const head = subject ? `${owner ?? 'A teammate'} is answering` : 'Answering';+ return `${head} ${by} of the ${work}${tail}`;+ }+ const whose = owner ? possessive(owner) : 'a teammate’s';+ const verb = { now: 'is double-checking', will: 'will double-check', started: 'started double-checking', done: 'double-checked' }[tense];+ const head = subject ? `${challenger ?? 'A teammate'} ${verb}` : cap(verb.replace(/^is /, ''));+ return `${head} ${whose} ${work}${tail}`;+}++/** The heading of one audit on its task (the task itself is on screen, so no title). */+export function auditHeaderLine(a: Pick<Audit, 'status' | 'trigger' | 'challenger_kwant_id' | 'owner_kwant_id'>, names: Record<string, string>, sourceKind?: string | null): string {+ const tense: AuditTense = a.status === 'queued' ? 'will' : auditLive(a) ? 'now' : a.status === 'done' ? 'done' : 'started';+ return auditWhyLine({ challenger: names[a.challenger_kwant_id], owner: names[a.owner_kwant_id], sourceKind, trigger: a.trigger }, { tense });+}++/** The line for a running audit turn, with names looked up. */+export function auditTurnLine(a: AuditTurn, names: Record<string, string>, opts: { subject?: boolean } = {}): string {+ return auditWhyLine(+ { challenger: names[a.challenger_kwant_id], owner: names[a.owner_kwant_id], title: a.task_title, sourceKind: a.source_kind, trigger: a.trigger, stage: a.stage },+ opts,+ );+}++/**+ * The short line for compact places (sidebar busy line, Live now chip, header pill): the bot is+ * already the row's name, so it says which work, with no reason and no period (14a). The full+ * `auditTurnLine` goes in the tooltip.+ */+export function auditShortLine(a: AuditTurn, names: Record<string, string>): string {+ const t = (a.task_title ?? '').replace(/^Routine:\s*/, '').trim();+ const owner = names[a.owner_kwant_id]?.trim();+ const what = t ? `“${t}”` : `${owner ? possessive(owner) : 'a teammate’s'} ${WORK_KIND[a.source_kind] ?? 'task'}`;+ return a.stage === 'rebuttal' ? `Answering the double-check of ${what}` : `Double-checking ${what}`;+}++/** "today at 8:15 PM" today, "on Nov 7, 8:15 PM" another day. */+const when = (iso: string | null | undefined, now: number): string | null => {+ const c = localClock(iso, now);+ return c ? `${c.includes(',') ? 'on' : 'today at'} ${c}` : null;+};++/** Why a routine run went unchecked: "this routine was double-checked today at 9:00 AM; next check from Nov 14, 9:00 AM". */+export function routineSkipText(lastAuditAt: string | null | undefined, nextFrom: string | null | undefined, now: number = Date.now()): string {+ const last = when(lastAuditAt, now);+ const next = when(nextFrom, now);+ if (last && next) return `this routine was double-checked ${last}; next check from ${next.replace(/^on /, '')}`;+ if (last) return `this routine was double-checked ${last}`;+ return 'this routine was double-checked in the last week';+}export const unresolved = (r: Pick<Risk, 'status'>) => r.status === 'open' || r.status === 'disputed';diff --git a/frontend/src/botStatus.ts b/frontend/src/botStatus.tsindex d5205075..f0a6cc53 100644--- a/frontend/src/botStatus.ts+++ b/frontend/src/botStatus.ts@@ -1,6 +1,8 @@// One status per bot for the dot on its avatar: what it's doing right now, from its turns and whether// anything can run. A bot with a running turn is never "Available", the open chat included.+import { AuditTurn, auditShortLine, auditTurnLine } from './auditor';+export type BotStatus = 'needs_you' | 'working' | 'queued' | 'cant_run' | 'available';export interface StatusTurn {@@ -8,6 +10,8 @@ export interface StatusTurn {kwant_id: string;state: 'queued' | 'running';context_id?: string;+ /** 14a: an audit's hidden turn. */+ audit?: AuditTurn;}export interface StatusInputs {@@ -68,17 +72,27 @@ export const STATUS_DOT: Record<BotStatus, string> = {* The line under each busy bot's name. Running beats queued so it agrees with the dot; other chats* come before the open one, which reads "here" instead of naming itself.*/-export function busyLines({ turns, openCtx, awaiting, browser, describe }: {+export function busyLines({ turns, openCtx, awaiting, browser, describe, names, titles }: {turns: Iterable<StatusTurn>;openCtx: string;awaiting?: ReadonlySet<string>;browser?: ReadonlySet<string>;describe: (contextId: string, kwantId: string) => string;+ /** Bot names, for an audit turn's line (14a). */+ names?: Record<string, string>;+ /** Filled with the full who-and-why line for each bot whose line is an audit's, for its tooltip (14a). */+ titles?: Record<string, string>;}): Record<string, string> {const out: Record<string, string> = {};const later = (t: StatusTurn) => (t.state === 'queued' ? 2 : 0) + (t.context_id === openCtx ? 1 : 0);for (const t of [...turns].sort((x, y) => later(x) - later(y))) {if (!t?.kwant_id || out[t.kwant_id]) continue;+ // 14a: an audit's turn says whose work it double-checks and why, not "Working here".+ if (t.audit && t.state === 'running' && !browser?.has(t.turn_id) && !awaiting?.has(t.turn_id)) {+ out[t.kwant_id] = auditShortLine(t.audit, names ?? {});+ if (titles) titles[t.kwant_id] = auditTurnLine(t.audit, names ?? {}, { subject: false });+ continue;+ }const what = t.state === 'queued' ? 'Waiting to work' : browser?.has(t.turn_id) ? 'Needs you in the browser' : awaiting?.has(t.turn_id) ? 'Asked you a question' : 'Working';out[t.kwant_id] =t.context_id === openCtx ? `${what} here` : `${what} ${t.state === 'queued' || what === 'Working' ? 'on' : 'in'} ${describe(t.context_id ?? '', t.kwant_id)}`;diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsxindex c8cd6518..ca18a4a5 100644--- a/frontend/src/components/MissionBoardView.tsx+++ b/frontend/src/components/MissionBoardView.tsx@@ -1156,9 +1156,9 @@ export const LiveStrip: React.FC<{type="button"onClick={onOpen ? () => onOpen(b) : undefined}disabled={!onOpen}- title={`${b.name}: ${b.what}${b.more ? ` (+${b.more} more)` : ''}. Open the conversation.`}+ title={`${b.name}: ${(b.kind === 'audit' && b.title ? b.title : b.what).replace(/\.$/, '')}${b.more ? ` (+${b.more} more)` : ''}. ${b.kind === 'audit' ? 'Open the task.' : 'Open the conversation.'}`}className={`group flex items-center gap-2 w-[220px] sm:w-[240px] min-h-[44px] px-2 py-1.5 rounded-xl border text-left ${- b.kind === 'task' ? 'border-sky-500/30 bg-sky-500/5 hover:bg-sky-500/10' : 'border-emerald-500/25 bg-emerald-500/5 hover:bg-emerald-500/10'+ b.kind === 'task' || b.kind === 'audit' ? 'border-sky-500/30 bg-sky-500/5 hover:bg-sky-500/10' : 'border-emerald-500/25 bg-emerald-500/5 hover:bg-emerald-500/10'} ${focusRing}`}data-live-bot={b.kwantId}data-live-kind={b.kind}@@ -2506,6 +2506,7 @@ export const TaskDetailBody: React.FC<{waiting={waitingCard}onResolve={onResolveRisk}onOpenWaiting={onOpenAuditCard}+ sourceKind={t.source_kind}/>{t.waiting_on.length > 0 && (@@ -3891,7 +3892,7 @@ export const MissionBoardPage: React.FC<{openRisks={riskCounts}now={tick}live={live}- onOpenLive={onOpenPlace ? (b) => onOpenPlace(b.place) : undefined}+ onOpenLive={(b) => (b.kind === 'audit' && b.taskId ? openTask(b.taskId) : onOpenPlace?.(b.place))}teams={teams}groupBy={groupBy}onGroupBy={(g) => {diff --git a/frontend/src/components/RisksSection.tsx b/frontend/src/components/RisksSection.tsxindex 24777d3d..e611802c 100644--- a/frontend/src/components/RisksSection.tsx+++ b/frontend/src/components/RisksSection.tsx@@ -13,7 +13,7 @@ import {auditStatusText,auditTokens,riskState,- triggerLabel,+ auditHeaderLine,unresolved,} from '../auditor';import { formatTokens } from '../missions';@@ -89,7 +89,8 @@ const AuditBlock: React.FC<{canResolve: boolean;busy: boolean;onResolve?: (r: Risk, resolution: RiskResolution) => void;-}> = ({ a, names, canResolve, busy, onResolve }) => {+ sourceKind?: string | null;+}> = ({ a, names, canResolve, busy, onResolve, sourceKind }) => {const challenger = names[a.challenger_kwant_id] || 'A bot';const owner = names[a.owner_kwant_id] || 'The owner';const tokens = auditTokens(a);@@ -97,12 +98,16 @@ const AuditBlock: React.FC<{return (<li className="space-y-2" data-audit={a.id} data-audit-status={a.status}><div className="text-[11px] text-zinc-400 break-words">- <span className="font-medium text-zinc-200">Audit by {challenger}</span>- <span> · {triggerLabel(a.trigger)}</span>- {tokens > 0 && <span className="tabular-nums"> · {formatTokens(tokens)} tokens</span>}- <span className="block" data-audit-line>- {auditStatusText(a, names)}+ <span className="font-medium text-zinc-200" data-audit-who>+ {auditHeaderLine(a, names, sourceKind).replace(/\.$/, '')}</span>+ {tokens > 0 && <span className="tabular-nums"> · {formatTokens(tokens)} tokens</span>}+ {a.status !== 'challenge' && (+ // While challenging, the heading above already says who is double-checking (14a).+ <span className="block" data-audit-line>+ {auditStatusText(a, names)}+ </span>+ )}</div>{chipState(fresh) !== 'R3' && (<div className="relative flex flex-wrap gap-1.5">@@ -130,7 +135,9 @@ export const RisksSection: React.FC<{waiting?: AuditWaiting | null;onResolve?: (r: Risk, resolution: RiskResolution) => void;onOpenWaiting?: (w: AuditWaiting) => void;-}> = ({ data, names, canResolve = true, busy = false, waiting = null, onResolve, onOpenWaiting }) => {+ /** The task's source, so the heading can say "routine run" or "hand-off" (14a). */+ sourceKind?: string | null;+}> = ({ data, names, canResolve = true, busy = false, waiting = null, onResolve, onOpenWaiting, sourceKind }) => {if (!data || data.audits.length === 0) return null;const open = data.open_risks;return (@@ -159,7 +166,7 @@ export const RisksSection: React.FC<{)}<ul className="space-y-3">{data.audits.map((a) => (- <AuditBlock key={a.id} a={a} names={names} canResolve={canResolve} busy={busy} onResolve={onResolve} />+ <AuditBlock key={a.id} a={a} names={names} canResolve={canResolve} busy={busy} onResolve={onResolve} sourceKind={sourceKind} />))}</ul><p className="text-[11px] text-zinc-500" data-not-a-pass>diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsxindex 01244aa2..804cd786 100644--- a/frontend/src/components/Sidebar.tsx+++ b/frontend/src/components/Sidebar.tsx@@ -115,6 +115,8 @@ export interface SidebarProps {selectedTeamId?: string | null;/** What busy bots are doing ("Working on …", "Working here"), shown under their name. */busyKwants?: Record<string, string>;+ /** The full line behind a short busy line (an audit's who and why, 14a), for its tooltip. */+ busyTitles?: Record<string, string>;/** Teammates who already replied in a team turn now waiting on the person: "Done · replied in @team". */doneKwants?: Record<string, string>;/** Busy bots' status for the avatar dot; bots not listed are Available (or Can't run). */@@ -365,6 +367,7 @@ export const Sidebar: React.FC<SidebarProps> = ({isChannel,selectedTeamId,busyKwants = {},+ busyTitles,doneKwants = {},botStatus = {},needsYou = {},@@ -692,7 +695,7 @@ export const Sidebar: React.FC<SidebarProps> = ({className={`flex items-center gap-1.5 text-meta truncate${actionRoom} ${warn || asked ? 'text-warn' : attLine ? attTone : status === 'queued' ? 'text-zinc-300' : 'text-[#b8adff]'}`}- title={busyLine}+ title={busyLine === busyKwants[k.id] ? busyTitles?.[k.id] ?? busyLine : busyLine}data-bot-busy><spandiff --git a/frontend/src/missions.ts b/frontend/src/missions.tsindex 72575a3e..5d45b090 100644--- a/frontend/src/missions.ts+++ b/frontend/src/missions.ts@@ -9,6 +9,7 @@ import { PersonCancelledError, personFetch } from './auth';import { relativeTime } from './away';import { Capabilities, CapabilityChange, CapabilityChangedEvent, ENGINE_CANT_SANDBOX, ProposalDecision, ProposalStatus, Scorecard, TaskTier, Tier, TierProposal } from './flightSchool';import type { Risk, RiskResolution, TaskRisks } from './auditor';+import { AuditTurn, auditShortLine, auditTurnLine, auditWhyLine, routineSkipText } from './auditor';import { Dispute, DisputeStatus, Fact, FactChangedEvent, FactDetail, FactDisputeEvent, FactStatus, ledgerSetting } from './truthLedger';export type TaskState = 'backlog' | 'ready' | 'working' | 'needs_you' | 'review' | 'verified' | 'blocked' | 'failed' | 'cancelled';@@ -1520,8 +1521,9 @@ export const safeHttps = (url: string | null | undefined): string | null => {// ---------------------------------------------------------------------------// Activity+const QUIET_EVENTS = new Set(['lessons_held_out', 'audit_fresh_eyes']);/** Events the Activity list leaves out: they have no text for the person. */-export const isQuietEvent = (e: Pick<TaskEvent, 'kind'>): boolean => e.kind === 'lessons_held_out';+export const isQuietEvent = (e: Pick<TaskEvent, 'kind'>): boolean => QUIET_EVENTS.has(e.kind);/** One plain line per event for the activity list. */export function eventText(e: TaskEvent, names: Record<string, string> = {}): string {@@ -1598,8 +1600,15 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): strreturn str(d.status) === 'stale' ? 'A proposed change went out of date, so nothing changed' : `${Who} ${str(d.status) === 'rejected' ? 'rejected' : 'approved'} a proposed change`;case 'workflow_change_applied':return 'The approved change was applied';- case 'audit_started':- return `An audit started: ${actorName(str(d.challenger) ?? '', null, names)} challenges the work`;+ case 'audit_started': {+ // 14a: who is double-checking whose work, and why. Older events have no owner: "a teammate's".+ const challenger = str(d.challenger);+ const owner = str(d.owner);+ return auditWhyLine(+ { challenger: challenger ? names[challenger] : null, owner: owner ? names[owner] : null, sourceKind: str(d.source_kind), trigger: str(d.trigger) },+ { tense: 'started' },+ ).replace(/\.$/, '');+ }case 'audit_challenge':return `${Who} raised ${typeof d.risks === 'number' ? (d.risks === 1 ? '1 risk' : `${d.risks} risks`) : 'risks'} in the audit`;case 'audit_rebuttal':@@ -1607,7 +1616,7 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): strcase 'audit_done':return str(d.status) === 'done' ? 'The audit finished. It doesn’t change whether the task passed' : `The audit ended: ${str(d.status) ?? 'stopped'}`;case 'audit_skipped':- return `No audit: ${str(d.reason) === 'daily_cap' ? 'today’s limit was reached' : str(d.reason) === 'no_challenger' ? 'no other bot could challenge it' : str(d.reason) === 'task_moved' ? 'the task moved on' : 'skipped'}`;+ return `No audit: ${str(d.reason) === 'daily_cap' ? 'today’s limit was reached' : str(d.reason) === 'no_challenger' ? 'no other bot could challenge it' : str(d.reason) === 'task_moved' ? 'the task moved on' : str(d.reason) === 'routine_recently_checked' ? routineSkipText(str(d.last_audit_at), str(d.next_audit_from)) : 'skipped'}`;case 'risk_resolved':return `${Who} ${str(d.resolution) === 'dismissed' ? 'dismissed' : 'resolved'} a risk`;case 'self_checked':@@ -1619,6 +1628,9 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): strcase 'lessons_held_out':// A measurement holdout. It says nothing the person can use, so the Activity list leaves it out.return '';+ case 'audit_fresh_eyes':+ // The audit's own "Checked with fresh eyes" label says this in plain words (14a).+ return '';case 'class_changed':return `${Who} changed its kind of work${str(d.to) ? ` to ${str(d.to)}` : ''}`;default:@@ -1990,6 +2002,8 @@ export interface BoardTurn {state: 'queued' | 'running';since?: string;purpose?: string;+ /** 14a: set on an audit's hidden turn. */+ audit?: AuditTurn;}export interface BoardTeam {@@ -2174,7 +2188,9 @@ export interface LiveBot {teamName: string;/** One line: what it is doing. */what: string;- kind: 'task' | 'room' | 'thread' | 'chat' | 'deciding';+ /** The full line for its tooltip, when `what` is a short form (an audit's, 14a). */+ title?: string;+ kind: 'task' | 'audit' | 'room' | 'thread' | 'chat' | 'deciding';since?: string;/** Where clicking it goes. */place: ChatPlace;@@ -2195,7 +2211,7 @@ export interface LiveContext {}/** What one running turn is about, and where it happens. */-export function describeTurn(turn: BoardTurn, ctx: LiveContext): Pick<LiveBot, 'what' | 'kind' | 'place' | 'taskId'> {+export function describeTurn(turn: BoardTurn, ctx: LiveContext): Pick<LiveBot, 'what' | 'title' | 'kind' | 'place' | 'taskId'> {const room = ctx.rooms?.[turn.context_id];const place: ChatPlace = room !== undefined? { channelId: turn.context_id, kwantId: null, threadId: turn.thread_id }@@ -2204,6 +2220,10 @@ export function describeTurn(turn: BoardTurn, ctx: LiveContext): Pick<LiveBot, 'const task = (ctx.tasks ?? []).find((t) => t.state === 'working' && taskBot(t) === turn.kwant_id && (turn.thread_id ? t.thread_id === turn.thread_id : !t.thread_id && (t.channel_id ?? t.direct_kwant_id) === turn.context_id),);+ // 14a: an audit's turn says who is double-checking whose work and why, and opens that task.+ if (turn.audit) {+ return { what: auditShortLine(turn.audit, ctx.names), title: auditTurnLine(turn.audit, ctx.names, { subject: false }), kind: 'audit', place, taskId: turn.audit.task_id || null };+ }if (task) return { what: task.title, kind: 'task', place, taskId: task.id };if (turn.purpose === 'decide') return { what: 'Deciding how to answer', kind: 'deciding', place, taskId: null };if (room !== undefined) return { what: `In ${room || 'a room'}`, kind: 'room', place, taskId: null };diff --git a/frontend/src/threads.ts b/frontend/src/threads.tsindex 567b18ec..cc783519 100644--- a/frontend/src/threads.ts+++ b/frontend/src/threads.ts@@ -31,6 +31,8 @@ export interface ActiveTurn {since?: string;/** "decide": a consult or decide turn of the decide-first gate. */purpose?: string;+ /** 14a: an audit's hidden turn, with whose work it double-checks and why. */+ audit?: import('./auditor').AuditTurn;/** A running turn's steps so far (like `meta.activity`), so a page opened mid-turn can show them. */activity?: unknown;}@@ -179,6 +181,7 @@ export function applyTurnEvent(turns: TurnMap, ev: { type?: string; data?: any }state: 'running',seq: prev?.seq ?? ++seqCounter,since: prev?.since ?? new Date().toISOString(),+ ...((d.audit ?? prev?.audit) ? { audit: d.audit ?? prev?.audit } : {}),},};}diff --git a/frontend/tests/auditor.test.mjs b/frontend/tests/auditor.test.mjsindex 4c159cba..741394b3 100644--- a/frontend/tests/auditor.test.mjs+++ b/frontend/tests/auditor.test.mjs@@ -59,8 +59,8 @@ test('open: risk, evidence, count, tokens and person-only buttons', () => {assert.match(html, /data-open-risks="1"/);assert.match(html, /The yearly discount is not in the copy\./);assert.match(html, /Evidence: <\/span>docs\/pricing\.md/);- assert.match(html, /Audit by Architect/);- assert.match(html, /high or urgent task/);+ assert.match(html, /Architect double-checked Ann’s task: it’s marked high priority</);+ assert.doesNotMatch(html, /Swarm Auditor|Audit by/);assert.match(html, /15\.4k tokens/);assert.match(html, /data-risk-status="open"/);assert.match(html, />Resolve</);@@ -107,7 +107,10 @@ test('waiting: a live audit stalled on an approval card says so and links to it'assert.match(html, /Audit waiting for your answer/);assert.match(html, /Architect asked for your OK\. The audit stays paused until you answer\./);assert.match(html, /data-open-audit-card/);- assert.match(html, /Architect is challenging the work\./);+ // 14a: the heading already says who is double-checking, so the status line doesn't repeat it.+ assert.doesNotMatch(html, /is challenging the work/);+ assert.doesNotMatch(html, /data-audit-line/);+ assert.match(html, /data-audit-who="true">Architect is double-checking Ann’s task/);assert.deepEqual(a.auditCardPlace(w), { channelId: null, kwantId: 'k_arch', threadId: null });});@@ -160,10 +163,25 @@ test('board badge counts only unresolved risks per task', () => {test('activity lines for audit events', () => {const ev = (kind, detail = {}, actor = 'kwant') => m.eventText({ id: 1, task_id: 't1', mission_id: null, kind, actor, actor_name: null, from_state: null, to_state: null, detail, created_at: '' }, names);- assert.equal(ev('audit_started', { challenger: 'k_arch' }), 'An audit started: Architect challenges the work');+ // 14a: who double-checks whose work, and why; an event from before 14a has no owner.+ assert.equal(ev('audit_started', { challenger: 'k_arch' }), 'Architect started double-checking a teammate’s task');+ assert.equal(+ ev('audit_started', { challenger: 'k_arch', owner: 'k_ann', source_kind: 'routine', trigger: 'low_confidence' }),+ 'Architect started double-checking Ann’s routine run: nothing else checks it',+ );assert.equal(ev('audit_challenge', { risks: 2 }, 'k_arch'), 'Architect raised 2 risks in the audit');assert.equal(ev('audit_done', { status: 'done' }), 'The audit finished. It doesn’t change whether the task passed');assert.equal(ev('audit_skipped', { reason: 'daily_cap' }), 'No audit: today’s limit was reached');+ const skipped = ev('audit_skipped', { reason: 'routine_recently_checked', last_audit_at: '2026-10-29T10:00:00Z', next_audit_from: '2026-11-05T10:00:00Z' });+ assert.match(skipped, /^No audit: this routine was double-checked on Oct 29, .+; next check from Nov 5, \d.+$/);+ // Same day: "today at", so it isn't any 5:03 PM.+ const now = Date.parse('2026-11-14T17:30:00Z');+ const today = a.routineSkipText('2026-11-14T17:03:00Z', '2026-11-21T17:03:00Z', now);+ assert.match(today, /^this routine was double-checked today at \d{1,2}:03\s?[AP]M; next check from Nov 21, \d{1,2}:03\s?[AP]M$/);+ assert.match(a.routineSkipText('2026-11-14T17:03:00Z', null, now), /^this routine was double-checked today at /);+ // The raw fresh-eyes event stays out of Activity; the audit's own label says it.+ assert.equal(ev('audit_fresh_eyes', { verdict: 'ok' }, 'k_arch'), '');+ assert.equal(ev('audit_skipped', { reason: 'routine_recently_checked' }), 'No audit: this routine was double-checked in the last week');assert.equal(ev('risk_resolved', { resolution: 'dismissed' }, 'person'), 'You dismissed a risk');});@@ -173,6 +191,7 @@ test('settings: off by default, cap clamped, hidden on servers without it', () =assert.deepEqual(a.parseAuditorSettings({ auditor: 'on' }), { auditor: 'on', auditor_daily_cap: 5 });assert.equal(a.parseAuditorSettings({}), null);assert.match(a.SETTING_HINT, /never marks work passed or failed, and each audit uses tokens/);+ assert.match(a.SETTING_HINT, /Routine runs without a check are double-checked on their first run and then at most once a week\./);const src = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');assert.match(src, /id="auditor"/);assert.match(src, /\.\.\.\(auditor \?\? \{\}\)/, 'saved only when the server has it');@@ -184,3 +203,63 @@ test('a 403 on resolve hides the buttons; resolving re-reads the risks', () => {assert.match(fn, /status === 403\) setCanResolveRisks\(false\)/);assert.match(fn, /await loadRisks\(taskId\)/);});++// ---------- 14a: who is double-checking whose work, and why ----------++test('the who-and-why line: routine run, high priority, hand-off, manual', () => {+ const routine = { challenger: 'Ben', owner: 'Ann', title: 'Routine: Daily digest', sourceKind: 'routine', trigger: 'low_confidence' };+ assert.equal(a.auditWhyLine(routine), 'Ben is double-checking Ann’s routine run “Daily digest”: nothing else checks it.');+ assert.equal(a.auditWhyLine({ ...routine, trigger: 'high_impact' }), 'Ben is double-checking Ann’s routine run “Daily digest”: it’s marked high priority.');+ assert.equal(a.auditWhyLine({ ...routine, sourceKind: 'delegation', title: 'Fix the footer' }), 'Ben is double-checking Ann’s hand-off “Fix the footer”: nothing else checks it.');+ assert.equal(a.auditWhyLine({ ...routine, sourceKind: 'person', title: 'Fix the footer', trigger: 'manual' }), 'Ben is double-checking Ann’s task “Fix the footer”: you asked for it.');+ assert.equal(a.auditWhyLine({ ...routine, trigger: 'something_new' }), 'Ben is double-checking Ann’s routine run “Daily digest”.');+ // Under the bot's own name the subject goes; in the log it is past.+ assert.equal(a.auditWhyLine(routine, { subject: false }), 'Double-checking Ann’s routine run “Daily digest”: nothing else checks it.');+ assert.equal(a.auditWhyLine(routine, { tense: 'started' }), 'Ben started double-checking Ann’s routine run “Daily digest”: nothing else checks it.');+ assert.equal(a.auditWhyLine(routine, { tense: 'done' }), 'Ben double-checked Ann’s routine run “Daily digest”: nothing else checks it.');+ // The owner's answer turn.+ assert.equal(a.auditWhyLine({ ...routine, stage: 'rebuttal' }), 'Ann is answering Ben’s double-check of the routine run “Daily digest”: nothing else checks it.');+ assert.equal(a.auditWhyLine({ ...routine, stage: 'rebuttal' }, { subject: false }), 'Answering Ben’s double-check of the routine run “Daily digest”: nothing else checks it.');+ // A name ending in s.+ assert.equal(a.auditWhyLine({ ...routine, owner: 'Atlas' }), 'Ben is double-checking Atlas’ routine run “Daily digest”: nothing else checks it.');+});++test('the who-and-why line with a missing name or title', () => {+ assert.equal(a.auditWhyLine({ challenger: 'Ben', owner: null, title: 'Routine: Daily digest', sourceKind: 'routine', trigger: 'low_confidence' }), 'Ben is double-checking a teammate’s routine run “Daily digest”: nothing else checks it.');+ assert.equal(a.auditWhyLine({ challenger: ' ', owner: 'Ann', sourceKind: 'routine', trigger: 'high_impact' }), 'A teammate is double-checking Ann’s routine run: it’s marked high priority.');+ assert.equal(a.auditWhyLine({ challenger: 'Ben', owner: undefined, stage: 'rebuttal', trigger: 'low_confidence' }), 'A teammate is answering Ben’s double-check of the task: nothing else checks it.');+ assert.equal(a.auditWork('routine', 'Routine: '), 'routine run');+});++test('a running audit turn: names looked up, internals never shown', () => {+ const turn = { audit_id: 'a1', task_id: 't1', task_title: 'Routine: Daily digest', source_kind: 'routine', trigger: 'low_confidence', stage: 'challenge', challenger_kwant_id: 'k_arch', owner_kwant_id: 'k_ann' };+ const line = a.auditTurnLine(turn, names);+ assert.equal(line, 'Architect is double-checking Ann’s routine run “Daily digest”: nothing else checks it.');+ assert.doesNotMatch(line, /Swarm|Auditor|audit_|prompt/i);+ assert.equal(a.auditTurnLine({ ...turn, owner_kwant_id: 'k_gone' }, names), 'Architect is double-checking a teammate’s routine run “Daily digest”: nothing else checks it.');+});++test('the short line for compact places: the work first, no period', () => {+ const turn = { audit_id: 'a1', task_id: 't1', task_title: 'Routine: Weekly report', source_kind: 'routine', trigger: 'low_confidence', stage: 'challenge', challenger_kwant_id: 'k_arch', owner_kwant_id: 'k_ann' };+ // A title: just its name.+ assert.equal(a.auditShortLine(turn, names), 'Double-checking “Weekly report”');+ // No title, with an owner.+ assert.equal(a.auditShortLine({ ...turn, task_title: 'Routine: ' }, names), 'Double-checking Ann’s routine run');+ assert.equal(a.auditShortLine({ ...turn, task_title: '', source_kind: 'delegation' }, names), 'Double-checking Ann’s hand-off');+ // No title and no owner name.+ assert.equal(a.auditShortLine({ ...turn, task_title: '', owner_kwant_id: 'k_gone', source_kind: 'person' }, names), 'Double-checking a teammate’s task');+ // The owner's answer.+ assert.equal(a.auditShortLine({ ...turn, stage: 'rebuttal' }, names), 'Answering the double-check of “Weekly report”');+ for (const t of [turn, { ...turn, stage: 'rebuttal' }, { ...turn, task_title: '' }]) assert.doesNotMatch(a.auditShortLine(t, names), /\.$|Swarm|Auditor|audit_/);+});++test('the audit heading on its task follows the audit status', () => {+ const h = (status, sk) => a.auditHeaderLine(audit({ status, trigger: 'low_confidence' }), names, sk);+ assert.equal(h('queued', 'routine'), 'Architect will double-check Ann’s routine run: nothing else checks it.');+ assert.equal(h('challenge', 'routine'), 'Architect is double-checking Ann’s routine run: nothing else checks it.');+ assert.equal(h('rebuttal', 'routine'), 'Architect is double-checking Ann’s routine run: nothing else checks it.');+ assert.equal(h('done', 'routine'), 'Architect double-checked Ann’s routine run: nothing else checks it.');+ assert.equal(h('failed', null), 'Architect started double-checking Ann’s task: nothing else checks it.');+ const html = ui.risks({ data: data([audit({ status: 'challenge', trigger: 'low_confidence' })]), names, sourceKind: 'routine' });+ assert.match(html, /data-audit-who="true">Architect is double-checking Ann’s routine run: nothing else checks it</);+});diff --git a/frontend/tests/botStatus.test.mjs b/frontend/tests/botStatus.test.mjsindex 43fdf6dd..6b301353 100644--- a/frontend/tests/botStatus.test.mjs+++ b/frontend/tests/botStatus.test.mjs@@ -151,3 +151,32 @@ test('the line says when a bot waits on the person, here or elsewhere', () => {});assert.deepEqual(lines, { ed: 'Asked you a question here', lin: 'Needs you in the browser in Engineering Room', rig: 'Asked you a question in Release notes' });});++test('an audit turn says whose work it double-checks and why, here or elsewhere (14a)', () => {+ const audit = { audit_id: 'a1', task_id: 't1', task_title: 'Routine: Daily digest', source_kind: 'routine', trigger: 'low_confidence', stage: 'challenge', challenger_kwant_id: 'ben', owner_kwant_id: 'ann' };+ const titles = {};+ const lines = s.busyLines({+ turns: [{ ...turn('a', 'ben', 'ben'), audit }, { ...turn('b', 'ann', 'open'), audit: { ...audit, stage: 'rebuttal', trigger: 'high_impact' } }],+ openCtx: 'open',+ describe,+ names: { ben: 'Ben', ann: 'Ann' },+ titles,+ });+ // The visible line names the work, short and without a period; the tooltip has who and why.+ assert.equal(lines.ben, 'Double-checking “Daily digest”');+ assert.equal(lines.ann, 'Answering the double-check of “Daily digest”');+ assert.deepEqual(titles, {+ ben: 'Double-checking Ann’s routine run “Daily digest”: nothing else checks it.',+ ann: 'Answering Ben’s double-check of the routine run “Daily digest”: it’s marked high priority.',+ });+ // Waiting on the person still says so.+ const asked = s.busyLines({ turns: [{ ...turn('a', 'ben', 'ben'), audit }], openCtx: 'open', describe, awaiting: new Set(['a']) });+ assert.equal(asked.ben, 'Asked you a question in another conversation');+ // No names: "a teammate's".+ assert.equal(s.busyLines({ turns: [{ ...turn('a', 'ben', 'ben'), audit }], openCtx: 'open', describe }).ben, 'Double-checking “Daily digest”');+ assert.equal(s.busyLines({ turns: [{ ...turn('a', 'ben', 'ben'), audit: { ...audit, task_title: '' } }], openCtx: 'open', describe }).ben, 'Double-checking a teammate’s routine run');+ // An ordinary turn gets no tooltip entry.+ const none = {};+ s.busyLines({ turns: [turn('a', 'ben', 'x')], openCtx: 'open', describe, titles: none });+ assert.deepEqual(none, {});+});diff --git a/frontend/tests/lessons.test.mjs b/frontend/tests/lessons.test.mjsindex 76f63832..de549943 100644--- a/frontend/tests/lessons.test.mjs+++ b/frontend/tests/lessons.test.mjs@@ -89,8 +89,9 @@ test('eventText: self_checked, lessons_shown and lessons_held_out', () => {assert.equal(m.eventText(ev('lessons_held_out', { keys: ['a'] })), '');});-test('isQuietEvent: only the holdout is left out of Activity', () => {+test('isQuietEvent: the holdout and the fresh-eyes event are left out of Activity', () => {assert.equal(m.isQuietEvent(ev('lessons_held_out')), true);+ assert.equal(m.isQuietEvent(ev('audit_fresh_eyes')), true);assert.equal(m.isQuietEvent(ev('lessons_shown')), false);assert.equal(m.isQuietEvent(ev('self_checked')), false);});diff --git a/frontend/tests/missionBoardLive.test.mjs b/frontend/tests/missionBoardLive.test.mjsindex 398b94f1..51c71d6c 100644--- a/frontend/tests/missionBoardLive.test.mjs+++ b/frontend/tests/missionBoardLive.test.mjs@@ -3,6 +3,7 @@// showing only the last day unless the person asks for older.import assert from 'node:assert/strict';import test from 'node:test';+import { readFileSync } from 'node:fs';import { loadBundled } from './bundle.mjs';const store = new Map();@@ -421,3 +422,18 @@ test('card actions can ask for keepalive, so they finish after the page closes',{ url: '/api/tasks/t1/reject', keepalive: false },]);});++test('an audit turn on the Live strip says who is double-checking whose work and why, and opens the task (14a)', () => {+ const audit = { audit_id: 'a1', task_id: 'tk_dig', task_title: 'Routine: Daily digest', source_kind: 'routine', trigger: 'high_impact', stage: 'challenge', challenger_kwant_id: 'k_tw', owner_kwant_id: 'k_gone' };+ const d = m.describeTurn(turn({ purpose: 'audit', audit }), { names, teams, tasks: [] });+ assert.equal(d.kind, 'audit');+ assert.equal(d.taskId, 'tk_dig');+ assert.equal(d.what, 'Double-checking “Daily digest”');+ assert.equal(d.title, 'Double-checking a teammate’s routine run “Daily digest”: it’s marked high priority.');+ // The chip's tooltip uses the full line.+ const src = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');+ assert.match(src, /b\.kind === 'audit' && b\.title \? b\.title : b\.what/);+ // Even when the bot also has a working task in that chat, the audit turn says it is the audit.+ const own = task({ state: 'working', owner_kwant_id: 'k_tw', title: 'Something else', channel_id: null, direct_kwant_id: 'k_tw' });+ assert.equal(m.describeTurn(turn({ audit }), { names, teams, tasks: [own] }).kind, 'audit');+});diff --git a/frontend/tests/threads.test.mjs b/frontend/tests/threads.test.mjsindex 30d68752..e272fdb8 100644--- a/frontend/tests/threads.test.mjs+++ b/frontend/tests/threads.test.mjs@@ -324,3 +324,11 @@ test('App refetches open hand-offs on a reconnect, and live updates and stops guassert.match(live, /noteLiveDelegation\(dl\.id\);/);assert.equal(app.match(/noteLiveDelegation\(next\.id\);/g)?.length, 2, 'both Stop paths');});++test('turn_started keeps an audit turn’s who-and-why (14a)', () => {+ const audit = { audit_id: 'a1', task_id: 't1', task_title: 'Routine: Daily digest', source_kind: 'routine', trigger: 'low_confidence', stage: 'challenge', challenger_kwant_id: 'ben', owner_kwant_id: 'ann' };+ let m = t.applyTurnEvent({}, ev('turn_started', { turn_id: 'x', kwant_id: 'ben', context_id: 'ben', audit }));+ assert.deepEqual(m.x.audit, audit);+ m = t.applyTurnEvent({}, ev('turn_started', { turn_id: 'y', kwant_id: 'ben', context_id: 'ben' }));+ assert.equal('audit' in m.y, false);+});diff --git a/src/db/auditor.rs b/src/db/auditor.rsindex b3f0b13a..14773413 100644--- a/src/db/auditor.rs+++ b/src/db/auditor.rs@@ -62,6 +62,16 @@ impl Risk {}}+/// A routine's latest audit (see [`Database::last_routine_audit`]).+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct RoutineAudit {+ pub audit_id: String,+ pub task_id: String,+ pub created_at: DateTime<Utc>,+ /// The routine's fingerprint when it was audited ([`crate::server::missions::auditor::routine_fingerprint`]).+ pub fingerprint: Option<String>,+}+/// A challenge's risk before it's stored.#[derive(Debug, Clone, PartialEq)]pub struct NewRisk {@@ -214,6 +224,25 @@ impl Database {Ok(n)}+ /// The latest audit of any run of `routine_id` that checked (or is checking) it: queued, in a+ /// stage or done, not skipped, failed or interrupted. With the routine fingerprint its+ /// `audit_started` event recorded (`None` for audits from before 14a).+ pub async fn last_routine_audit(&self, routine_id: &str) -> Result<Option<RoutineAudit>, DbError> {+ Ok(sqlx::query_as::<_, RoutineAudit>(+ "SELECT a.id AS audit_id, a.task_id, a.created_at, \+ (SELECT json_extract(e.detail, '$.routine_fp') FROM task_events e \+ WHERE e.task_id = a.task_id AND e.kind = 'audit_started' AND json_valid(e.detail) \+ AND json_extract(e.detail, '$.audit_id') = a.id LIMIT 1) AS fingerprint \+ FROM task_audits a JOIN tasks t ON t.id = a.task_id AND t.source_kind = 'routine' \+ JOIN routine_runs r ON r.id = t.source_id \+ WHERE r.routine_id = ? AND a.status IN ('queued', 'challenge', 'rebuttal', 'done') \+ ORDER BY a.created_at DESC, a.rowid DESC LIMIT 1",+ )+ .bind(routine_id)+ .fetch_optional(&self.pool)+ .await?)+ }+/// How many audits each bot challenged since `since`.pub async fn challenges_since(&self, since: DateTime<Utc>) -> Result<Vec<(String, i64)>, DbError> {Ok(sqlx::query_as("SELECT challenger_kwant_id, COUNT(*) FROM task_audits WHERE created_at >= ? GROUP BY challenger_kwant_id")diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex f4797eba..c4e3f561 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -76,6 +76,10 @@ pub enum RuntimeEvent {/// Set when the turn runs in a thread (then `context_id` is the thread id too).#[serde(default, skip_serializing_if = "Option::is_none")]thread_id: Option<String>,+ /// An audit turn's who and why (`server::turns::AuditTurn`), so the app can say whose work+ /// is being double-checked. Boxed so the event (held across awaits in turn futures) stays small.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ audit: Option<Box<serde_json::Value>>,},/// A kwant's turn is over, however it ended: "completed", "failed" or "cancelled".#[serde(rename = "turn_ended", alias = "TurnEnded")]diff --git a/src/server/activity.rs b/src/server/activity.rsindex 24d18e6e..33a4d398 100644--- a/src/server/activity.rs+++ b/src/server/activity.rs@@ -257,6 +257,7 @@ mod tests {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,};let tag = TurnTag { turn_id: "turn-view-test".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };let turn = TurnActivity::start(broadcast::channel(16).0, tag);@@ -283,6 +284,7 @@ mod tests {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,};let token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789";let (tx, mut rx) = broadcast::channel(16);diff --git a/src/server/bot_status.rs b/src/server/bot_status.rsindex 8d960b23..6b76c998 100644--- a/src/server/bot_status.rs+++ b/src/server/bot_status.rs@@ -1055,6 +1055,7 @@ mod tests {state: "running".into(),since,purpose: None,+ audit: None,},signals: TurnSignals { engine: Some("Claude"), live_steps: Some(true), ..Default::default() },wait: None,diff --git a/src/server/missions/auditor.rs b/src/server/missions/auditor.rsindex b48d667d..69eed05a 100644--- a/src/server/missions/auditor.rs+++ b/src/server/missions/auditor.rs@@ -2,10 +2,13 @@//! review gets one challenge from a teammate (with evidence) and one rebuttal from its owner; the//! risks left unresolved are listed on the task until the person closes them. An audit never//! verifies or fails a task and never counts agreement as proof: only outcome checks verify (§4).-//! Off by default. See docs/mission-control.md §18.+//! On by default, within a daily cap. A routine run with no check of its own is audited on its+//! first run and after its instructions change, then at most once a week (14a). See+//! docs/mission-control.md §18.use super::routes::{bad, conflict, internal, not_found};-use crate::db::auditor::{audit_json, Answer, Audit, NewRisk};+use crate::db::auditor::{audit_json, Answer, Audit, NewRisk, RoutineAudit};+use crate::db::continuity::RoutineRow;use crate::db::missions::{OutcomeCheck, Task};use crate::db::models::Kwant;use crate::db::spaces::SpaceId;@@ -20,7 +23,7 @@ use axum::{response::{IntoResponse, Response},Json,};-use chrono::{Duration, Utc};+use chrono::{DateTime, Duration, Utc};use serde::Deserialize;use serde_json::{json, Value};use std::collections::HashMap;@@ -111,6 +114,74 @@ pub fn trigger_of(task: &Task, checks: &[OutcomeCheck]) -> Option<&'static str>(super::checks_summary(task, checks)["status"] == "not_checked").then_some("low_confidence")}+/// How long a routine's runs with no check of their own go without a second check once one of+/// them was audited (14a). Its first run, and its first run after its instructions or acceptance+/// changed, are audited whatever the date.+pub const ROUTINE_RECHECK_DAYS: i64 = 7;+/// The `audit_skipped` reason for such a run (with `last_audit_at` and `next_audit_from`).+pub const ROUTINE_CHECKED: &str = "routine_recently_checked";++/// A routine's instructions and acceptance, hashed. An audit of one of its runs records it, so a+/// later run can tell the routine changed since.+pub fn routine_fingerprint(instructions: &str, acceptance: Option<&str>) -> String {+ use sha2::{Digest, Sha256};+ let mut h = Sha256::new();+ h.update(instructions.trim().as_bytes());+ h.update([0u8]);+ h.update(acceptance.map(str::trim).unwrap_or("").as_bytes());+ h.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect()+}++/// Whether a routine run that only a `low_confidence` audit would check gets one, given its+/// routine's latest audit (14a): yes when there is none, when the routine changed since (or that+/// audit is from before fingerprints), and once [`ROUTINE_RECHECK_DAYS`] have passed.+pub fn routine_due(last: Option<&RoutineAudit>, fingerprint: &str, now: DateTime<Utc>) -> bool {+ match last {+ None => true,+ Some(a) => a.fingerprint.as_deref() != Some(fingerprint) || now - a.created_at >= Duration::days(ROUTINE_RECHECK_DAYS),+ }+}++/// The routine a routine run's task came from; `None` for other tasks or a deleted routine.+async fn routine_of(state: &AppState, task: &Task) -> Option<RoutineRow> {+ if task.source_kind != "routine" {+ return None;+ }+ let (routine_id, _) = state.db.routine_run_of(task.source_id.as_deref()?).await.ok().flatten()?;+ state.db.get_routine(&routine_id).await.ok().flatten()+}++/// [`trigger_of`] for a task just in review, except that a routine run's `low_confidence` audit+/// waits its turn ([`routine_due`]): when it isn't due, `audit_skipped` is logged on the task with+/// [`ROUTINE_CHECKED`] and when the routine was last audited, and this is `None`. High impact,+/// hand-offs, goals and every other task are unchanged.+pub async fn review_trigger(state: &AppState, task: &Task) -> Option<&'static str> {+ let checks = state.db.list_checks(&task.id).await.unwrap_or_default();+ let trigger = trigger_of(task, &checks)?;+ if trigger != "low_confidence" {+ return Some(trigger);+ }+ let Some(routine) = routine_of(state, task).await else { return Some(trigger) };+ let last = match state.db.last_routine_audit(&routine.id).await {+ Ok(last) => last,+ Err(e) => {+ tracing::warn!(task_id = %task.id, error = %e, "routine's last audit not read; auditing");+ return Some(trigger);+ }+ };+ let fingerprint = routine_fingerprint(&routine.instructions, routine.acceptance.as_deref());+ match last {+ Some(last) if !routine_due(Some(&last), &fingerprint, Utc::now()) => {+ let next = last.created_at + Duration::days(ROUTINE_RECHECK_DAYS);+ let detail = json!({"reason": ROUTINE_CHECKED, "routine_id": routine.id, "last_audit_at": last.created_at,+ "last_audit_task_id": last.task_id, "next_audit_from": next});+ event(state, &task.id, "audit_skipped", "kwant", detail).await;+ None+ }+ _ => Some(trigger),+ }+}+/// Whether `task` is at or above the auditor's impact bar.pub fn is_high_impact(task: &Task) -> bool {task.priority >= IMPACT_BAR@@ -275,8 +346,7 @@ pub fn on_review(state: &AppState, task: &Task) {if !enabled(&state).await {return;}- let checks = state.db.list_checks(&task.id).await.unwrap_or_default();- if let Some(trigger) = trigger_of(&task, &checks) {+ if let Some(trigger) = review_trigger(&state, &task).await {if let Err(why) = begin(&state, &task, trigger).await {tracing::info!(task_id = %task.id, why, "no audit");}@@ -315,7 +385,14 @@ pub async fn start(state: &AppState, task: &Task, trigger: &str) -> Result<AuditErr(e) => return Err(e.to_string()),};let model = model_mode(state).await;- event(state, &task.id, "audit_started", "kwant", json!({"audit_id": audit.id, "trigger": trigger, "challenger": challenger.id, "pool": pool, "model": model})).await;+ let mut detail = json!({"audit_id": audit.id, "trigger": trigger, "challenger": challenger.id, "owner": owner, "source_kind": task.source_kind,+ "pool": pool, "model": model});+ // What the routine said when its run was audited, so a later run can tell it changed (14a)+ if let Some(r) = routine_of(state, task).await {+ detail["routine_id"] = json!(r.id);+ detail["routine_fp"] = json!(routine_fingerprint(&r.instructions, r.acceptance.as_deref()));+ }+ event(state, &task.id, "audit_started", "kwant", detail).await;Ok(audit)}@@ -477,6 +554,17 @@ async fn run_stage(state: &AppState, audit: &Audit, task: &Task, bot: &Kwant, st}let mut opts = TurnOpts::always_asking("Audit");(opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));+ // So the person sees who is double-checking whose work and why (14a)+ opts.audit = Some(Box::new(crate::server::turns::AuditTurn {+ audit_id: audit.id.clone(),+ task_id: task.id.clone(),+ task_title: task.title.clone(),+ source_kind: task.source_kind.clone(),+ trigger: audit.trigger.clone(),+ stage: stage.into(),+ challenger_kwant_id: audit.challenger_kwant_id.clone(),+ owner_kwant_id: audit.owner_kwant_id.clone(),+ }));// B1: the challenger reviews with fresh eyes (the spec and the result in its prompt,// no chat, notes or history tools); the rebuttal is the owner answering for its workopts.fresh_eyes = stage_is_fresh(stage);diff --git a/src/server/routes.rs b/src/server/routes.rsindex 63bfae94..ebeac127 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -2051,6 +2051,10 @@ pub(super) struct TurnOpts {pub(super) quiet_finish: bool,/// Shown as the turn's `purpose` in `GET /api/turns` (`turns[]`).pub(super) purpose: Option<String>,+ /// An audit turn's who and why, shown with the turn (`audit` in `GET /api/turns` and its+ /// `turn_started` event).+ /// Boxed: turn futures are large and a debug-build test thread overflowed its stack with it inline.+ pub(super) audit: Option<Box<super::turns::AuditTurn>>,/// 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>,/// A Skill Foundry replay (a dry run, see [`super::mcp_runtime::RehearseApprover`]): runs only@@ -2467,6 +2471,7 @@ pub(super) async fn turn_once(state: "running".into(),since: chrono::Utc::now(),purpose: opts.purpose.clone(),+ audit: opts.audit.clone(),});// Kept until the turn ends, so a restart mid-reply is said in the chat (see interrupt_running_turns)let running = crate::db::continuity::RunningTurn {@@ -2492,6 +2497,7 @@ pub(super) async fn turn_once(context_id: Some(tag.context_id.clone()),turn_id: Some(tag.turn_id.clone()),thread_id: tag.thread_id.clone(),+ audit: opts.audit.as_ref().and_then(|a| serde_json::to_value(a).ok()).map(Box::new),});if scope.cancel_token.is_cancelled() {return Err("stopped by the user".into());@@ -3623,6 +3629,7 @@ async fn run_kwant_turn_inner(context_id: Some(tag.context_id.clone()),turn_id: Some(tag.turn_id.clone()),thread_id: tag.thread_id.clone(),+ audit: state.turns.audit_of(&tag.turn_id).map(Box::new),});}// Lets a task handed in during the turn pay for it then (see `super::missions::spend_at_hand_in`)diff --git a/src/server/sse.rs b/src/server/sse.rsindex f491e364..951d4a8c 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -239,7 +239,7 @@ mod tests {E::ApprovalRequired { id: s("a"), tool_name: s("x"), details: json!({}) },E::ApprovalWithdrawn { id: s("a"), answered_via: None, outcome: None },E::TurnComplete { tokens: 1, duration_ms: 1, kwant_id: Some(s("k")), profile_id: None },- E::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: None, thread_id: None },+ E::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: None, thread_id: None, audit: None },E::TurnEnded { kwant_id: s("k"), context_id: None, outcome: s("completed"), turn_id: None, thread_id: None, quiet: false },E::TurnQueued { turn_id: s("x"), kwant_id: s("k"), context_id: None, thread_id: None, position: 1, reason: s("x"), slots: None },E::TurnRunsOn {@@ -446,7 +446,7 @@ mod tests {fn turn_runs_on_is_placed_like_turn_started() {let s = |x: &str| x.to_string();for thread_id in [None, Some(s("th"))] {- let started = RuntimeEvent::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: Some(s("t")), thread_id: thread_id.clone() };+ let started = RuntimeEvent::TurnStarted { kwant_id: s("k"), context_id: Some(s("c")), turn_id: Some(s("t")), thread_id: thread_id.clone(), audit: None };let runs_on = RuntimeEvent::TurnRunsOn {kwant_id: s("k"),turn_id: s("t"),diff --git a/src/server/turns.rs b/src/server/turns.rsindex bccc8cc7..1f8372e5 100644--- a/src/server/turns.rs+++ b/src/server/turns.rs@@ -49,6 +49,26 @@ pub struct ActiveTurn {/// "decide" for the hidden decide-first round's turns (see [`super::decide`]).#[serde(skip_serializing_if = "Option::is_none")]pub purpose: Option<String>,+ /// An audit turn's who and why, so the UI can say whose work is being double-checked.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub audit: Option<Box<AuditTurn>>,+}++/// What an audit turn is about (14a): the task, whose it is, who checks it and why. Ids and the+/// trigger only; the person-facing line is built by the app with the bots' names.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct AuditTurn {+ pub audit_id: String,+ pub task_id: String,+ pub task_title: String,+ /// The task's `source_kind`: `routine`, `delegation`, `person`, ...+ pub source_kind: String,+ /// `high_impact`, `low_confidence` or `manual`.+ pub trigger: String,+ /// `challenge` (the challenger checks) or `rebuttal` (the owner answers).+ pub stage: String,+ pub challenger_kwant_id: String,+ pub owner_kwant_id: String,}#[derive(Default)]@@ -223,6 +243,11 @@ impl TurnRegistry {inner.turns.insert(turn.turn_id.clone(), turn);}+ /// A running audit turn's [`AuditTurn`], as the JSON its `turn_started` event carries.+ pub fn audit_of(&self, turn_id: &str) -> Option<serde_json::Value> {+ self.lock().turns.get(turn_id)?.audit.as_ref().and_then(|a| serde_json::to_value(a).ok())+ }+/// Marks a known turn "queued" or "running" again (an isolated reply waiting for the VM), keeping/// when it started.pub fn set_turn_state(&self, turn_id: &str, state: &str) {@@ -470,6 +495,7 @@ impl TurnRegistry {state: "queued".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});self.note_queue_reason(&tag.turn_id, rx.reason);let _ = events.send(RuntimeEvent::TurnQueued {@@ -791,6 +817,7 @@ mod tests {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});reg.note_screenshot("t", shot("https://a.test/1"));reg.note_screenshot("t", shot("https://a.test/2"));@@ -808,6 +835,7 @@ mod tests {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});assert!(!reg.take_pictures("t").shared_image, "ending the turn forgot them");}@@ -823,6 +851,7 @@ mod tests {state: "running".into(),since: chrono::Utc::now(),purpose: purpose.map(String::from),+ audit: None,};reg.set_turn(turn("a", "k", Some("foundry")));reg.set_turn(turn("b", "k", None));@@ -847,6 +876,7 @@ mod tests {state: state.into(),since: chrono::Utc::now(),purpose: None,+ audit: None,};reg.note_source("t", TurnSource::bot("Ada"));reg.set_turn(turn("queued"));@@ -887,6 +917,7 @@ mod tests {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});assert!(!reg.defer("t", "d1"), "nothing waits before the turn's first hand-off");assert_eq!(reg.hold("t"), Some(true));diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rsindex bd1964ff..d84c9fbe 100644--- a/tests/approvals_off_test.rs+++ b/tests/approvals_off_test.rs@@ -123,6 +123,7 @@ async fn turn_with(e: &Env, bot: &Kwant, opts: mcp_runtime::TurnApprovalOpts) ->state: "running".into(),since: Utc::now(),purpose: None,+ audit: None,});(turn_id, token, folder)}diff --git a/tests/attachments_test.rs b/tests/attachments_test.rsindex c6917834..65740d42 100644--- a/tests/attachments_test.rs+++ b/tests/attachments_test.rs@@ -493,6 +493,7 @@ async fn a_shared_screenshot_posts_as_the_bot_and_counts_for_the_turn() {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});let scope = SelfScope {kwant_id: env.a.clone(),diff --git a/tests/auditor_test.rs b/tests/auditor_test.rsindex c6ff944e..63581f08 100644--- a/tests/auditor_test.rs+++ b/tests/auditor_test.rs@@ -1,5 +1,6 @@//! The Swarm Auditor (Phase D2): which tasks get audited, who challenges, the caps, the two tool-//! calls, and that an audit never verifies, fails or moves a task. Off by default.+//! calls, and that an audit never verifies, fails or moves a task. On by default; a routine run with+//! no check of its own earns its audit (14a).//! Contract: docs/mission-control.md §18.use axum::{@@ -1225,3 +1226,194 @@ async fn a_spec_comes_first_and_the_challenger_checks_against_it() {);assert_ne!(a.challenger_kwant_id, owner.id);}++// 14a: a routine run with no check of its own earns its audit.++async fn routine(e: &Env, owner: &Kwant, name: &str) -> kwnt::db::continuity::RoutineRow {+ e.state.db.create_routine(&routine_input(owner, name, "Post the digest", None)).await.unwrap()+}++fn routine_input(owner: &Kwant, name: &str, instructions: &str, acceptance: Option<&str>) -> kwnt::db::continuity::NewRoutine {+ kwnt::db::continuity::NewRoutine {+ kwant_id: owner.id.clone(),+ channel_id: None,+ name: name.into(),+ instructions: instructions.into(),+ schedule: json!({"kind": "daily", "time": "09:00"}).to_string(),+ enabled: false,+ next_run_at: None,+ thread_id: None,+ context_message_id: None,+ origin: None,+ suggestion_id: None,+ task_class: None,+ acceptance: acceptance.map(String::from),+ checks: None,+ }+}++/// One run of `r` that reached review, as the routine listener makes it (owned, no checks).+async fn run_in_review(e: &Env, r: &kwnt::db::continuity::RoutineRow, priority: i64) -> Task {+ let run = e.state.db.start_routine_run(&r.id, "schedule", "ok", None).await.unwrap();+ let t = NewTask {+ title: format!("Routine: {}", r.name),+ acceptance: r.acceptance.clone().unwrap_or_else(|| r.instructions.clone()),+ state: "review".into(),+ priority,+ owner_kwant_id: Some(r.kwant_id.clone()),+ budget_tokens: 0,+ max_attempts: 3,+ source_kind: "routine".into(),+ source_id: Some(run.id),+ created_by: "kwant".into(),+ ..Default::default()+ };+ e.state.db.create_task(&SpaceId::default_space(), &t).await.unwrap()+}++async fn last_event(e: &Env, tid: &str, kind: &str) -> Value {+ let evs = e.state.db.task_events(tid, 200).await.unwrap();+ evs.into_iter().rev().find(|ev| ev.kind == kind).map(|ev| ev.detail_value()).unwrap_or(Value::Null)+}++/// Audits `t` the way a move to review does, without driving the turns: `Some(trigger)` when it+/// started.+async fn review(e: &Env, t: &Task) -> Option<&'static str> {+ let trigger = auditor::review_trigger(&e.state, t).await?;+ auditor::start(&e.state, t, trigger).await.ok().map(|_| trigger)+}++#[tokio::test]+async fn a_routine_run_is_audited_first_then_at_most_weekly() {+ let e = setup().await;+ let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);+ auditor_on(&e, 50).await;+ let r = routine(&e, &owner, "Daily digest").await;++ // First run: audited, and the audit records what the routine said+ let first = run_in_review(&e, &r, 1).await;+ assert_eq!(review(&e, &first).await, Some("low_confidence"));+ let started = last_event(&e, &first.id, "audit_started").await;+ assert_eq!((started["routine_id"].as_str(), started["owner"].as_str(), started["source_kind"].as_str()), (Some(r.id.as_str()), Some(owner.id.as_str()), Some("routine")), "{started}");+ assert_eq!(started["routine_fp"].as_str(), Some(auditor::routine_fingerprint("Post the digest", None).as_str()), "{started}");++ // Second run the next day: skipped, and the task says why and since when+ let second = run_in_review(&e, &r, 1).await;+ assert_eq!(review(&e, &second).await, None);+ assert!(e.state.db.audits_of(&second.id).await.unwrap().is_empty());+ let skipped = last_event(&e, &second.id, "audit_skipped").await;+ assert_eq!(skipped["reason"], auditor::ROUTINE_CHECKED, "{skipped}");+ assert_eq!(skipped["last_audit_task_id"].as_str(), Some(first.id.as_str()), "{skipped}");+ assert!(skipped["last_audit_at"].is_string() && skipped["next_audit_from"].is_string(), "{skipped}");++ // Six days later still skipped; at seven days due again+ e.state.db.exec_raw_for_test(&format!("UPDATE task_audits SET created_at = '{}' WHERE task_id = '{}'", (chrono::Utc::now() - chrono::Duration::days(6)).to_rfc3339(), first.id)).await.unwrap();+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None, "6 days");+ e.state.db.exec_raw_for_test(&format!("UPDATE task_audits SET created_at = '{}' WHERE task_id = '{}'", (chrono::Utc::now() - chrono::Duration::days(7)).to_rfc3339(), first.id)).await.unwrap();+ let week = run_in_review(&e, &r, 1).await;+ assert_eq!(review(&e, &week).await, Some("low_confidence"), "7 days");+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None, "the weekly one counts as the last");+}++#[tokio::test]+async fn a_routine_run_after_its_instructions_or_acceptance_change_is_audited() {+ let e = setup().await;+ let (owner, other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);+ auditor_on(&e, 50).await;+ let r = routine(&e, &owner, "Daily digest").await;+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"));+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None);++ // New instructions: the next run is audited, the one after isn't+ let r = e.state.db.update_routine(&r.id, &routine_input(&owner, "Daily digest", "Post the digest and the top 3 links", None)).await.unwrap().unwrap();+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"), "instructions changed");+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None);++ // A new acceptance too; renaming it or its schedule isn't a change of what it does+ let r = e.state.db.update_routine(&r.id, &routine_input(&owner, "Daily digest", "Post the digest and the top 3 links", Some("3 links, each opens"))).await.unwrap().unwrap();+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"), "acceptance changed");+ let r = e.state.db.update_routine(&r.id, &routine_input(&owner, "Morning digest", "Post the digest and the top 3 links", Some("3 links, each opens"))).await.unwrap().unwrap();+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None, "renamed only");++ // An audit from before 14a (its event has no fingerprint) doesn't hold the next run back+ let legacy = run_in_review(&e, &r, 1).await;+ e.state.db.create_audit(&legacy.id, &legacy.space_id, 1, "low_confidence", &other.id, &owner.id).await.unwrap().unwrap();+ assert_eq!(e.state.db.last_routine_audit(&r.id).await.unwrap().unwrap().fingerprint, None);+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"), "no fingerprint");+}++#[tokio::test]+async fn an_audit_that_never_checked_does_not_count_for_its_routine() {+ let e = setup().await;+ let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);+ auditor_on(&e, 50).await;+ let r = routine(&e, &owner, "Daily digest").await;+ let first = run_in_review(&e, &r, 1).await;+ assert_eq!(review(&e, &first).await, Some("low_confidence"));+ for status in ["failed", "skipped", "interrupted"] {+ e.state.db.exec_raw_for_test(&format!("UPDATE task_audits SET status = '{status}' WHERE task_id = '{}'", first.id)).await.unwrap();+ let next = run_in_review(&e, &r, 1).await;+ assert_eq!(auditor::review_trigger(&e.state, &next).await, Some("low_confidence"), "{status}");+ }+}++#[tokio::test]+async fn high_priority_routine_runs_hand_offs_and_other_tasks_are_audited_as_before() {+ let e = setup().await;+ let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);+ auditor_on(&e, 50).await;+ let r = routine(&e, &owner, "Daily digest").await;+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, Some("low_confidence"));+ // Marked high priority: audited every run+ for _ in 0..2 {+ assert_eq!(review(&e, &run_in_review(&e, &r, 2).await).await, Some("high_impact"));+ }+ // A low-priority run is still held back by the audits above+ assert_eq!(review(&e, &run_in_review(&e, &r, 1).await).await, None);++ // Hand-offs and person tasks with no check: every one, as before+ for _ in 0..2 {+ let d = task(&e, Some(&owner), 1, "review").await;+ e.state.db.exec_raw_for_test(&format!("UPDATE tasks SET source_kind = 'delegation', source_id = 'd-{}' WHERE id = '{}'", d.id, d.id)).await.unwrap();+ let d = e.state.db.get_task(&d.id).await.unwrap().unwrap();+ assert_eq!(review(&e, &d).await, Some("low_confidence"), "hand-off");+ assert_eq!(review(&e, &task(&e, Some(&owner), 1, "review").await).await, Some("low_confidence"), "person task");+ }+ // A routine run whose routine is gone is treated like any task+ let gone = run_in_review(&e, &r, 1).await;+ e.state.db.delete_routine(&r.id).await.unwrap();+ assert_eq!(auditor::review_trigger(&e.state, &gone).await, Some("low_confidence"));+}++#[tokio::test]+async fn the_daily_cap_still_holds_and_a_capped_run_does_not_count() {+ let e = setup().await;+ let (owner, _other) = (bot(&e, "Ann").await, bot(&e, "Ben").await);+ auditor_on(&e, 1).await;+ let (a, b) = (routine(&e, &owner, "Digest A").await, routine(&e, &owner, "Digest B").await);+ assert_eq!(review(&e, &run_in_review(&e, &a, 1).await).await, Some("low_confidence"));+ // Routine B's first run is due but today's cap is used: skipped for the cap+ let capped = run_in_review(&e, &b, 1).await;+ assert_eq!(auditor::review_trigger(&e.state, &capped).await, Some("low_confidence"));+ assert!(auditor::start(&e.state, &capped, "low_confidence").await.unwrap_err().contains("cap"));+ assert_eq!(last_event(&e, &capped.id, "audit_skipped").await["reason"], "daily_cap");+ // So B's next run is still its first check+ assert_eq!(auditor::review_trigger(&e.state, &run_in_review(&e, &b, 1).await).await, Some("low_confidence"));+}++#[test]+fn routine_due_rules() {+ use kwnt::db::auditor::RoutineAudit;+ let now = chrono::Utc::now();+ let fp = auditor::routine_fingerprint("Post the digest", None);+ assert_eq!(fp, auditor::routine_fingerprint(" Post the digest\n", Some("")), "whitespace and an empty acceptance are no change");+ assert_ne!(fp, auditor::routine_fingerprint("Post the digest", Some("x")));+ assert_ne!(auditor::routine_fingerprint("ab", Some("c")), auditor::routine_fingerprint("a", Some("bc")), "fields are separated");+ let at = |days: i64, fp: Option<&str>| RoutineAudit { audit_id: "a".into(), task_id: "t".into(), created_at: now - chrono::Duration::days(days), fingerprint: fp.map(String::from) };+ assert!(auditor::routine_due(None, &fp, now));+ assert!(!auditor::routine_due(Some(&at(0, Some(&fp))), &fp, now));+ assert!(!auditor::routine_due(Some(&at(6, Some(&fp))), &fp, now));+ assert!(auditor::routine_due(Some(&at(7, Some(&fp))), &fp, now));+ assert!(auditor::routine_due(Some(&at(1, Some("other"))), &fp, now));+ assert!(auditor::routine_due(Some(&at(1, None)), &fp, now));+}diff --git a/tests/away_test.rs b/tests/away_test.rsindex c4445422..916fbcc5 100644--- a/tests/away_test.rs+++ b/tests/away_test.rs@@ -396,6 +396,7 @@ async fn live_approval(app: &Router, state: &AppState, kwant: &kwnt::db::models:state: "running".into(),since: Utc::now(),purpose: None,+ audit: None,});let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve","arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rsindex 01f27817..7c931f74 100644--- a/tests/builtin_tools_test.rs+++ b/tests/builtin_tools_test.rs@@ -194,6 +194,7 @@ async fn turn_in_thread(state: &AppState, bot: &kwnt::db::models::Kwant, turn_idstate: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };mcp_runtime::prepare_turn_with_self(state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1diff --git a/tests/flight_school_scorecard_test.rs b/tests/flight_school_scorecard_test.rsindex aaa80c5d..700e4451 100644--- a/tests/flight_school_scorecard_test.rs+++ b/tests/flight_school_scorecard_test.rs@@ -114,6 +114,7 @@ async fn turn(e: &Env, folder: &Path) -> (String, String) {state: "running".into(),since: Utc::now(),purpose: None,+ audit: None,});(turn_id, token)}diff --git a/tests/flight_school_test.rs b/tests/flight_school_test.rsindex b6c095de..980903df 100644--- a/tests/flight_school_test.rs+++ b/tests/flight_school_test.rs@@ -123,6 +123,7 @@ async fn turn(e: &Env, folder: &Path) -> (String, String) {state: "running".into(),since: Utc::now(),purpose: None,+ audit: None,});(turn_id, token)}diff --git a/tests/kwant_delete_test.rs b/tests/kwant_delete_test.rsindex 2df1dd39..3b3dc25c 100644--- a/tests/kwant_delete_test.rs+++ b/tests/kwant_delete_test.rs@@ -103,6 +103,7 @@ async fn the_person_deletes_any_bot_with_its_history() {state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});let (s, v) = call_as(&app, "DELETE", &format!("/api/kwants/{}", bot.id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::CONFLICT);diff --git a/tests/mission_watch_test.rs b/tests/mission_watch_test.rsindex 23bc466f..ad3023f1 100644--- a/tests/mission_watch_test.rs+++ b/tests/mission_watch_test.rs@@ -125,6 +125,7 @@ async fn turn(e: &Env, bot: &Kwant, purpose: Option<&str>) -> String {state: "running".into(),since: chrono::Utc::now(),purpose: purpose.map(String::from),+ audit: None,});let origin = TurnOrigin { channel_id: Some(e.general.clone()), ..Default::default() };let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), origin: Some(origin), turn_id: Some(turn_id.clone()), ..Default::default() };@@ -498,6 +499,7 @@ fn turn_in(e: &Env, bot: &Kwant, context_id: &str, thread: Option<&str>, purposestate: "running".into(),since: chrono::Utc::now(),purpose: purpose.map(String::from),+ audit: None,});turn_id}diff --git a/tests/payment_floor_test.rs b/tests/payment_floor_test.rsindex 9892f063..d1f7c3b4 100644--- a/tests/payment_floor_test.rs+++ b/tests/payment_floor_test.rs@@ -102,6 +102,7 @@ async fn turn(e: &Env) -> (String, String, TempDir) {state: "running".into(),since: Utc::now(),purpose: None,+ audit: None,});(turn_id, token, folder)}diff --git a/tests/reactions_replies_test.rs b/tests/reactions_replies_test.rsindex 2c155ed8..d64a8965 100644--- a/tests/reactions_replies_test.rs+++ b/tests/reactions_replies_test.rs@@ -207,6 +207,7 @@ async fn a_running_turn_clearing_or_changing_a_reaction_starts_no_second_turn()state: "running".into(),since: chrono::Utc::now(),purpose: None,+ audit: None,});assert_eq!(react(&env, &q.id, json!("up")).await.1["answered"], false);env.state.turns.end_turn("t-busy");diff --git a/tests/smart_approvals_test.rs b/tests/smart_approvals_test.rsindex dd712faf..12eddde5 100644--- a/tests/smart_approvals_test.rs+++ b/tests/smart_approvals_test.rs@@ -125,6 +125,7 @@ async fn ask(e: &Env, tool: &str, input: impl FnOnce(&Path) -> Value) -> Outcomestate: "running".into(),since: Utc::now(),purpose: None,+ audit: None,});let mut events = e.state.event_sender.subscribe();let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",diff --git a/tests/tool_notes_test.rs b/tests/tool_notes_test.rsindex 320a4d53..763d5cb7 100644--- a/tests/tool_notes_test.rs+++ b/tests/tool_notes_test.rs@@ -340,6 +340,7 @@ async fn note_tool_is_only_in_chat_routine_and_hand_off_turns() {state: "running".into(),since: chrono::Utc::now(),purpose: purpose.map(String::from),+ audit: None,});let list = rpc(&env, token, "tools/list", json!({})).await;let r = rpc(&env, token, "tools/call", json!({"name": "note_tool", "arguments": {"tool": "bash", "kind": "tip", "text": format!("from {token}")}})).await;