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.

An audit reads the same everywhere; Activity has no raw event names (16b) (#659)

Oleksandr Ivanchenko0366eaa37e51
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 589a3e6a..617a0f67 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -3561,6 +3561,26 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const awaitingBotHere = awaitingTurnHere ? { id: awaitingTurnHere.kwant_id, name: kwants.find((k) => k.id === awaitingTurnHere.kwant_id)?.name ?? '' } : null;
// The open chat's running turn's live steps (the newest, when several reply at once).
const activityHere = Object.values(activity).filter((a) => a.ctx === openCtx && turns[a.turnId]).pop() ?? null;
+ // 16b: the open chat's running turn double-checks another bot's work (the challenger's own chat).
+ const auditHere = isCurrentContextStreaming ? Object.values(turns).find((t) => t.context_id === openCtx && t.state === 'running' && t.audit)?.audit ?? null : null;
+ const liveAudit = useMemo(
+ () =>
+ auditHere
+ ? {
+ line: auditTurnLine(auditHere, kwantNames),
+ // The phone strip is narrow: the Live now chip's words, the full line stays as its title.
+ short: auditShortLine(auditHere, kwantNames),
+ onOpenTask: missionBoard && auditHere.task_id
+ ? () => {
+ setPendingTaskId(auditHere.task_id);
+ showPage('board');
+ }
+ : undefined,
+ }
+ : null,
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [auditHere?.audit_id, auditHere?.stage, auditHere?.task_title, kwantNames, missionBoard],
+ );
const needsYouByKwant = openStepsByKwant(humanSteps);
const chatQueue = queuedInChat(turns, openCtx);
const asQueued = (t: TrackedTurn): QueuedState => ({
@@ -4451,6 +4471,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
awaitingBrowser={awaitingBrowserHere}
awaitingBot={awaitingBotHere}
liveActivity={isCurrentContextStreaming ? activityHere : null}
+ liveAudit={liveAudit}
renderHumanStep={renderHumanStep}
contextKey={openCtx}
deciding={decidingHere ? { botName: kwantName(decidingHere.kwantId) ?? chatTitle, consulted: decidingHere.consulted } : null}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 5bbcb82c..c365ae81 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -394,6 +394,8 @@ export interface ChatViewProps {
awaitingBot?: { id: string; name: string } | null;
/** The running reply's steps so far (thinking, tools, waits). */
liveActivity?: LiveActivity | null;
+ /** 16b: the running turn double-checks another bot's work: its line and a way to the audited task. */
+ liveAudit?: { line: string; short?: string; onOpenTask?: () => void } | null;
/** Draws a bot's browser-step card (message meta kind "human_step"). */
renderHumanStep?: (msg: ChatMessage, meta: HumanStepMeta, flash: boolean) => React.ReactNode;
/** Changes when another chat opens, so the view jumps to its bottom. */
@@ -635,6 +637,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
awaitingBrowser,
awaitingBot,
liveActivity,
+ liveAudit,
renderHumanStep,
contextKey,
deciding,
@@ -982,6 +985,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
onAnswer={showWaitingCard}
onWatch={onWatchBrowser && !vmOpen ? onWatchBrowser : undefined}
phone={phone}
+ audit={liveAudit}
/>
);
// Cards are last in the stream. While the person follows the chat, keep the bottom pinned when a
@@ -2551,6 +2555,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
? discussionState.currentSpeaker
: streamingSpeakerName || title
}
+ audit={liveAudit}
/>
)}
</div>
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index ca18a4a5..4c469599 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -1157,7 +1157,7 @@ export const LiveStrip: React.FC<{
onClick={onOpen ? () => onOpen(b) : undefined}
disabled={!onOpen}
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 ${
+ className={`group flex items-center gap-2 w-full max-w-[320px] sm:w-[240px] min-h-[44px] px-2 py-1.5 rounded-xl border text-left ${
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}
diff --git a/frontend/src/components/WorkingAvatar.tsx b/frontend/src/components/WorkingAvatar.tsx
index d8a7525d..155dc54e 100644
--- a/frontend/src/components/WorkingAvatar.tsx
+++ b/frontend/src/components/WorkingAvatar.tsx
@@ -8,12 +8,21 @@ const PLUS: Array<[number, number]> = [[18, 1], [17, 2], [19, 2], [18, 3]];
const TIPS: Array<[number, number]> = [[18, 0], [16, 2], [20, 2], [18, 4]];
const LINES: Array<[number, number]> = [[8, 11], [10, 9], [12, 6]]; // [y, width], x = 19
-export const WorkingAvatar: React.FC<{ name: string }> = ({ name }) => {
+export interface WorkingAvatarProps {
+ name: string;
+ /**
+ * 16b: this turn is a double-check of another bot's work. The line says so in the same words as the
+ * bot's status and the Live now chip (`auditTurnLine`), instead of "is working on it".
+ */
+ audit?: { line: string; short?: string; onOpenTask?: () => void } | null;
+}
+
+export const WorkingAvatar: React.FC<WorkingAvatarProps> = ({ name, audit }) => {
// Same role and name as the row's avatar, so the bot at the laptop is the bot in the portrait.
const c = useCreatureFor(name, name);
- const label = `${name} is working on the answer`;
+ const label = audit ? audit.line : `${name} is working on the answer`;
return (
- <div className="kw-wa" role="status" aria-label={label} data-working-avatar="">
+ <div className="kw-wa" role="status" aria-label={label} data-working-avatar="" data-audit={audit ? '' : undefined}>
<svg className="kw-wa-scene" viewBox="0 0 36 18" width={108} height={54} aria-hidden="true" focusable="false">
<rect x={1} y={17} width={35} height={1} fill="var(--kw-wa-ground)" />
<g transform="translate(-5 -2)">
@@ -36,12 +45,23 @@ export const WorkingAvatar: React.FC<{ name: string }> = ({ name }) => {
<rect className="kw-wa-s1" x={18} y={2} width={1} height={1} fill="var(--kw-wa-spark-core)" />
</g>
</svg>
- <p className="kw-wa-text" aria-hidden="true">
- <span className="kw-wa-name">{name}</span> is working on it
- <span className="kw-wa-dots">
- <span className="kw-mood-dot">.</span><span className="kw-mood-dot kw-mood-dot-1">.</span><span className="kw-mood-dot kw-mood-dot-2">.</span>
- </span>
- </p>
+ {audit ? (
+ <div className="kw-wa-text kw-wa-audit">
+ <p aria-hidden="true">{audit.line}</p>
+ {audit.onOpenTask && (
+ <button type="button" className="kw-wa-open" onClick={audit.onOpenTask} data-open-audited-task="">
+ Open the task
+ </button>
+ )}
+ </div>
+ ) : (
+ <p className="kw-wa-text" aria-hidden="true">
+ <span className="kw-wa-name">{name}</span> is working on it
+ <span className="kw-wa-dots">
+ <span className="kw-mood-dot">.</span><span className="kw-mood-dot kw-mood-dot-1">.</span><span className="kw-mood-dot kw-mood-dot-2">.</span>
+ </span>
+ </p>
+ )}
<span className="sr-only">{label}</span>
</div>
);
diff --git a/frontend/src/components/WorkingStrip.tsx b/frontend/src/components/WorkingStrip.tsx
index 49afdee5..ec66d9ed 100644
--- a/frontend/src/components/WorkingStrip.tsx
+++ b/frontend/src/components/WorkingStrip.tsx
@@ -1,7 +1,7 @@
import React, { useEffect, useRef, useState } from 'react';
import { ArrowUp, Square } from 'lucide-react';
import type { LiveActivity } from '../activity';
-import { formatElapsed, turnStart, waitingOn, workingLabel } from '../workingStrip';
+import { formatElapsed, stripSentence, turnStart, waitingOn } from '../workingStrip';
import { usePhoneLayout } from '../usePhoneLayout';
import { ModernAvatar } from './ModernAvatar';
import { WatchButton } from './WatchLive';
@@ -26,6 +26,11 @@ interface WorkingStripProps {
onWatch?: () => void;
/** Forces the phone or desktop look (tests); by default it follows the window. */
phone?: boolean;
+ /**
+ * 16b: the turn double-checks another bot's work: its line replaces "is getting started" / "is working
+ * on it". On a phone, where the live bubble is hidden, the strip also carries "Open the task".
+ */
+ audit?: { line: string; short?: string; onOpenTask?: () => void } | null;
}
/**
@@ -37,7 +42,7 @@ interface WorkingStripProps {
* On desktop (0.8.0) it is the same kind of quiet line at desktop size. Both sit inside the composer
* section (ChatView renders them there; on a phone too since 0.8.1 F4), lined up with the box below.
*/
-export const WorkingStrip: React.FC<WorkingStripProps> = ({ active, name, title, live, queued, awaitingAnswer, awaitingBrowser, writing, onStop, onAnswer, onWatch, phone: forcePhone }) => {
+export const WorkingStrip: React.FC<WorkingStripProps> = ({ active, name, title, live, queued, awaitingAnswer, awaitingBrowser, writing, onStop, onAnswer, onWatch, phone: forcePhone, audit }) => {
const mountedAt = useRef(Date.now());
const [now, setNow] = useState(() => Date.now());
const phoneLayout = usePhoneLayout();
@@ -52,7 +57,7 @@ export const WorkingStrip: React.FC<WorkingStripProps> = ({ active, name, title,
if (!active) return null;
const state = { live, queued, awaitingAnswer, awaitingBrowser, writing };
- const label = workingLabel(state);
+ const sentence = stripSentence(name, state, audit?.line);
const elapsed = formatElapsed(now - turnStart(live, mountedAt.current));
const on = waitingOn(state);
const waiting = !!queued || !!awaitingAnswer || on !== null;
@@ -65,14 +70,25 @@ export const WorkingStrip: React.FC<WorkingStripProps> = ({ active, name, title,
<span className={`shrink-0 inline-flex ${waiting ? '' : 'kw-avatar-working'}`}>
<ModernAvatar role={title} name={name} size={16} />
</span>
- <p className="min-w-0 flex-1 truncate text-xs leading-4 text-zinc-400" role="status" aria-live="polite">
- <span className="font-medium text-zinc-300">{name}</span> is {label}
+ <p className="min-w-0 flex-1 truncate text-xs leading-4 text-zinc-400" role="status" aria-live="polite" title={sentence.audit ? sentence.text : undefined} data-strip-audit={sentence.audit ? '' : undefined}>
+ {sentence.audit ? audit?.short || sentence.text : <><span className="font-medium text-zinc-300">{name}</span>{sentence.text.slice(name.length)}</>}
</p>
+ {sentence.audit && audit?.onOpenTask && !answer && (
+ <button
+ type="button"
+ onClick={audit.onOpenTask}
+ data-open-audited-task=""
+ data-compact=""
+ className="kws-hit -mr-1 shrink-0 inline-flex h-7 items-center rounded-md px-1.5 text-xs font-medium text-[#b8adff] underline underline-offset-2 hover:text-[#d6d0ff] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#b8adff]"
+ >
+ Open the task
+ </button>
+ )}
{/* Hidden behind Answer: what to do next matters more than for how long. Below 400 px with
- Watch showing, the time goes so the line never wraps. */}
+ Watch or "Open the task" showing, the time goes so the line never wraps. */}
{!answer && (
<span
- className={`shrink-0 tabular-nums text-xs leading-4 text-zinc-500${onWatch ? ' hidden min-[400px]:inline' : ''}`}
+ className={`shrink-0 tabular-nums text-xs leading-4 text-zinc-500${onWatch || (sentence.audit && audit?.onOpenTask) ? ' hidden min-[400px]:inline' : ''}`}
aria-hidden="true"
data-working-elapsed=""
>
@@ -122,8 +138,8 @@ export const WorkingStrip: React.FC<WorkingStripProps> = ({ active, name, title,
<span className={`shrink-0 inline-flex ${waiting ? '' : 'kw-avatar-working'}`}>
<ModernAvatar role={title} name={name} size={20} />
</span>
- <p className="min-w-0 flex-1 truncate text-xs leading-4 text-zinc-400" role="status" aria-live="polite">
- <span className="font-medium text-zinc-200">{name}</span> is {label}
+ <p className="min-w-0 flex-1 truncate text-xs leading-4 text-zinc-400" role="status" aria-live="polite" title={sentence.audit ? sentence.text : undefined} data-strip-audit={sentence.audit ? '' : undefined}>
+ {sentence.audit ? sentence.text : <><span className="font-medium text-zinc-200">{name}</span>{sentence.text.slice(name.length)}</>}
</p>
{/* Own box, so a long step name never cuts the time off. Hidden behind Answer, as on the phone. */}
{!answer && (
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 5d45b090..2207e058 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -7,7 +7,7 @@
import { spendStopEventText } from './spendStop';
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 { Capabilities, CapabilityChange, CapabilityChangedEvent, ENGINE_CANT_SANDBOX, ProposalDecision, ProposalStatus, Scorecard, TaskTier, Tier, TierProposal, isTier, tierLabel } 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';
@@ -1521,7 +1521,19 @@ export const safeHttps = (url: string | null | undefined): string | null => {
// ---------------------------------------------------------------------------
// Activity
-const QUIET_EVENTS = new Set(['lessons_held_out', 'audit_fresh_eyes']);
+const QUIET_EVENTS = new Set(['lessons_held_out', 'audit_fresh_eyes', 'checkpoint_pruned']);
+/** "12 files", "1 file". */
+const count = (n: unknown, one: string): string | null => (typeof n === 'number' ? `${n} ${one}${n === 1 ? '' : 's'}` : null);
+/** When a checkpoint was saved, after "saved a checkpoint" (16b). A checkpoint the person saved needs none. */
+const CHECKPOINT_WHEN: Record<string, string> = { before_run: ' before the run', after_run: ' after the run', before_restore: ' before the restore' };
+/** Why the checker (verifier.rs skip_reason) didn't check it, after "Not checked: ". */
+const VERIFIER_SKIP: Record<string, string> = {
+ off: 'the checker is off',
+ kwant_task: 'it’s the app’s own task',
+ round_limit: 'it was already checked the most times allowed',
+ no_checkpoint: 'there was no checkpoint to re-run it from',
+ nothing_to_reproduce: 'there was nothing to re-run',
+};
/** Events the Activity list leaves out: they have no text for the person. */
export const isQuietEvent = (e: Pick<TaskEvent, 'kind'>): boolean => QUIET_EVENTS.has(e.kind);
@@ -1586,6 +1598,9 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
return `AutoFix sent it back to Ready: ${strategyLabel(str(d.strategy) ?? '').toLowerCase()}`;
case 'autofix_scheduled':
return str(d.status) === 'suggested' ? 'AutoFix suggested a retry. It waits for your OK' : `AutoFix planned a retry: ${strategyLabel(str(d.strategy) ?? '').toLowerCase()}`;
+ case 'autofix_held':
+ // The spending-stop wording comes first (spendStop.ts); this is any other hold.
+ return 'AutoFix waits. It retries once it can';
case 'autofix_started':
return 'AutoFix started a retry';
case 'autofix_finished': {
@@ -1633,6 +1648,58 @@ export function eventText(e: TaskEvent, names: Record<string, string> = {}): str
return '';
case 'class_changed':
return `${Who} changed its kind of work${str(d.to) ? ` to ${str(d.to)}` : ''}`;
+ // 16b: checkpoints and the checker (verifier) in plain words, not "Kwant: Checkpoint".
+ case 'checkpoint': {
+ const left = typeof d.skipped === 'number' && d.skipped > 0 ? `${count(d.skipped, 'file')} left out` : null;
+ const parts = [count(d.files, 'file'), formatBytes(typeof d.bytes === 'number' ? d.bytes : null), left].filter(Boolean);
+ return `${Who} saved a checkpoint${CHECKPOINT_WHEN[str(d.kind) ?? ''] ?? ''}${parts.length ? ` (${parts.join(', ')})` : ''}`;
+ }
+ case 'checkpoint_failed':
+ return `${Who} couldn’t save a checkpoint${CHECKPOINT_WHEN[str(d.kind) ?? ''] ?? ''}${str(d.error) ? `: ${str(d.error)}` : ''}`;
+ case 'verifier_started':
+ return typeof d.round === 'number' && d.round > 1 ? `The checker started round ${d.round}` : 'The checker started';
+ case 'verifier_turn': {
+ const bot = str(d.kwant_id) ? names[str(d.kwant_id)!] : null;
+ const how = str(d.difference) === 'model' ? ', on a different AI model' : str(d.difference) === 'tier' ? ', on a different model size' : '';
+ return `${bot ?? 'A teammate'} took on the check${how}`;
+ }
+ case 'verifier_done': {
+ const n = typeof d.findings === 'number' ? d.findings : 0;
+ const missed = Array.isArray(d.couldnt_verify) && d.couldnt_verify.length > 0 ? `. It couldn’t check ${count(d.couldnt_verify.length, 'step')}` : '';
+ const v = str(d.verdict);
+ const head =
+ v === 'pass'
+ ? 'The checker passed it'
+ : v === 'fail'
+ ? `The checker found ${n > 0 ? count(n, 'problem') : 'a problem'}${str(d.next) === 'sent_back' ? ', so it went back for a fix' : str(d.next) === 'escalated' ? ', so it waits for you' : ''}`
+ : 'The checker needs you to look at it';
+ return `${head}${missed}`;
+ }
+ case 'verifier_skipped':
+ return `Not checked: ${VERIFIER_SKIP[str(d.reason) ?? ''] ?? 'the checker skipped it'}`;
+ case 'verdict_overturned':
+ return `${Who} overruled the checker${str(d.to) ? `: ${str(d.to) === 'pass' ? 'it passes' : str(d.to) === 'fail' ? 'it fails' : 'it needs you'}` : ''}`;
+ // Kinds the guard test found falling back to "Kwant: <raw kind>" (16b).
+ case 'watch':
+ return `${Who} moved it to ${stateLabel(e.to_state ?? '').label}${note ? `: ${note}` : ''}`;
+ case 'skipped':
+ return 'Skipped for now';
+ case 'handoff_ended':
+ return str(d.status) === 'completed' ? 'The hand-off finished. Unblock it to review the result' : 'The hand-off stopped. Unblock it to carry on';
+ case 'check_wait_more':
+ return `${Who} gave a check ${typeof d.hours === 'number' ? (d.hours === 1 ? '1 more hour' : `${d.hours} more hours`) : 'more time'}`;
+ case 'skill_drafted_from':
+ return `${Who} drafted a skill from this task`;
+ case 'contract_updated':
+ return `${Who} changed what it needs to count as done`;
+ case 'tier_stepped_down':
+ // isTier first: tierLabel falls back to "Act", which would be wrong for a step down.
+ return isTier(d.to_tier)
+ ? `You rolled it back, so its owner drops to ${tierLabel(d.to_tier)} on this kind of work`
+ : 'You rolled it back, so its owner drops one level on this kind of work';
+ case 'checkpoint_pruned':
+ // Retention housekeeping: an old checkpoint went. Nothing for the person to act on.
+ return '';
default:
return `${Who}: ${humanize(e.kind)}`;
}
diff --git a/frontend/src/styles/stream.css b/frontend/src/styles/stream.css
index 1634b824..a245b384 100644
--- a/frontend/src/styles/stream.css
+++ b/frontend/src/styles/stream.css
@@ -261,6 +261,28 @@
text-overflow: ellipsis;
}
.kw-wa-name { color: var(--kw-wa-name); font-weight: 500; }
+/* 16b: an audit turn says whose work it double-checks. The line wraps (it is a sentence, not a name),
+ so the scene grows past 62 px instead of cutting it off, and "Open the task" sits under it. */
+.kw-wa[data-audit] { height: auto; min-height: 62px; }
+.kw-wa-audit { white-space: normal; overflow: visible; }
+.kw-wa-audit p { margin: 0; overflow-wrap: anywhere; }
+.kw-wa-open {
+ margin-top: 2px;
+ padding: 0;
+ border: 0;
+ background: none;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 500;
+ color: #b8adff;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ cursor: pointer;
+ border-radius: 4px;
+}
+.kw-wa-open:hover { color: #d6d0ff; }
+.kw-wa-open:focus-visible { outline: 2px solid #b8adff; outline-offset: 2px; }
+[data-theme="light"] .kw-wa-open { color: #5b4bc4; }
.kw-wa-dots { display: inline-block; width: 1.1em; }
/* The first words fade in over the place the scene held. */
diff --git a/frontend/src/workingStrip.ts b/frontend/src/workingStrip.ts
index ae53eb18..0fdc3acf 100644
--- a/frontend/src/workingStrip.ts
+++ b/frontend/src/workingStrip.ts
@@ -30,6 +30,18 @@ export function workingLabel(s: WorkingState): string {
return 'getting started';
}
+/**
+ * 16b: the strip's whole sentence. During an audit the generic "is getting started" / "is working on
+ * it" give way to the audit's own line (`auditTurnLine`, which already starts with the bot's name), so
+ * the challenger's chat reads like its status and the Live now chip. A step, the reply or a wait still
+ * says what it is: those are more specific than the audit.
+ */
+export function stripSentence(name: string, s: WorkingState, auditLine?: string | null): { audit: boolean; text: string } {
+ const label = workingLabel(s);
+ if (auditLine && (label === 'getting started' || label === 'working on it')) return { audit: true, text: auditLine };
+ return { audit: false, text: `${name} is ${label}` };
+}
+
/**
* What the bot waits on the person for, so the phone strip can offer "Answer ↑" (spec A3): a question,
* an approval card, or null (working, in line, or a browser step, which has its own card and button).
diff --git a/frontend/tests/auditLineEverywhere.test.mjs b/frontend/tests/auditLineEverywhere.test.mjs
new file mode 100644
index 00000000..de89fe45
--- /dev/null
+++ b/frontend/tests/auditLineEverywhere.test.mjs
@@ -0,0 +1,185 @@
+// 16b (autonomy/audit-line-everywhere/brief.md): an audit reads the same everywhere, and Activity has
+// no raw event names.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`export * from './src/missions'; export { auditTurnLine, auditShortLine } from './src/auditor'; export { stripSentence } from './src/workingStrip';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { WorkingAvatar } from './src/components/WorkingAvatar';
+ import { WorkingStrip } from './src/components/WorkingStrip';
+ export const scene = (props) => renderToStaticMarkup(React.createElement(WorkingAvatar, props));
+ export const strip = (props) => renderToStaticMarkup(React.createElement(WorkingStrip, { active: true, title: 'Writer', ...props }));
+`);
+const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8');
+
+const names = { w: 'Writer', r: 'Researcher' };
+const audit = { audit_id: 'a1', task_id: 't1', task_title: 'Routine: Weekly report', source_kind: 'routine', trigger: 'unchecked', stage: 'challenge', challenger_kwant_id: 'w', owner_kwant_id: 'r' };
+const line = m.auditTurnLine(audit, names);
+const open = () => {};
+
+// --- 1. The live line
+
+test('an audit turn: the live bubble says the audit line and links to the task, not "is working on it"', () => {
+ assert.match(line, /^Writer is double-checking Researcher’s routine run/);
+ const html = ui.scene({ name: 'Writer', audit: { line, onOpenTask: open } });
+ assert.ok(html.includes(`aria-label="${line.replace(/"/g, '&quot;')}"`), 'the status label is the audit line');
+ assert.ok(html.includes('data-audit=""'));
+ assert.doesNotMatch(html, /is working on it/);
+ assert.match(html, /<button type="button" class="kw-wa-open" data-open-audited-task="">Open the task<\/button>/);
+ assert.match(html, /<svg class="kw-wa-scene"/, 'the scene (avatar, animation) stays');
+});
+
+test('an audit turn with no board: the line, no link', () => {
+ const html = ui.scene({ name: 'Writer', audit: { line } });
+ assert.doesNotMatch(html, /Open the task/);
+});
+
+test('a plain turn: the live bubble is unchanged', () => {
+ const html = ui.scene({ name: 'Writer' });
+ assert.match(html, /<span class="kw-wa-name">Writer<\/span> is working on it/);
+ assert.match(html, /aria-label="Writer is working on the answer"/);
+ assert.doesNotMatch(html, /data-audit|Open the task/);
+});
+
+test('the strip: the audit line replaces "getting started" / "working on it", never a step, the reply or a wait', () => {
+ assert.deepEqual(m.stripSentence('Writer', {}, line), { audit: true, text: line });
+ assert.deepEqual(m.stripSentence('Writer', { live: { steps: [{ id: 's', kind: 'tool', status: 'done', title: 'x', started_at: '2026-11-15T03:00:00Z' }] } }, line), { audit: true, text: line });
+ assert.deepEqual(m.stripSentence('Writer', { writing: true }, line), { audit: false, text: 'Writer is writing the reply' });
+ assert.deepEqual(m.stripSentence('Writer', { queued: true }, line), { audit: false, text: 'Writer is waiting in line' });
+ assert.deepEqual(m.stripSentence('Writer', { awaitingAnswer: true }, line), { audit: false, text: 'Writer is waiting for your answer' });
+ assert.deepEqual(m.stripSentence('Writer', {}, null), { audit: false, text: 'Writer is getting started' });
+});
+
+test('the strip on desktop and phone: the audit line, with "Open the task" on the phone (its live bubble is hidden)', () => {
+ const desk = ui.strip({ name: 'Writer', phone: false, audit: { line, onOpenTask: open } });
+ assert.ok(desk.includes('data-strip-audit=""'));
+ assert.doesNotMatch(desk, /is getting started/);
+ const phone = ui.strip({ name: 'Writer', phone: true, audit: { line, onOpenTask: open } });
+ assert.match(phone, /data-open-audited-task=""[^>]*>Open the task<\/button>/);
+ assert.match(phone, /data-working-elapsed=""/);
+ assert.match(phone, /hidden min-\[400px\]:inline/, 'below 400 px the clock gives way to the link');
+ const plain = ui.strip({ name: 'Writer', phone: true });
+ assert.match(plain, /<span class="font-medium text-zinc-300">Writer<\/span> is getting started/);
+ assert.doesNotMatch(plain, /Open the task|data-strip-audit/);
+});
+
+test('the phone strip says the short line; the full line stays as its title, and desktop keeps the full line', () => {
+ const short = m.auditShortLine(audit, names);
+ assert.match(short, /^Double-checking “Weekly report”/);
+ const esc = (x) => x.replace(/"/g, '&quot;');
+ const phone = ui.strip({ name: 'Writer', phone: true, audit: { line, short, onOpenTask: open } });
+ assert.ok(phone.includes(`data-strip-audit="">${short}</p>`), 'phone text is the short line');
+ assert.ok(phone.includes(`title="${esc(line)}"`), 'phone title is the full line');
+ const desk = ui.strip({ name: 'Writer', phone: false, audit: { line, short, onOpenTask: open } });
+ assert.ok(desk.includes(`data-strip-audit="">${line}</p>`), 'desktop text stays the full line');
+ assert.match(read('src/App.tsx'), /short: auditShortLine\(auditHere, kwantNames\)/);
+});
+
+test('App finds the open chat’s running audit turn and opens its task on the board', () => {
+ const app = read('src/App.tsx');
+ assert.match(app, /t\.context_id === openCtx && t\.state === 'running' && t\.audit/);
+ assert.match(app, /line: auditTurnLine\(auditHere, kwantNames\)/);
+ assert.match(app, /setPendingTaskId\(auditHere\.task_id\);\s*showPage\('board'\);/);
+ assert.match(app, /liveAudit=\{liveAudit\}/);
+ const chat = read('src/components/ChatView.tsx');
+ assert.equal((chat.match(/audit=\{liveAudit\}/g) ?? []).length, 2, 'the bubble and the strip');
+});
+
+// --- 2. Activity in plain words
+
+const ev = (kind, detail = {}, extra = {}) => ({ id: 1, task_id: 't', kind, actor: 'kwant', actor_name: null, detail, created_at: '2026-11-15T03:00:00Z', ...extra });
+
+test('checkpoint', () => {
+ assert.equal(m.eventText(ev('checkpoint', { checkpoint_id: 'c', kind: 'after_run', files: 12, bytes: 40960, skipped: 0 })), 'Kwant saved a checkpoint after the run (12 files, 40 KB)');
+ assert.equal(m.eventText(ev('checkpoint', { kind: 'before_run', files: 1, bytes: 10, skipped: 2 })), 'Kwant saved a checkpoint before the run (1 file, 10 B, 2 files left out)');
+ assert.equal(m.eventText(ev('checkpoint', { kind: 'manual' }, { actor: 'person' })), 'You saved a checkpoint');
+});
+
+test('checkpoint_failed', () => {
+ assert.equal(m.eventText(ev('checkpoint_failed', { kind: 'before_run', error: 'the folder is gone' })), 'Kwant couldn’t save a checkpoint before the run: the folder is gone');
+ assert.equal(m.eventText(ev('checkpoint_failed', {})), 'Kwant couldn’t save a checkpoint');
+});
+
+test('verifier_started', () => {
+ assert.equal(m.eventText(ev('verifier_started', { check_id: 'k', round: 1, risk_tier: 'low' })), 'The checker started');
+ assert.equal(m.eventText(ev('verifier_started', { round: 2 })), 'The checker started round 2');
+});
+
+test('verifier_turn', () => {
+ assert.equal(m.eventText(ev('verifier_turn', { kwant_id: 'w', difference: 'model', pin: 'grok' }), names), 'Writer took on the check, on a different AI model');
+ assert.equal(m.eventText(ev('verifier_turn', { kwant_id: 'w', difference: 'tier' }), names), 'Writer took on the check, on a different model size');
+ assert.equal(m.eventText(ev('verifier_turn', { kwant_id: 'gone', difference: 'none' }), names), 'A teammate took on the check');
+});
+
+test('verifier_done', () => {
+ assert.equal(m.eventText(ev('verifier_done', { verdict: 'pass', next: 'counted', findings: 0, couldnt_verify: [] })), 'The checker passed it');
+ assert.equal(m.eventText(ev('verifier_done', { verdict: 'fail', next: 'sent_back', findings: 2, couldnt_verify: [] })), 'The checker found 2 problems, so it went back for a fix');
+ assert.equal(m.eventText(ev('verifier_done', { verdict: 'fail', next: 'escalated', findings: 1, couldnt_verify: [] })), 'The checker found 1 problem, so it waits for you');
+ assert.equal(m.eventText(ev('verifier_done', { verdict: 'needs_you', next: 'held_for_you', findings: 0, couldnt_verify: ['a', 'b'] })), 'The checker needs you to look at it. It couldn’t check 2 steps');
+});
+
+test('verifier_skipped: every reason the server gives', () => {
+ const r = (reason) => m.eventText(ev('verifier_skipped', { reason }));
+ assert.equal(r('off'), 'Not checked: the checker is off');
+ assert.equal(r('kwant_task'), 'Not checked: it’s the app’s own task');
+ assert.equal(r('round_limit'), 'Not checked: it was already checked the most times allowed');
+ assert.equal(r('no_checkpoint'), 'Not checked: there was no checkpoint to re-run it from');
+ assert.equal(r('nothing_to_reproduce'), 'Not checked: there was nothing to re-run');
+ assert.equal(r('new_reason'), 'Not checked: the checker skipped it');
+});
+
+test('tier_stepped_down names the tier it drops to, or says one level when the tier is unknown', () => {
+ const r = (d) => m.eventText(ev('tier_stepped_down', d));
+ assert.equal(r({ from_tier: 'act', to_tier: 'sandbox' }), 'You rolled it back, so its owner drops to Sandbox on this kind of work');
+ assert.equal(r({ from_tier: 'sandbox', to_tier: 'observe' }), 'You rolled it back, so its owner drops to Observe on this kind of work');
+ assert.equal(r({ to_tier: 'mystery' }), 'You rolled it back, so its owner drops one level on this kind of work');
+ assert.equal(r({}), 'You rolled it back, so its owner drops one level on this kind of work');
+});
+
+test('checkpoint_pruned is quiet', () => {
+ assert.equal(m.isQuietEvent({ kind: 'checkpoint_pruned' }), true);
+ assert.equal(m.isQuietEvent({ kind: 'lessons_held_out' }), true);
+ assert.equal(m.isQuietEvent({ kind: 'audit_fresh_eyes' }), true);
+});
+
+// --- 3. The guard: every task event kind the server emits (grep of src/**/*.rs, Nov 15 2026: insert_event,
+// log_task_event, task_event, auditor/verifier event(), TaskChange kinds and literal INSERTs). Add a kind here
+// when the server starts emitting one.
+const SERVER_KINDS = [
+ 'audit_challenge', 'audit_done', 'audit_fresh_eyes', 'audit_rebuttal', 'audit_skipped', 'audit_started',
+ 'autofix_finished', 'autofix_held', 'autofix_scheduled', 'autofix_started',
+ 'check_added', 'check_result', 'check_started', 'check_wait_more',
+ 'checkpoint', 'checkpoint_failed', 'checkpoint_pruned',
+ 'claimed', 'class_changed', 'contract_updated', 'created', 'edited', 'evidence', 'failure',
+ 'flag_resolved', 'flagged', 'forked', 'handoff_ended', 'held', 'lease_expired',
+ 'lessons_held_out', 'lessons_shown', 'note', 'released', 'restored', 'review', 'risk_resolved',
+ 'self_checked', 'skill_drafted_from', 'skipped', 'state', 'tier_stepped_down',
+ 'verdict_overturned', 'verifier_done', 'verifier_skipped', 'verifier_started', 'verifier_turn', 'watch',
+ 'workflow_change_applied', 'workflow_change_decided', 'workflow_change_proposed',
+];
+
+test('guard: no kind the server emits renders as "Kwant: <raw kind>"', () => {
+ const raw = [];
+ for (const kind of SERVER_KINDS) {
+ const e = ev(kind, {}, { to_state: 'ready' });
+ if (m.isQuietEvent(e)) continue;
+ const text = m.eventText(e);
+ const humanized = kind.replace(/_/g, ' ');
+ if (!text || new RegExp(`^Kwant: ${humanized}$`, 'i').test(text)) raw.push(`${kind} -> ${JSON.stringify(text)}`);
+ }
+ assert.deepEqual(raw, []);
+ // The fallback itself still works for a kind nobody knows yet.
+ assert.equal(m.eventText(ev('brand_new_kind')), 'Kwant: Brand new kind');
+});
+
+// --- 4. The Live now chip
+
+test('Live now chip: full width up to 320 px on a phone, 240 px from sm', () => {
+ const board = read('src/components/MissionBoardView.tsx');
+ assert.match(board, /flex items-center gap-2 w-full max-w-\[320px\] sm:w-\[240px\] min-h-\[44px\]/);
+ assert.doesNotMatch(board, /w-\[220px\] sm:w-\[240px\]/);
+});