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.

Open risks UI for the Swarm Auditor

pixel-bot5d7472fa553a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e48c630..2d00f4e3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,7 +25,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
listed on the task until you close it. An audit never verifies, fails or moves a task, and "no risks
raised" isn't a pass. Both turns ask before changing anything; at most 5 audits a day by default.
`GET /api/tasks/:id/risks`, `GET /api/risks`, `POST /api/tasks/:id/audit`, and
- `POST /api/tasks/:id/risks/:risk_id/resolve`. No screen for it yet.
+ `POST /api/tasks/:id/risks/:risk_id/resolve`.
+- **Open risks on tasks.** An audited task's panel lists each audit (who challenged, how far it got,
+ its tokens) and each risk with its evidence and the owner's answer, with Resolve and Dismiss for you.
+ Board cards show how many risks are still open. While an audit waits on one of your approval cards,
+ the task says "Audit waiting for your answer" with a link to it. Settings has the Auditor switch and
+ its daily limit.
### Changed
- **Audits run on the fast model by default.** The Swarm Auditor's challenge and rebuttal turns now use
diff --git a/frontend/src/auditor.ts b/frontend/src/auditor.ts
new file mode 100644
index 00000000..74c9f71c
--- /dev/null
+++ b/frontend/src/auditor.ts
@@ -0,0 +1,178 @@
+// Swarm Auditor (Phase D2, docs/mission-control.md §18): a second bot challenges a task with
+// evidence, the owner answers once, and the risks left unresolved stay listed on the task until the
+// 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';
+
+export type AuditStatus = 'queued' | 'challenge' | 'rebuttal' | 'done' | 'skipped' | 'failed' | 'interrupted';
+export type RiskStatus = 'open' | 'disputed' | 'resolved' | 'dismissed';
+export type RiskResolution = 'resolved' | 'dismissed';
+
+export interface Risk {
+ id: string;
+ audit_id: string;
+ task_id: string;
+ seq: number;
+ risk: string;
+ evidence: string;
+ evidence_ids?: string[];
+ stance: string | null;
+ answer: string | null;
+ answer_evidence: string | null;
+ status: RiskStatus;
+ resolved_by: string | null;
+ resolved_at: string | null;
+ note: string | null;
+ created_at: string;
+ unresolved?: boolean;
+}
+
+export interface Audit {
+ id: string;
+ task_id: string;
+ attempt: number;
+ trigger: string;
+ challenger_kwant_id: string;
+ owner_kwant_id: string;
+ status: AuditStatus;
+ reason: string | null;
+ challenge_tokens: number;
+ rebuttal_tokens: number;
+ created_at: string;
+ finished_at: string | null;
+ risks: Risk[];
+}
+
+export interface TaskRisks {
+ audits: Audit[];
+ open_risks: number;
+}
+
+/** 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.';
+
+export const unresolved = (r: Pick<Risk, 'status'>) => r.status === 'open' || r.status === 'disputed';
+
+export const RISK_STATE: Record<RiskStatus, { label: string; tone: 'amber' | 'rose' | 'emerald' | 'zinc' }> = {
+ open: { label: 'Open', tone: 'amber' },
+ disputed: { label: 'Disputed', tone: 'rose' },
+ resolved: { label: 'Resolved', tone: 'emerald' },
+ dismissed: { label: 'Dismissed', tone: 'zinc' },
+};
+export const riskState = (s: string) => RISK_STATE[s as RiskStatus] ?? { label: s, tone: 'zinc' as const };
+
+/** Is the audit still going (so a card may be waiting on the person)? */
+export const auditLive = (a: Pick<Audit, 'status'>) => a.status === 'queued' || a.status === 'challenge' || a.status === 'rebuttal';
+
+/** The bot whose turn it is, or null when no turn is running. */
+export function auditTurnBot(a: Pick<Audit, 'status' | 'challenger_kwant_id' | 'owner_kwant_id'>): string | null {
+ if (a.status === 'challenge') return a.challenger_kwant_id;
+ if (a.status === 'rebuttal') return a.owner_kwant_id;
+ return null;
+}
+
+const name = (id: string, names: Record<string, string>) => names[id] || 'A bot';
+
+/** One plain line for an audit's state. */
+export function auditStatusText(a: Audit, names: Record<string, string> = {}): string {
+ const challenger = name(a.challenger_kwant_id, names);
+ const owner = name(a.owner_kwant_id, names);
+ switch (a.status) {
+ case 'queued':
+ return `${challenger} will challenge it once the audit before it finishes.`;
+ case 'challenge':
+ return `${challenger} is challenging the work.`;
+ case 'rebuttal':
+ return `${owner} is answering the risks.`;
+ case 'done':
+ return a.risks.length === 0 ? `${challenger} raised no risks. That isn’t a pass.` : `${challenger} raised ${plural(a.risks.length, 'risk')}; ${owner} answered.`;
+ case 'skipped':
+ return `Skipped${a.reason ? `: ${a.reason}` : ''}.`;
+ case 'failed':
+ return `Didn’t finish${a.reason ? `: ${a.reason}` : ''}.`;
+ case 'interrupted':
+ return 'Stopped when the app restarted.';
+ default:
+ return a.status;
+ }
+}
+
+export const TRIGGER_LABELS: Record<string, string> = {
+ high_impact: 'high or urgent task',
+ low_confidence: 'nothing outside the bot checks it',
+ manual: 'started by you',
+};
+export const triggerLabel = (t: string) => TRIGGER_LABELS[t] ?? t.replace(/_/g, ' ');
+
+const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}`;
+
+export function auditTokens(a: Pick<Audit, 'challenge_tokens' | 'rebuttal_tokens'>): number {
+ return Math.max(0, (a.challenge_tokens || 0) + (a.rebuttal_tokens || 0));
+}
+
+/** Board badge: unresolved risks per task, from `GET /api/risks`. */
+export function openRiskCounts(risks: Array<Pick<Risk, 'task_id' | 'status'>>): Record<string, number> {
+ const out: Record<string, number> = {};
+ for (const r of risks) if (unresolved(r)) out[r.task_id] = (out[r.task_id] ?? 0) + 1;
+ return out;
+}
+
+export const riskBadgeText = (n: number) => (n === 1 ? '1 open risk' : `${n} open risks`);
+
+/** A live audit's turn waiting on one of the person's approval cards. */
+export interface AuditWaiting {
+ audit_id: string;
+ kwant_id: string;
+ approval_id: string;
+ /** Where the card is: its own chat when the server says, else the bot's direct chat. */
+ link: AwayLink;
+}
+
+/**
+ * The approval card a live audit is waiting on: a waiting approval from the bot whose turn it is,
+ * asked after the audit started. Audit turns always ask, so this is what stalls an audit.
+ */
+export function auditWaiting(audits: Audit[], waiting: AwayItem[]): AuditWaiting | null {
+ for (const a of audits) {
+ const bot = auditTurnBot(a);
+ if (!bot) continue;
+ const since = Date.parse(a.created_at);
+ const card = waiting
+ .filter((i) => i.kind === 'approval' && i.kwant_id === bot && !(Date.parse(i.timestamp) < since))
+ .sort((x, y) => Date.parse(y.timestamp) - Date.parse(x.timestamp))[0];
+ if (!card) continue;
+ const l = card.link;
+ const link = l && (l.thread_id || l.channel_id || l.direct_kwant_id) ? l : { thread_id: null, channel_id: null, direct_kwant_id: bot };
+ return { audit_id: a.id, kwant_id: bot, approval_id: card.id, link };
+ }
+ return null;
+}
+
+/** Where "Answer in chat" goes for a stalled audit: the card's chat, else the bot's direct chat. */
+export function auditCardPlace(w: AuditWaiting): { channelId: string | null; kwantId: string | null; threadId: string | null } {
+ const l = w.link;
+ if (l.channel_id) return { channelId: l.channel_id, kwantId: null, threadId: l.thread_id };
+ return { channelId: null, kwantId: l.direct_kwant_id ?? w.kwant_id, threadId: l.thread_id };
+}
+
+export interface AuditorSettings {
+ auditor: 'on' | 'off';
+ auditor_daily_cap: number;
+}
+export const DAILY_CAP_MIN = 1;
+export const DAILY_CAP_MAX = 50;
+export const DAILY_CAPS = [1, 2, 3, 5, 10, 20, 50];
+
+/** `auditor` and `auditor_daily_cap` from GET /api/settings; null on a server without the Auditor. */
+export function parseAuditorSettings(data: unknown): AuditorSettings | null {
+ if (!data || typeof data !== 'object') return null;
+ const d = data as Record<string, unknown>;
+ if (d.auditor !== 'on' && d.auditor !== 'off') return null;
+ const cap = typeof d.auditor_daily_cap === 'number' ? Math.max(DAILY_CAP_MIN, Math.min(DAILY_CAP_MAX, Math.round(d.auditor_daily_cap))) : 5;
+ return { auditor: d.auditor, auditor_daily_cap: cap };
+}
+
+/** What a resolve press says afterwards. */
+export const riskResolvedText = (r: RiskResolution) => (r === 'resolved' ? 'Marked resolved. The task’s state doesn’t change.' : 'Dismissed. The task’s state doesn’t change.');
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 9c8a42c7..ce55db5d 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -29,6 +29,9 @@ import {
import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { ModernAvatar } from './ModernAvatar';
import { PerformancePanel } from './PerformancePanel';
+import { RisksSection } from './RisksSection';
+import { AuditWaiting, Risk, RiskResolution, TaskRisks, auditCardPlace, auditLive, auditWaiting, openRiskCounts, riskBadgeText, riskResolvedText } from '../auditor';
+import { awayApi } from '../away';
import { playSfx } from '../audio/chiptune';
import {
ACTION_DONE,
@@ -478,7 +481,9 @@ export const TaskCard: React.FC<{
/** Out of budget: remove its limit and put it back in Ready, from the card. */
onRemoveLimit?: (t: Task) => void;
busy?: boolean;
-}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen, onRemoveLimit, busy = false }) => {
+ /** Unresolved Auditor risks on this task. */
+ openRisks?: number;
+}> = ({ task: t, names, now = Date.now(), showMission = true, onOpen, onRemoveLimit, busy = false, openRisks = 0 }) => {
const owner = (t.owner_kwant_id && names[t.owner_kwant_id]) || t.owner_name;
const checks = checksText(t.checks_summary);
const optionalNote = optionalChecksNote(t.checks_summary);
@@ -513,6 +518,11 @@ export const TaskCard: React.FC<{
<Badge tone="amber">May be invalid</Badge>
</span>
)}
+ {openRisks > 0 && (
+ <span data-risk-badge={openRisks}>
+ <Badge tone="amber">{riskBadgeText(openRisks)}</Badge>
+ </span>
+ )}
{t.state === 'verified' && flags.length > 0 && <Badge tone="emerald">Verified</Badge>}
{t.priority >= 2 && <Badge tone={t.priority >= 3 ? 'rose' : 'amber'}>{priorityLabel(t.priority)}</Badge>}
{showsTier(t) && t.owner_tier !== 'act' && (
@@ -582,7 +592,9 @@ export const Board: React.FC<{
onOpen: (t: Task) => void;
onRemoveLimit?: (t: Task) => void;
busy?: boolean;
-}> = ({ tasks, names, column, now, showMission, onColumn, onOpen, onRemoveLimit, busy }) => {
+ /** Task id → unresolved Auditor risks. */
+ openRisks?: Record<string, number>;
+}> = ({ tasks, names, column, now, showMission, onColumn, onOpen, onRemoveLimit, busy, openRisks = {} }) => {
const grouped = useMemo(() => groupByColumn(tasks), [tasks]);
const tabsId = useId();
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
@@ -600,7 +612,7 @@ export const Board: React.FC<{
return items.length ? (
<ul className="space-y-2">
{items.map((t) => (
- <TaskCard key={t.id} task={t} names={names} now={now} showMission={showMission} onOpen={onOpen} onRemoveLimit={onRemoveLimit} busy={busy} />
+ <TaskCard key={t.id} task={t} names={names} now={now} showMission={showMission} onOpen={onOpen} onRemoveLimit={onRemoveLimit} busy={busy} openRisks={openRisks[t.id] ?? 0} />
))}
</ul>
) : (
@@ -1439,6 +1451,14 @@ export const TaskDetailBody: React.FC<{
onSetBudget?: (budget: number) => void;
/** Out of budget: set the new limit (0 = none) and put it back in Ready. */
onContinueWithLimit?: (budget: number) => void;
+ /** Swarm Auditor: the task's audits and risks (null on a server without them). */
+ risks?: TaskRisks | null;
+ /** A live audit stalled on one of the person's approval cards. */
+ auditWaiting?: AuditWaiting | null;
+ /** False after the server said 403: Resolve and Dismiss go. */
+ canResolveRisks?: boolean;
+ onResolveRisk?: (r: Risk, resolution: RiskResolution) => void;
+ onOpenAuditCard?: (w: AuditWaiting) => void;
}> = ({
detail,
names,
@@ -1464,6 +1484,11 @@ export const TaskDetailBody: React.FC<{
onSetClass,
onSetBudget,
onContinueWithLimit,
+ risks = null,
+ auditWaiting: waitingCard = null,
+ canResolveRisks = true,
+ onResolveRisk,
+ onOpenAuditCard,
}) => {
const t = detail.task;
const limitHit = outOfBudget(t);
@@ -1776,6 +1801,16 @@ export const TaskDetailBody: React.FC<{
</section>
)}
+ <RisksSection
+ data={risks}
+ names={names}
+ canResolve={canResolveRisks}
+ busy={busy}
+ waiting={waitingCard}
+ onResolve={onResolveRisk}
+ onOpenWaiting={onOpenAuditCard}
+ />
+
{t.waiting_on.length > 0 && (
<section aria-labelledby="wait-h" className="space-y-1">
<h4 id="wait-h" className="text-xs font-semibold text-zinc-200">
@@ -2026,6 +2061,8 @@ export interface MissionBoardViewProps {
showPerformance?: boolean;
/** Bumps with each board refresh so Performance reloads too. */
refreshCount?: number;
+ /** Task id → unresolved Auditor risks, for the card badges. */
+ openRisks?: Record<string, number>;
}
export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
@@ -2061,6 +2098,7 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
onRetryGraph,
showPerformance = false,
refreshCount = 0,
+ openRisks,
}) => {
const selectId = useId();
const visibleMissions = missions.filter((m) => m.status !== 'cancelled');
@@ -2220,6 +2258,7 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
onOpen={onOpenTask}
onRemoveLimit={onRemoveLimit}
busy={busyCard}
+ openRisks={openRisks}
/>
)}
@@ -2265,6 +2304,11 @@ export const MissionBoardPage: React.FC<{
const [graphLoading, setGraphLoading] = useState(false);
const [graphError, setGraphError] = useState<string | null>(null);
const [scanning, setScanning] = useState(false);
+ // Swarm Auditor: the open task's audits, the card it waits on, and the board's badge counts.
+ const [risks, setRisks] = useState<TaskRisks | null>(null);
+ const [waitingCard, setWaitingCard] = useState<AuditWaiting | null>(null);
+ const [riskCounts, setRiskCounts] = useState<Record<string, number>>({});
+ const [canResolveRisks, setCanResolveRisks] = useState(true);
// One key per intent: a repeat of the same press (double click, retry after a dropped answer) reuses it.
const pendingKey = useRef<{ what: string; key: string } | null>(null);
const inFlight = useRef(false);
@@ -2280,8 +2324,17 @@ export const MissionBoardPage: React.FC<{
const failMsg = (e: unknown) => (e instanceof Error ? e.message : 'Something went wrong.');
+ // Never blocks the board; a server without the Auditor answers 404 and shows no badges.
+ const loadRiskCounts = useCallback(() => {
+ missionsApi.spaceRisks().then(
+ (rs) => alive.current && setRiskCounts(openRiskCounts(rs)),
+ () => {},
+ );
+ }, []);
+
const load = useCallback(async () => {
setLoading(true);
+ loadRiskCounts();
try {
const [t, m] = await Promise.all([missionsApi.tasks(), missionsApi.missions()]);
if (!alive.current) return;
@@ -2297,6 +2350,25 @@ export const MissionBoardPage: React.FC<{
} finally {
if (alive.current) setLoading(false);
}
+ }, [loadRiskCounts]);
+
+ /** The open task's audits, and while one runs, the approval card it may be stalled on. */
+ const loadRisks = useCallback(async (id: string) => {
+ try {
+ const r = await missionsApi.risks(id);
+ if (!alive.current || openIdRef.current !== id) return;
+ setRisks(r);
+ setRiskCounts((c) => ({ ...c, [id]: r.open_risks }));
+ if (r.audits.some(auditLive)) {
+ const away = await awayApi.get().catch(() => null);
+ if (alive.current && openIdRef.current === id) setWaitingCard(away ? auditWaiting(r.audits, away.waiting) : null);
+ } else setWaitingCard(null);
+ } catch {
+ if (alive.current && openIdRef.current === id) {
+ setRisks(null);
+ setWaitingCard(null);
+ }
+ }
}, []);
const loadDetail = useCallback(async (id: string) => {
@@ -2313,10 +2385,20 @@ export const MissionBoardPage: React.FC<{
if (t.needs_you.some((n) => n.kind === 'workflow_change')) {
missionsApi.workflowChanges('proposed', id).then((cs) => alive.current && openIdRef.current === id && setChanges(cs), () => {});
} else setChanges([]);
+ loadRisks(id);
} catch (e) {
if (alive.current && openIdRef.current === id) setDetailError(failMsg(e));
}
- }, []);
+ }, [loadRisks]);
+
+ // A live audit stalls on the person's cards: look again every 15 s while the task is open.
+ const auditRunning = !!risks?.audits.some(auditLive);
+ useEffect(() => {
+ if (!openId || !auditRunning) return;
+ const id = openId;
+ const timer = window.setInterval(() => loadRisks(id), 15_000);
+ return () => window.clearInterval(timer);
+ }, [openId, auditRunning, loadRisks]);
useEffect(() => {
alive.current = true;
@@ -2360,7 +2442,10 @@ export const MissionBoardPage: React.FC<{
};
const refreshInsights = () => {
if (insightsTimer.current) window.clearTimeout(insightsTimer.current);
- insightsTimer.current = window.setTimeout(() => missionsApi.insights().then((i) => alive.current && setInsights(i), () => {}), 1500);
+ insightsTimer.current = window.setTimeout(() => {
+ missionsApi.insights().then((i) => alive.current && setInsights(i), () => {});
+ loadRiskCounts();
+ }, 1500);
};
const offTask = onMission('task_updated', ({ task }) => {
if (!task || task.space_id !== spaceId) return;
@@ -2379,13 +2464,15 @@ export const MissionBoardPage: React.FC<{
if (insightsTimer.current) window.clearTimeout(insightsTimer.current);
if (graphTimer.current) window.clearTimeout(graphTimer.current);
};
- }, [spaceId, loadDetail, loadGraph]);
+ }, [spaceId, loadDetail, loadGraph, loadRiskCounts]);
const openTask = (id: string) => {
setOpenId(id);
setDetail(null);
setFailures([]);
setChanges([]);
+ setRisks(null);
+ setWaitingCard(null);
setDetailError(null);
setDetailNotice(null);
loadDetail(id);
@@ -2638,6 +2725,32 @@ export const MissionBoardPage: React.FC<{
},
autofixErrorText,
);
+ const resolveRisk = async (r: Risk, resolution: RiskResolution) => {
+ if (!openId || inFlight.current) return;
+ const taskId = openId;
+ inFlight.current = true;
+ setBusy(true);
+ setDetailNotice(null);
+ try {
+ await missionsApi.resolveRisk(taskId, r.id, resolution);
+ if (!alive.current) return;
+ setDetailNotice({ text: riskResolvedText(resolution), error: false });
+ playSfx('click');
+ } catch (e) {
+ if (!alive.current) return;
+ if (e instanceof MissionError && e.status === 401) setNeedsToken(true);
+ if (e instanceof MissionError && e.status === 403) setCanResolveRisks(false);
+ setDetailNotice({
+ text: e instanceof MissionError && e.status === 403 ? 'Only you can close a risk.' : e instanceof MissionError && e.status === 409 ? 'This risk is already closed.' : failMsg(e),
+ error: !(e instanceof MissionError && e.status === 409),
+ });
+ } finally {
+ inFlight.current = false;
+ if (alive.current) setBusy(false);
+ if (alive.current && openIdRef.current === taskId) await loadRisks(taskId);
+ }
+ };
+
const decideChange = (cid: string, approve: boolean) =>
personAction(
`change:${cid}:${approve}`,
@@ -2737,6 +2850,7 @@ export const MissionBoardPage: React.FC<{
onRetryGraph={() => missionId && loadGraph(missionId)}
showPerformance
refreshCount={refreshCount}
+ openRisks={riskCounts}
/>
{openId && (
<TaskPanel title={detail?.task.title ?? listed?.title ?? 'Task'} onClose={closeTask}>
@@ -2762,6 +2876,19 @@ export const MissionBoardPage: React.FC<{
onDecideChange={decideChange}
onRestored={restored}
onRestoreError={restoreError}
+ risks={risks}
+ auditWaiting={waitingCard}
+ canResolveRisks={canResolveRisks}
+ onResolveRisk={resolveRisk}
+ onOpenAuditCard={
+ onOpenChat
+ ? (w) => {
+ const t = detail.task;
+ closeTask();
+ onOpenChat(t, auditCardPlace(w));
+ }
+ : undefined
+ }
onOpenChat={
onOpenChat
? (t, place) => {
diff --git a/frontend/src/components/RisksSection.tsx b/frontend/src/components/RisksSection.tsx
new file mode 100644
index 00000000..106d1544
--- /dev/null
+++ b/frontend/src/components/RisksSection.tsx
@@ -0,0 +1,162 @@
+// Swarm Auditor on the task panel (Phase D2, docs/mission-control.md §18): each audit with who
+// challenged, how far it got and its tokens; each risk with its evidence, the owner's answer and
+// whether it's still open. Only the person closes a risk, and closing one never moves the task.
+import React from 'react';
+import { MessageSquare, ShieldAlert } from 'lucide-react';
+import {
+ Audit,
+ AuditWaiting,
+ NOT_A_PASS_TEXT,
+ Risk,
+ RiskResolution,
+ TaskRisks,
+ auditStatusText,
+ auditTokens,
+ riskState,
+ triggerLabel,
+ unresolved,
+} from '../auditor';
+import { formatTokens } from '../missions';
+
+const TONE: Record<string, string> = {
+ amber: 'bg-amber-500/15 text-amber-200 border-amber-500/30',
+ rose: 'bg-rose-500/15 text-rose-200 border-rose-500/30',
+ emerald: 'bg-emerald-500/15 text-emerald-200 border-emerald-500/30',
+ zinc: 'bg-zinc-800 text-zinc-300 border-zinc-700',
+};
+const btn =
+ 'inline-flex items-center justify-center gap-1.5 min-h-[40px] sm:min-h-[32px] px-3 rounded-lg text-xs font-medium disabled:opacity-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+
+export const WAITING_TITLE = 'Audit waiting for your answer';
+
+const RiskItem: React.FC<{
+ r: Risk;
+ owner: string;
+ canResolve: boolean;
+ busy: boolean;
+ onResolve?: (r: Risk, resolution: RiskResolution) => void;
+}> = ({ r, owner, canResolve, busy, onResolve }) => {
+ const st = riskState(r.status);
+ const open = unresolved(r);
+ return (
+ <li className={`px-3 py-2 rounded-lg border text-xs space-y-1.5 ${open ? 'border-amber-500/25 bg-amber-500/5' : 'border-zinc-800 bg-zinc-900/30'}`} data-risk={r.id} data-risk-status={r.status}>
+ <div className="flex items-start gap-2">
+ <span className={`shrink-0 px-1.5 py-0.5 rounded border text-[10px] font-medium ${TONE[st.tone]}`}>{st.label}</span>
+ <p className={`flex-1 min-w-0 break-words ${open ? 'text-zinc-100' : 'text-zinc-400'}`}>{r.risk}</p>
+ </div>
+ <p className="text-[11px] text-zinc-400 break-words">
+ <span className="font-medium text-zinc-300">Evidence: </span>
+ {r.evidence}
+ </p>
+ {r.answer && (
+ <div className="text-[11px] text-zinc-400 break-words border-l-2 border-zinc-700 pl-2" data-rebuttal>
+ <span className="font-medium text-zinc-300">
+ {owner} {r.stance === 'disputed' ? 'disputes it' : 'accepts it'}:{' '}
+ </span>
+ {r.answer}
+ {r.answer_evidence && (
+ <span className="block mt-0.5">
+ <span className="font-medium text-zinc-300">Their evidence: </span>
+ {r.answer_evidence}
+ </span>
+ )}
+ </div>
+ )}
+ {!open && (
+ <p className="text-[11px] text-zinc-500" data-closed>
+ You {r.status === 'dismissed' ? 'dismissed' : 'resolved'} it{r.note ? `: ${r.note}` : '.'}
+ </p>
+ )}
+ {open && canResolve && onResolve && (
+ <div className="flex flex-wrap gap-2 pt-0.5" data-risk-actions>
+ <button type="button" disabled={busy} onClick={() => onResolve(r, 'resolved')} className={`${btn} bg-emerald-600 text-white hover:bg-emerald-500`}>
+ Resolve
+ </button>
+ <button type="button" disabled={busy} onClick={() => onResolve(r, 'dismissed')} className={`${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700`}>
+ Dismiss
+ </button>
+ </div>
+ )}
+ </li>
+ );
+};
+
+const AuditBlock: React.FC<{
+ a: Audit;
+ names: Record<string, string>;
+ canResolve: boolean;
+ busy: boolean;
+ onResolve?: (r: Risk, resolution: RiskResolution) => void;
+}> = ({ a, names, canResolve, busy, onResolve }) => {
+ const challenger = names[a.challenger_kwant_id] || 'A bot';
+ const owner = names[a.owner_kwant_id] || 'The owner';
+ const tokens = auditTokens(a);
+ 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>
+ </div>
+ {a.risks.length > 0 && (
+ <ul className="space-y-1.5">
+ {a.risks.map((r) => (
+ <RiskItem key={r.id} r={r} owner={owner} canResolve={canResolve} busy={busy} onResolve={onResolve} />
+ ))}
+ </ul>
+ )}
+ </li>
+ );
+};
+
+/** The task's audits; nothing at all when it has never been audited. */
+export const RisksSection: React.FC<{
+ data: TaskRisks | null;
+ names: Record<string, string>;
+ /** False after a 403: the person-only buttons go. */
+ canResolve?: boolean;
+ busy?: boolean;
+ waiting?: AuditWaiting | null;
+ onResolve?: (r: Risk, resolution: RiskResolution) => void;
+ onOpenWaiting?: (w: AuditWaiting) => void;
+}> = ({ data, names, canResolve = true, busy = false, waiting = null, onResolve, onOpenWaiting }) => {
+ if (!data || data.audits.length === 0) return null;
+ const open = data.open_risks;
+ return (
+ <section aria-labelledby="risks-h" className="space-y-2" data-risks>
+ <h4 id="risks-h" className="flex items-center gap-1.5 text-xs font-semibold text-zinc-200">
+ <ShieldAlert size={13} className={open > 0 ? 'text-amber-300' : 'text-zinc-400'} aria-hidden="true" />
+ Open risks
+ <span className={`min-w-[18px] px-1 rounded-full text-[10px] text-center tabular-nums ${open > 0 ? 'bg-amber-500 text-zinc-950' : 'bg-zinc-800 text-zinc-300'}`} data-open-risks={open}>
+ {open}
+ </span>
+ </h4>
+ {waiting && (
+ <div role="status" className="px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 flex flex-wrap items-center gap-2 text-xs text-amber-100" data-audit-waiting>
+ <span className="flex-1 min-w-[10rem]">
+ <span className="block font-medium">{WAITING_TITLE}</span>
+ <span className="block text-[11px] text-amber-200/80">
+ {names[waiting.kwant_id] || 'A bot'} asked for your OK. The audit stays paused until you answer.
+ </span>
+ </span>
+ {onOpenWaiting && (
+ <button type="button" onClick={() => onOpenWaiting(waiting)} className={`${btn} border border-amber-500/40 hover:bg-amber-500/10`} data-open-audit-card>
+ <MessageSquare size={13} aria-hidden="true" /> Answer in chat
+ </button>
+ )}
+ </div>
+ )}
+ <ul className="space-y-3">
+ {data.audits.map((a) => (
+ <AuditBlock key={a.id} a={a} names={names} canResolve={canResolve} busy={busy} onResolve={onResolve} />
+ ))}
+ </ul>
+ <p className="text-[11px] text-zinc-500" data-not-a-pass>
+ {NOT_A_PASS_TEXT}
+ </p>
+ </section>
+ );
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 2e05b729..a5cbdef2 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -1,4 +1,5 @@
import React, { useState, useEffect, useRef } from 'react';
+import { AuditorSettings, DAILY_CAPS, SETTING_HINT as AUDITOR_HINT, parseAuditorSettings } from '../auditor';
import { Key, Globe, X, Settings, Check, ChevronDown, ChevronRight, LogOut, Bell, AlertTriangle, Layers, Monitor, Volume2, VolumeX, Gauge, MapPin, Vibrate, VibrateOff, Sparkles, KanbanSquare } from 'lucide-react';
import { TURN_LIMITS, TurnLimitKey, limitError } from '../threads';
import { budgetError, budgetValue } from '../chainBudget';
@@ -263,6 +264,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
// null: this server has no Mission board, so the switch stays hidden.
const [missionBoard, setMissionBoard] = useState<boolean | null>(null);
const [autofix, setAutofix] = useState<AutofixSettings | null>(null);
+ // null on a server without the Swarm Auditor: the switch stays hidden and out of the save
+ const [auditor, setAuditor] = useState<AuditorSettings | null>(null);
// null on a server without Flight School: the switch stays hidden and out of the save
const [flightSchool, setFlightSchool] = useState<FlightSchoolSettings | null>(null);
// null until loaded, and on a server without these settings
@@ -336,6 +339,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
setProactive(parseProactiveSettings(data));
setMissionBoard(parseMissionBoardSetting(data));
setAutofix(parseAutofixSettings(data));
+ setAuditor(parseAuditorSettings(data));
setFlightSchool(parseFlightSchoolSettings(data));
setPlace(
typeof data.timezone === 'string'
@@ -420,6 +424,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
...(missionBoard !== null ? { mission_board: missionBoard } : {}),
...(autofix !== null ? { autofix: autofix.autofix, recovery_budget_pct: autofix.recovery_budget_pct } : {}),
...(flightSchool ?? {}),
+ ...(auditor ?? {}),
...(place ? { timezone: place.timezone.trim(), location: place.location.trim() } : {}),
}),
});
@@ -919,6 +924,38 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</SwitchRow>
)}
{flightSchool !== null && <FlightSchoolSetting value={flightSchool} onChange={setFlightSchool} />}
+ {auditor !== null && (
+ <SwitchRow
+ id="auditor"
+ label="Challenge important work with an audit"
+ hint={AUDITOR_HINT}
+ checked={auditor.auditor === 'on'}
+ onToggle={() => setAuditor((a) => (a ? { ...a, auditor: a.auditor === 'on' ? 'off' : 'on' } : a))}
+ >
+ {auditor.auditor === 'on' && (
+ <div className="mt-2 flex flex-wrap items-center gap-2" data-testid="auditor-options">
+ <label htmlFor="auditor-cap" className="text-[11px] text-zinc-300">
+ At most
+ </label>
+ <select
+ id="auditor-cap"
+ value={auditor.auditor_daily_cap}
+ onChange={(e) => setAuditor((a) => (a ? { ...a, auditor_daily_cap: Number(e.target.value) } : a))}
+ className="bg-zinc-950 border border-zinc-800 rounded-lg px-2 py-1.5 text-xs text-zinc-100 focus:border-sky-500 focus:outline-none"
+ >
+ {[...new Set([...DAILY_CAPS, auditor.auditor_daily_cap])]
+ .sort((x, y) => x - y)
+ .map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ <span className="text-[11px] text-zinc-300">{auditor.auditor_daily_cap === 1 ? 'audit' : 'audits'} a day</span>
+ </div>
+ )}
+ </SwitchRow>
+ )}
</fieldset>
)}
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 8ad1eaf5..d20206ac 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -7,6 +7,7 @@
import { PersonCancelledError, personFetch } from './auth';
import { relativeTime } from './away';
import { Capabilities, CapabilityChange, ENGINE_CANT_SANDBOX, TaskTier, Tier } from './flightSchool';
+import type { Risk, RiskResolution, TaskRisks } from './auditor';
export type TaskState = 'backlog' | 'ready' | 'working' | 'needs_you' | 'review' | 'verified' | 'blocked' | 'failed' | 'cancelled';
export type MissionStatus = 'draft' | 'active' | 'done' | 'cancelled';
@@ -1370,6 +1371,18 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
return 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_challenge':
+ return `${Who} raised ${typeof d.risks === 'number' ? (d.risks === 1 ? '1 risk' : `${d.risks} risks`) : 'risks'} in the audit`;
+ case 'audit_rebuttal':
+ return `${Who} answered the audit`;
+ case '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'}`;
+ case 'risk_resolved':
+ return `${Who} ${str(d.resolution) === 'dismissed' ? 'dismissed' : 'resolved'} a risk`;
case 'class_changed':
return `${Who} changed its kind of work${str(d.to) ? ` to ${str(d.to)}` : ''}`;
default:
@@ -1557,6 +1570,13 @@ export const missionsApi = {
cancelAutofix: (id: string, aid: string) => call<AutofixAttempt>(`/api/tasks/${enc(id)}/autofix/${enc(aid)}/cancel`, 'POST', {}),
workflowChanges: (status: WorkflowChangeStatus = 'proposed', taskId?: string) =>
call<WorkflowChange[]>(`/api/workflow-changes?status=${status}${taskId ? `&task_id=${enc(taskId)}` : ''}`),
+ /** Swarm Auditor: the task's audits and their risks. */
+ risks: (id: string) => call<TaskRisks>(`/api/tasks/${enc(id)}/risks`),
+ /** The space's unresolved risks, for the board's badges. */
+ spaceRisks: () => call<{ risks: Risk[] }>('/api/risks').then((r) => r.risks),
+ /** Close a risk (person only). The task's state doesn't change. */
+ resolveRisk: (id: string, riskId: string, resolution: RiskResolution, note?: string) =>
+ call<{ risk: Risk; unresolved: boolean }>(`/api/tasks/${enc(id)}/risks/${enc(riskId)}/resolve`, 'POST', note ? { resolution, note } : { resolution }),
decideChange: (id: string, approve: boolean) => call<WorkflowChange>(`/api/workflow-changes/${enc(id)}/${approve ? 'approve' : 'reject'}`, 'POST', {}),
/** One person action on a task. `run_checks` answers `{checks, task}`, the others the Task. */
act: async (id: string, action: TaskAction, reason?: string): Promise<Task> => {
diff --git a/frontend/tests/auditor.test.mjs b/frontend/tests/auditor.test.mjs
new file mode 100644
index 00000000..4c159cba
--- /dev/null
+++ b/frontend/tests/auditor.test.mjs
@@ -0,0 +1,186 @@
+// Swarm Auditor UI (Phase D2, docs/mission-control.md §18): the task panel's "Open risks" lists each
+// audit and each risk with its evidence and the owner's answer; only the person closes a risk, and
+// after a 403 those buttons go. A live audit stalled on an approval card says so. "No risks raised"
+// is never shown as a pass. Board cards count unresolved risks; Settings has the off-by-default switch.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {}, removeItem: () => {} };
+
+const a = await loadBundled(`export * from './src/auditor';`);
+const m = await loadBundled(`export * from './src/missions';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { RisksSection } from './src/components/RisksSection';
+ import { TaskCard, TaskDetailBody } from './src/components/MissionBoardView';
+ const r = (c, p) => renderToStaticMarkup(React.createElement(c, p));
+ export const risks = (p) => r(RisksSection, p);
+ export const detail = (p) => r(TaskDetailBody, p);
+ export const card = (p) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(TaskCard, p)));
+`);
+
+const names = { k_ann: 'Ann', k_arch: 'Architect' };
+const noop = () => {};
+const risk = (over = {}) => ({
+ id: 'r1', audit_id: 'a1', task_id: 't1', seq: 1, risk: 'The yearly discount is not in the copy.', evidence: 'docs/pricing.md has no “yearly”.',
+ evidence_ids: [], stance: null, answer: null, answer_evidence: null, status: 'open', resolved_by: null, resolved_at: null, note: null,
+ created_at: '2026-10-29T10:00:00Z', ...over,
+});
+const audit = (over = {}) => ({
+ id: 'a1', task_id: 't1', attempt: 1, trigger: 'high_impact', challenger_kwant_id: 'k_arch', owner_kwant_id: 'k_ann', status: 'done', reason: null,
+ challenge_tokens: 12000, rebuttal_tokens: 3400, created_at: '2026-10-29T10:00:00Z', finished_at: '2026-10-29T10:05:00Z', risks: [risk()], ...over,
+});
+const data = (audits) => ({ audits, open_risks: audits.flatMap((x) => x.risks).filter(a.unresolved).length });
+const approval = (over = {}) => ({
+ kind: 'approval', id: 'ap1', kwant_id: 'k_arch', kwant_name: 'Architect', title: 'Use Bash', summary: '', status: 'waiting',
+ timestamp: '2026-10-29T10:01:00Z', link: { thread_id: null, channel_id: null, direct_kwant_id: null }, ...over,
+});
+
+test('none: a task never audited shows no section at all', () => {
+ assert.equal(ui.risks({ data: null, names }), '');
+ assert.equal(ui.risks({ data: { audits: [], open_risks: 0 }, names }), '');
+});
+
+test('no risks raised reads as not a pass', () => {
+ const html = ui.risks({ data: data([audit({ risks: [] })]), names });
+ assert.match(html, /Architect raised no risks\. That isn’t a pass\./);
+ assert.match(html, /“no risks raised” is not a pass/);
+ assert.match(html, /data-open-risks="0"/);
+ assert.doesNotMatch(html, /Verified|passed it/i);
+});
+
+test('open: risk, evidence, count, tokens and person-only buttons', () => {
+ let got = null;
+ const html = ui.risks({ data: data([audit()]), names, onResolve: (r, how) => (got = [r.id, how]) });
+ assert.match(html, /Open risks/);
+ 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, /15\.4k tokens/);
+ assert.match(html, /data-risk-status="open"/);
+ assert.match(html, />Resolve</);
+ assert.match(html, />Dismiss</);
+ assert.equal(got, null);
+});
+
+test('disputed: shows the owner’s answer and evidence, and still counts as unresolved', () => {
+ const r = risk({ stance: 'disputed', answer: 'It is in the FAQ block.', answer_evidence: 'docs/pricing.md line 40', status: 'disputed' });
+ const html = ui.risks({ data: data([audit({ risks: [r] })]), names, onResolve: noop });
+ assert.match(html, /Disputed/);
+ assert.match(html, /Ann disputes it: <\/span>It is in the FAQ block\./);
+ assert.match(html, /Their evidence: <\/span>docs\/pricing\.md line 40/);
+ assert.match(html, /data-open-risks="1"/);
+ assert.match(html, /data-risk-actions/);
+ const accepted = ui.risks({ data: data([audit({ risks: [risk({ stance: 'accepted', answer: 'Fair, will fix.' })] })]), names });
+ assert.match(accepted, /Ann accepts it: /);
+});
+
+test('resolved and dismissed: closed, no buttons, nothing open', () => {
+ const html = ui.risks({
+ data: data([audit({ risks: [risk({ status: 'resolved', note: 'Fixed in the next task' }), risk({ id: 'r2', status: 'dismissed' })] })]),
+ names,
+ onResolve: noop,
+ });
+ assert.match(html, /data-open-risks="0"/);
+ assert.match(html, /You resolved it: Fixed in the next task/);
+ assert.match(html, /You dismissed it\./);
+ assert.doesNotMatch(html, /data-risk-actions/);
+});
+
+test('403: Resolve and Dismiss are hidden, the risks still show', () => {
+ const html = ui.risks({ data: data([audit()]), names, canResolve: false, onResolve: noop });
+ assert.match(html, /The yearly discount/);
+ assert.doesNotMatch(html, /data-risk-actions/);
+ assert.doesNotMatch(html, />Resolve</);
+});
+
+test('waiting: a live audit stalled on an approval card says so and links to it', () => {
+ const live = audit({ status: 'challenge', risks: [], finished_at: null });
+ const w = a.auditWaiting([live], [approval()]);
+ assert.deepEqual(w, { audit_id: 'a1', kwant_id: 'k_arch', approval_id: 'ap1', link: { thread_id: null, channel_id: null, direct_kwant_id: 'k_arch' } });
+ const html = ui.risks({ data: data([live]), names, waiting: w, onOpenWaiting: noop });
+ 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\./);
+ assert.deepEqual(a.auditCardPlace(w), { channelId: null, kwantId: 'k_arch', threadId: null });
+});
+
+test('waiting: only the bot whose turn it is, only cards asked since the audit began', () => {
+ const challenge = audit({ status: 'challenge', risks: [] });
+ assert.equal(a.auditWaiting([challenge], [approval({ kwant_id: 'k_ann' })]), null, 'owner card during the challenge');
+ assert.equal(a.auditWaiting([challenge], [approval({ timestamp: '2026-10-29T09:00:00Z' })]), null, 'card from before the audit');
+ assert.equal(a.auditWaiting([challenge], [approval({ kind: 'question' })]), null, 'questions are not approvals');
+ assert.equal(a.auditWaiting([audit()], [approval()]), null, 'finished audits wait on nothing');
+ const rebuttal = audit({ status: 'rebuttal' });
+ const w = a.auditWaiting([rebuttal], [approval({ kwant_id: 'k_ann', link: { thread_id: 'th1', channel_id: null, direct_kwant_id: 'k_ann' } })]);
+ assert.equal(w.kwant_id, 'k_ann');
+ assert.deepEqual(a.auditCardPlace(w), { channelId: null, kwantId: 'k_ann', threadId: 'th1' });
+ const inChannel = a.auditWaiting([rebuttal], [approval({ kwant_id: 'k_ann', link: { thread_id: null, channel_id: 'c1', direct_kwant_id: null } })]);
+ assert.deepEqual(a.auditCardPlace(inChannel), { channelId: 'c1', kwantId: null, threadId: null });
+});
+
+test('audit lines for each status', () => {
+ assert.match(a.auditStatusText(audit({ status: 'queued' }), names), /Architect will challenge it/);
+ assert.match(a.auditStatusText(audit({ status: 'rebuttal' }), names), /Ann is answering/);
+ assert.match(a.auditStatusText(audit({ risks: [risk(), risk({ id: 'r2' })] }), names), /raised 2 risks; Ann answered/);
+ assert.match(a.auditStatusText(audit({ status: 'failed', reason: 'the challenger’s turn ended without a challenge' }), names), /Didn’t finish: the challenger/);
+ assert.match(a.auditStatusText(audit({ status: 'interrupted' }), names), /restarted/);
+ assert.equal(a.triggerLabel('manual'), 'started by you');
+});
+
+test('board badge counts only unresolved risks per task', () => {
+ const counts = a.openRiskCounts([
+ risk(),
+ risk({ id: 'r2', status: 'disputed' }),
+ risk({ id: 'r3', status: 'resolved' }),
+ risk({ id: 'r4', task_id: 't2', status: 'dismissed' }),
+ risk({ id: 'r5', task_id: 't3' }),
+ ]);
+ assert.deepEqual(counts, { t1: 2, t3: 1 });
+ const t = {
+ id: 't1', space_id: 's1', mission_id: null, mission_title: null, title: 'Write the copy', acceptance: '', state: 'review', priority: 2,
+ owner_kwant_id: 'k_ann', owner_name: 'Ann', suggested_kwant_id: null, budget_tokens: 0, spent_tokens: 0, attempts: 1, max_attempts: 3, blocked_reason: null,
+ source_kind: 'mission', source_id: 'm1', created_by: 'k_arch', finished_at: null, channel_id: null, direct_kwant_id: null, thread_id: null, depends_on: [], waiting_on: [], claim: null, needs_you: [],
+ checks_summary: { status: 'not_checked', passed: 0, failed: 0, total: 0 }, created_at: '2026-10-29T09:00:00Z', updated_at: '2026-10-29T10:00:00Z',
+ };
+ assert.match(ui.card({ task: t, names, onOpen: noop, openRisks: 2 }), /data-risk-badge="2"[^]*2 open risks/);
+ assert.match(ui.card({ task: t, names, onOpen: noop, openRisks: 1 }), /1 open risk</);
+ assert.doesNotMatch(ui.card({ task: t, names, onOpen: noop }), /data-risk-badge/);
+ // The task panel shows the section from the risks prop.
+ const html = ui.detail({ detail: { task: t, checks: [], evidence: [], events: [] }, names, onAction: noop, onApproveCheck: noop, risks: data([audit()]), canResolveRisks: false });
+ assert.match(html, /data-risks/);
+ assert.doesNotMatch(html, /data-risk-actions/);
+});
+
+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');
+ 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');
+ assert.equal(ev('risk_resolved', { resolution: 'dismissed' }, 'person'), 'You dismissed a risk');
+});
+
+test('settings: off by default, cap clamped, hidden on servers without it', () => {
+ assert.deepEqual(a.parseAuditorSettings({ auditor: 'off', auditor_daily_cap: 5 }), { auditor: 'off', auditor_daily_cap: 5 });
+ assert.deepEqual(a.parseAuditorSettings({ auditor: 'on', auditor_daily_cap: 99 }), { auditor: 'on', auditor_daily_cap: 50 });
+ 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/);
+ 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');
+});
+
+test('a 403 on resolve hides the buttons; resolving re-reads the risks', () => {
+ const src = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');
+ const fn = src.slice(src.indexOf('const resolveRisk = async'), src.indexOf('const decideChange ='));
+ assert.match(fn, /status === 403\) setCanResolveRisks\(false\)/);
+ assert.match(fn, /await loadRisks\(taskId\)/);
+});