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.

Dev mode 0.7: landed, review, release-notes and production-floor cards (Iris) (#314)

Oleksandr Ivanchenkoed544761acd1
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 87151a52..ac59c7b4 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1508,6 +1508,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ decision }),
});
+ // Production floor (Dev mode): Allow without a fresh backup is refused and the card stays waiting.
+ if (res.status === 409) {
+ const body = await res.clone().json().catch(() => null);
+ if (body && typeof body === 'object' && (body as { status?: unknown }).status === 'needs_backup') {
+ haptic('warning');
+ pushToast('Back up first', 'This step needs a backup from the last 10 minutes. Take one on the card, then Allow.');
+ return;
+ }
+ }
// 409/404: it lapsed meanwhile (turn ended, expired, answered elsewhere).
if (res.ok || res.status === 409 || res.status === 404) {
const card = pendingApprovals.find((a) => a.id === ticketId);
diff --git a/frontend/src/components/ModernApprovalCard.tsx b/frontend/src/components/ModernApprovalCard.tsx
index 3a0e7a8d..29be6efa 100644
--- a/frontend/src/components/ModernApprovalCard.tsx
+++ b/frontend/src/components/ModernApprovalCard.tsx
@@ -6,6 +6,8 @@ import { tierReason } from '../flightSchool';
import { toolAction } from '../toolLabel';
import { localClock } from '../clock';
import { isPhoneLayout } from '../layout';
+import { parseProdFloor, type BackupResult } from '../dev/types';
+import { ProdFloorCard } from './dev/ProdFloorCard';
export interface PendingApproval {
id: string;
@@ -27,6 +29,8 @@ interface ModernApprovalCardProps {
disabled?: boolean;
/** Forces the phone or desktop look (tests); by default it follows the window when the card appears. */
phone?: boolean;
+ /** Production floor (Dev mode): takes a backup; defaults to the space's backup route. */
+ onBackup?: (spaceId: string) => Promise<BackupResult>;
}
/** Server/tool/arguments of an MCP approval, or null for other tools. */
@@ -185,7 +189,30 @@ export const ModernApprovalCard: React.FC<ModernApprovalCardProps> = ({
onResolve,
disabled = false,
phone,
+ onBackup,
}) => {
+ // Dev mode's production floor has its own card: blast radius, backup row, and never "always allow".
+ const floor = parseProdFloor(approval.details);
+ if (floor) {
+ const shellCmd = localShellView(approval) ?? builtinView(approval);
+ const kwant = approval.details?.kwant_name;
+ return (
+ <ProdFloorCard
+ id={approval.id}
+ floor={floor}
+ bot={typeof kwant === 'string' && kwant ? kwant : null}
+ command={shellCmd?.command ?? ''}
+ cwd={shellCmd?.cwd ?? null}
+ disabled={disabled}
+ onBackup={onBackup}
+ onResolve={(id, decision) => {
+ if (disabled) return;
+ playSfx('click');
+ onResolve(id, decision);
+ }}
+ />
+ );
+ }
const handleDecision = (decision: 'allow_once' | 'always_allow' | 'deny') => {
if (disabled) return;
playSfx('click');
diff --git a/frontend/src/components/dev/LandedCard.tsx b/frontend/src/components/dev/LandedCard.tsx
new file mode 100644
index 00000000..955fe7ae
--- /dev/null
+++ b/frontend/src/components/dev/LandedCard.tsx
@@ -0,0 +1,208 @@
+import React from 'react';
+import { AlertTriangle, Check, ChevronRight, FileText, FlaskConical, GitMerge, Minus, ShieldCheck, X } from 'lucide-react';
+import { Sticker } from '../Sticker';
+import type { LandedCard as Landed, LandedListProps, ReviewCard } from '../../dev/types';
+import { byDay, clock, openFindings, riskReasons, showVerified } from '../../dev/logic';
+import { OutLink, RiskChip, Who, personText } from './parts';
+
+const isTest = (path: string) => /(^|\/)(tests?|__tests__|e2e)\/|\.(test|spec)\.[a-z]+$|_test\.[a-z]+$/.test(path);
+
+const TESTS_ICON = { passed: Check, failed: X, none: Minus, unknown: Minus } as const;
+const TESTS_TONE = { passed: 'text-ok', failed: 'text-bad', none: 'text-zinc-400', unknown: 'text-zinc-400' } as const;
+
+/** One merge in plain words (design §4). */
+export const LandedCard: React.FC<{ card: Landed; reviews?: ReviewCard[]; onOpenReview?: (pr: number) => void }> = ({ card, reviews = [], onOpenReview }) => {
+ const verified = showVerified(card, reviews);
+ const writer = personText(card.written_by);
+ const merged = clock(card.merged_at);
+ const files = card.under_hood.files;
+ const add = files.reduce((n, f) => n + f.add, 0);
+ const del = files.reduce((n, f) => n + f.del, 0);
+ const openFollowUps = card.follow_ups;
+ // S1: a finding still open in this PR's review is something to do, even when CI and follow-ups are clear.
+ const findingsOpen = openFindings(reviews.find((r) => r.pr === card.pr));
+ const nothingToDo = openFollowUps.length === 0 && card.tests.state === 'passed' && findingsOpen === 0;
+ const TestsIcon = TESTS_ICON[card.tests.state];
+ const testsText =
+ card.tests.summary ?? (card.tests.state === 'passed' ? 'CI green' : card.tests.state === 'failed' ? 'CI failed' : card.tests.state === 'none' ? 'No CI checks' : 'CI not known');
+ const diff = card.links.commit ?? (card.links.pr ? `${card.links.pr}/files` : null);
+ const headingId = `landed-${card.id || card.pr}-h`;
+
+ return (
+ <article data-dev-card="landed" data-pr={card.pr} data-verified={verified || undefined} aria-labelledby={headingId} className="kw-card relative min-w-0 p-4">
+ <div className="flex flex-wrap items-center gap-1.5">
+ {card.area && <span className="kw-chip">{card.area}</span>}
+ {card.risk && <RiskChip level={card.risk.level} />}
+ {card.meta && <span className="text-meta text-zinc-400">{card.meta}</span>}
+ {verified && (
+ <Sticker tone="holo" icon={<ShieldCheck aria-hidden="true" />} className="ml-auto" ariaLabel="Verified: CI is green and someone other than the author reviewed it" title="CI green and reviewed by someone other than the author">
+ Verified
+ </Sticker>
+ )}
+ </div>
+
+ <h3 id={headingId} className="mt-2 text-title font-semibold text-zinc-50 [overflow-wrap:anywhere]">
+ {card.headline}
+ </h3>
+ <div className="mt-1 flex flex-wrap items-center gap-x-1 gap-y-0.5 text-meta text-zinc-400">
+ <GitMerge size={13} className="shrink-0 text-ok" aria-hidden="true" />
+ <span>
+ Merged{merged ? ` ${merged}` : ''}
+ {card.merged_by && (
+ <>
+ {' '}by <span className="font-medium text-zinc-100">{card.merged_by}</span>
+ </>
+ )}
+ </span>
+ {writer && (
+ <>
+ <span aria-hidden="true">·</span>
+ <span>written by</span>
+ <Who name={writer.name} />
+ {writer.sub && <span>({writer.sub})</span>}
+ </>
+ )}
+ <span aria-hidden="true">·</span>
+ {card.links.pr ? (
+ <a href={card.links.pr} target="_blank" rel="noreferrer noopener" className="kw-focus rounded text-sky-300 hover:text-sky-200">
+ PR #{card.pr}
+ </a>
+ ) : (
+ <span>PR #{card.pr}</span>
+ )}
+ </div>
+
+ {card.status === 'pending' && <p className="mt-3 text-meta text-zinc-400">Writing this change in plain words…</p>}
+ {card.error && (
+ <p className="mt-3 text-meta text-zinc-400">
+ No plain-words text for this change: <span className="text-zinc-300">{card.error}</span>
+ </p>
+ )}
+
+ {card.for_you && (
+ <div className="mt-3">
+ <p className="text-2xs font-semibold uppercase tracking-wider text-zinc-400">What changes for you</p>
+ <p className="mt-1 text-body text-zinc-100 [overflow-wrap:anywhere]">{card.for_you}</p>
+ </div>
+ )}
+
+ {(files.length > 0 || card.under_hood.summary) && (
+ <details className="group mt-3 border-t border-hairline pt-3">
+ <summary className="kw-focus flex min-h-[44px] cursor-pointer list-none items-center gap-1.5 rounded text-meta text-zinc-400 hover:text-zinc-200 sm:min-h-0 [&::-webkit-details-marker]:hidden">
+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 transition-transform duration-[160ms] group-open:rotate-90 motion-reduce:transition-none" />
+ <span>
+ Under the hood
+ {files.length > 0 && ` · ${files.length} ${files.length === 1 ? 'file' : 'files'}, +${add} −${del}`}
+ </span>
+ </summary>
+ {card.under_hood.summary && <p className="mt-2 text-meta text-zinc-300 [overflow-wrap:anywhere]">{card.under_hood.summary}</p>}
+ {files.length > 0 && (
+ <ul role="list" className="mt-2 space-y-1">
+ {files.map((f) => {
+ const Icon = isTest(f.path) ? FlaskConical : FileText;
+ return (
+ <li key={f.path} className="flex min-w-0 items-start gap-1.5 font-mono text-[12px] leading-5">
+ <Icon size={12} className="mt-1 shrink-0 text-zinc-500" aria-hidden="true" />
+ <span className="min-w-0 text-zinc-200 [overflow-wrap:anywhere]">{f.path}</span>
+ <span className="shrink-0 text-ok" aria-label={`${f.add} lines added`}>+{f.add}</span>
+ <span className="shrink-0 text-bad" aria-label={`${f.del} lines removed`}>−{f.del}</span>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ {card.risk && (
+ <p className="mt-2 text-2xs text-zinc-400">
+ Risk reasons: {riskReasons(card.risk).join(' · ')}
+ </p>
+ )}
+ {card.cut && <p className="mt-1 text-2xs text-zinc-400">{card.cut}</p>}
+ </details>
+ )}
+
+ {openFollowUps.length > 0 && (
+ <div role="note" className="mt-3 flex items-start gap-2 rounded-xl border border-amber-300/35 bg-amber-300/10 px-3 py-2 text-meta text-zinc-100">
+ <AlertTriangle size={14} className="mt-0.5 shrink-0 text-warn" aria-hidden="true" />
+ <p className="min-w-0 [overflow-wrap:anywhere]">
+ <span className="font-semibold text-warn">
+ {openFollowUps.length} follow-up{openFollowUps.length === 1 ? '' : 's'} open:
+ </span>{' '}
+ {openFollowUps.map((f, i) => (
+ <span key={i}>
+ {i > 0 && ' · '}
+ {f.text}
+ {f.ref && ` (${f.ref})`}
+ </span>
+ ))}
+ </p>
+ </div>
+ )}
+
+ <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-meta">
+ <span className={`inline-flex items-center gap-1 ${TESTS_TONE[card.tests.state]}`}>
+ <TestsIcon size={13} aria-hidden="true" />
+ {card.links.ci ? (
+ <a href={card.links.ci} target="_blank" rel="noreferrer noopener" className="kw-focus rounded hover:underline">
+ {testsText}
+ </a>
+ ) : (
+ testsText
+ )}
+ </span>
+ <span className="text-zinc-400">{card.reviewed_by ? `Reviewed by ${card.reviewed_by}` : 'No bot review'}</span>
+ {nothingToDo && <span className="text-zinc-400">Nothing to do for you.</span>}
+ {findingsOpen > 0 && (
+ <span data-findings-open={findingsOpen} className="inline-flex flex-wrap items-center gap-x-1">
+ <span className="font-semibold text-amber-300">
+ {findingsOpen} {findingsOpen === 1 ? 'finding' : 'findings'} open
+ </span>
+ <span className="text-zinc-400">in the review</span>
+ {onOpenReview && (
+ <>
+ <span aria-hidden="true" className="text-zinc-400">
+ ·
+ </span>
+ <button
+ type="button"
+ onClick={() => onOpenReview(card.pr)}
+ className="kw-focus inline-flex min-h-[44px] items-center rounded text-sky-300 hover:text-sky-200 hover:underline sm:min-h-0"
+ >
+ Open review
+ </button>
+ </>
+ )}
+ </span>
+ )}
+ <span className="flex items-center gap-3 sm:ml-auto">
+ {diff && (
+ <a href={diff} target="_blank" rel="noreferrer noopener" className="kw-focus inline-flex min-h-[44px] items-center rounded text-sky-300 hover:text-sky-200 sm:min-h-0">
+ Diff
+ </a>
+ )}
+ {card.links.pr && (
+ <OutLink href={card.links.pr} className="min-h-[44px] sm:min-h-0">
+ Open on GitHub
+ </OutLink>
+ )}
+ </span>
+ </div>
+ </article>
+ );
+};
+
+/** What landed: the cards under "Today", "Yesterday" and date separators. */
+export const LandedList: React.FC<LandedListProps> = ({ cards, reviews, now = Date.now(), onOpenReview }) => (
+ <div data-dev-landed-list className="space-y-3">
+ {byDay(cards, now).map((day) => (
+ <section key={day.label} aria-label={day.label} className="space-y-3">
+ <h3 className="flex items-center gap-3 pt-2 text-2xs font-semibold uppercase tracking-wider text-zinc-400">
+ <span>{day.label}</span>
+ <span aria-hidden="true" className="h-px flex-1 bg-hairline" />
+ </h3>
+ {day.cards.map((c) => (
+ <LandedCard key={c.id || c.pr} card={c} reviews={reviews} onOpenReview={onOpenReview} />
+ ))}
+ </section>
+ ))}
+ </div>
+);
diff --git a/frontend/src/components/dev/ProdFloorCard.tsx b/frontend/src/components/dev/ProdFloorCard.tsx
new file mode 100644
index 00000000..b7b8aa36
--- /dev/null
+++ b/frontend/src/components/dev/ProdFloorCard.tsx
@@ -0,0 +1,208 @@
+import React, { useEffect, useReducer, useRef, useState } from 'react';
+import { Database, Loader2, ShieldAlert, Target, X, Check } from 'lucide-react';
+import type { BackupResult, ProdFloor } from '../../dev/types';
+import { parseBackupResult } from '../../dev/types';
+import { allowReady, floorHeader, floorReducer, floorSubline, floorView, initialFloorUi, type RowTone } from '../../dev/logic';
+
+export type FloorDecision = 'allow_once' | 'deny';
+
+export interface ProdFloorCardProps {
+ id: string;
+ floor: ProdFloor;
+ bot: string | null;
+ command: string;
+ cwd: string | null;
+ onResolve: (id: string, decision: FloorDecision) => void;
+ disabled?: boolean;
+ /** Takes the backup; defaults to `POST /api/spaces/:space_id/dev/backup`. */
+ onBackup?: (spaceId: string) => Promise<BackupResult>;
+ /** A fixed clock for screenshots and tests; the card ticks on its own otherwise. */
+ now?: number;
+}
+
+/** Lin's route: 200 with {ok, error} for a run, 409 {error} when there is no command or one is running. */
+export async function postBackup(spaceId: string): Promise<BackupResult> {
+ const res = await fetch(`/api/spaces/${encodeURIComponent(spaceId)}/dev/backup`, { method: 'POST' });
+ const body = await res.json().catch(() => null);
+ if (!res.ok) {
+ const err = body && typeof body === 'object' && typeof (body as { error?: unknown }).error === 'string' ? (body as { error: string }).error : `HTTP ${res.status}`;
+ throw new Error(err);
+ }
+ return parseBackupResult(body);
+}
+
+const ROW: Record<RowTone, string> = {
+ ok: 'border-teal-300/35 bg-teal-300/10 text-zinc-100',
+ warn: 'border-amber-300/35 bg-amber-300/10 text-zinc-100',
+ bad: 'border-rose-300/40 bg-rose-300/10 text-zinc-100',
+ neutral: 'border-hairline bg-zinc-950/40 text-zinc-400',
+ info: 'border-hairline bg-zinc-950/40 text-sky-200',
+};
+const LEAD: Record<RowTone, string> = { ok: 'text-ok', warn: 'text-warn', bad: 'text-bad', neutral: 'text-zinc-300', info: 'text-sky-200' };
+
+const BTN = 'flex items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors min-h-[44px] sm:min-h-0 max-sm:w-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400 disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:opacity-50 aria-disabled:cursor-not-allowed';
+const AMBER = `${BTN} bg-amber-600 text-white shadow-sm hover:bg-amber-500`;
+const PLAIN = `${BTN} bg-zinc-800 text-zinc-300 hover:bg-zinc-700`;
+
+/** "kwant.jumpin.games · production": the place, then a warn chip for the word "production". */
+const BlastValue: React.FC<{ label: string; value: string }> = ({ label, value }) => {
+ const m = label === 'Where' ? value.match(/^(.*?)\s*·\s*production$/i) : null;
+ if (!m) return <>{value}</>;
+ return (
+ <>
+ {m[1]} <span className="kw-chip kw-chip-warn ml-1 align-middle">production</span>
+ </>
+ );
+};
+
+/** The production-floor variant of the approval card (design §6). Never offers "always allow". */
+export const ProdFloorCard: React.FC<ProdFloorCardProps> = ({ id, floor, bot, command, cwd, onResolve, disabled = false, onBackup = postBackup, now: fixedNow }) => {
+ const [ui, send] = useReducer(floorReducer, floor, initialFloorUi);
+ const mountedAt = useRef(fixedNow ?? Date.now()).current;
+ const [tick, setTick] = useState(() => Date.now());
+ useEffect(() => {
+ if (fixedNow !== undefined) return;
+ const t = window.setInterval(() => setTick(Date.now()), 1000);
+ return () => window.clearInterval(t);
+ }, [fixedNow]);
+ const now = fixedNow ?? tick;
+
+ const view = floorView(floor, ui, now, mountedAt);
+ const isDeploy = floor.kind === 'deploy' || floor.kind === 'deploy_migration';
+ const allowLabel = isDeploy ? 'Allow this deploy' : 'Allow';
+ const off = disabled || view.busy;
+ const headingId = `floor-${id}-h`;
+ const mainRef = useRef<HTMLButtonElement>(null);
+
+ // `fromSecondary`: the secondary "Back up first" unmounts once the backup starts, so focus goes back to the
+ // main button (which turns into Allow in place) when the backup is done.
+ const takeBackup = async (fromSecondary = false) => {
+ if (off || !floor.space_id) return;
+ send({ type: 'backup_start' });
+ try {
+ const result = await onBackup(floor.space_id);
+ send({ type: 'backup_done', result, now: Date.now() });
+ setTick(Date.now());
+ if (fromSecondary) window.setTimeout(() => mainRef.current?.focus(), 0);
+ } catch (e) {
+ send({ type: 'backup_error', error: e instanceof Error ? e.message : 'no reason given' });
+ }
+ };
+
+ const allow = () => {
+ // The Allow that replaced Back up first ignores presses for its first 500 ms.
+ if (off || !allowReady(ui, Date.now())) return;
+ onResolve(id, 'allow_once');
+ };
+
+ const main =
+ view.main === 'allow'
+ ? { label: allowLabel, icon: <Check size={14} aria-hidden="true" />, onClick: allow }
+ : view.main === 'backup'
+ ? { label: 'Back up first', icon: <Database size={14} aria-hidden="true" />, onClick: () => void takeBackup() }
+ : view.main === 'retry'
+ ? { label: 'Try the backup again', icon: <Database size={14} aria-hidden="true" />, onClick: () => void takeBackup() }
+ : null;
+
+ return (
+ <div
+ data-approval-card={id}
+ data-prod-floor={floor.kind}
+ data-floor-case={view.case}
+ role="group"
+ aria-labelledby={headingId}
+ className="my-3 max-w-2xl rounded-xl border border-amber-500/30 bg-amber-950/20 p-3 text-zinc-100 shadow-lg backdrop-blur-sm sm:p-4"
+ >
+ <div className="mb-1 flex items-start gap-2 text-xs font-semibold tracking-wide text-amber-400">
+ <ShieldAlert size={16} aria-hidden="true" className="mt-px shrink-0" />
+ <h3 id={headingId} className="min-w-0 [overflow-wrap:anywhere]">
+ {floorHeader(floor, bot ?? 'A bot')}
+ </h3>
+ </div>
+ <p className="mb-3 text-[11px] text-zinc-400 sm:pl-6">{floorSubline(floor)}</p>
+
+ <div className="mb-3 space-y-2 rounded-lg border border-zinc-800 bg-zinc-900/90 p-3 text-xs">
+ {floor.why && <p className="text-zinc-300 [overflow-wrap:anywhere]">This is {floor.why}.</p>}
+ <pre className="max-h-64 overflow-y-auto whitespace-pre-wrap break-all rounded-md border border-zinc-800 bg-zinc-950/70 p-2 font-mono text-[12px] text-zinc-100">
+ {command || '(empty command)'}
+ </pre>
+ {cwd && (
+ <p className="break-all text-[11px] text-zinc-400">
+ <span className="text-zinc-500">In folder:</span> <span className="font-mono text-zinc-300">{cwd}</span>
+ </p>
+ )}
+ </div>
+
+ {floor.blast.length > 0 && (
+ <section aria-label="Blast radius" className="mb-3 overflow-hidden rounded-xl border border-white/[0.14]">
+ <h4 className="flex items-center gap-1.5 border-b border-white/[0.14] bg-zinc-950/30 px-3 py-1.5 text-2xs font-semibold uppercase tracking-wider text-zinc-400">
+ <Target size={12} aria-hidden="true" />
+ Blast radius
+ </h4>
+ <dl className="divide-y divide-white/[0.08] text-xs">
+ {floor.blast.map(([label, value]) => (
+ <div key={label} className="grid grid-cols-1 gap-0.5 px-3 py-2 sm:grid-cols-[120px_1fr] sm:gap-3">
+ <dt className="text-zinc-400">{label}</dt>
+ <dd className="min-w-0 text-zinc-100 [overflow-wrap:anywhere]">
+ <BlastValue label={label} value={value} />
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+ )}
+
+ <div data-backup-row={view.case} aria-live="polite" className={`mb-3 flex items-start gap-2 rounded-lg border px-3 py-2 text-xs ${ROW[view.tone]}`}>
+ {view.case === 'taking' ? (
+ <Loader2 size={14} aria-hidden="true" className="mt-px shrink-0 animate-spin motion-reduce:animate-none" />
+ ) : view.tone === 'bad' ? (
+ <X size={14} aria-hidden="true" className={`mt-px shrink-0 ${LEAD.bad}`} />
+ ) : (
+ <Database size={14} aria-hidden="true" className={`mt-px shrink-0 ${LEAD[view.tone]}`} />
+ )}
+ <p className="min-w-0 [overflow-wrap:anywhere]">
+ {view.lead && <span className={`font-semibold ${LEAD[view.tone]}`}>{view.lead}</span>}
+ {view.text}
+ {view.file && (
+ <>
+ {' · '}
+ <code className="font-mono text-[11px] text-zinc-300">{view.file}</code>
+ </>
+ )}
+ </p>
+ </div>
+
+ <div data-approval-actions className="flex flex-wrap items-center gap-2 max-sm:flex-col max-sm:items-stretch">
+ <p className="text-[11px] text-zinc-400 sm:mr-auto">{view.note}</p>
+ {main && (
+ // One element for Back up first, Allow and Try again, so the button changes in place and keeps focus.
+ // aria-disabled, never disabled: disabling the focused button sends focus to <body> (B2). The handlers
+ // ignore presses while `off`.
+ <button
+ ref={mainRef}
+ key="main"
+ type="button"
+ data-floor-main={view.main}
+ aria-disabled={off || undefined}
+ aria-busy={view.busy || undefined}
+ onClick={() => !off && main.onClick()}
+ className={AMBER}
+ >
+ {main.icon}
+ {main.label}
+ </button>
+ )}
+ {view.secondaryBackup && (
+ <button type="button" disabled={off} onClick={() => void takeBackup(true)} className={PLAIN}>
+ <Database size={14} aria-hidden="true" />
+ Back up first
+ </button>
+ )}
+ <button type="button" disabled={off} onClick={() => !off && onResolve(id, 'deny')} className={PLAIN}>
+ <X size={14} aria-hidden="true" />
+ Deny
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/dev/ReleaseNotesSheet.tsx b/frontend/src/components/dev/ReleaseNotesSheet.tsx
new file mode 100644
index 00000000..e3bd07f0
--- /dev/null
+++ b/frontend/src/components/dev/ReleaseNotesSheet.tsx
@@ -0,0 +1,128 @@
+import React, { useRef, useState } from 'react';
+import { Check, Copy, Loader2, Sparkles, Trash2, X } from 'lucide-react';
+import { MarkdownRenderer } from '../MarkdownRenderer';
+import { useEscapeLayer } from '../../escape';
+import type { ReleaseNotesSheetProps } from '../../dev/types';
+
+/**
+ * The release-notes draft (design §4 "Release notes draft"): a bottom sheet on a phone, a centred panel
+ * on desktop. The server answers 202 pending and the ready card comes over SSE, so this shows a waiting
+ * state until `card.status` is ready. Save to Notion appears only when the caller passes it (connected).
+ */
+export const ReleaseNotesSheet: React.FC<ReleaseNotesSheetProps> = ({ card, onSaveToNotion, onDiscard, onClose }) => {
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [copied, setCopied] = useState(false);
+ const [saving, setSaving] = useState<'idle' | 'saving' | 'saved' | 'failed'>('idle');
+ const [saveError, setSaveError] = useState<string | null>(null);
+ useEscapeLayer(rootRef, true, onClose, { modal: true });
+
+ const ready = card.status === 'ready' && !!card.markdown;
+ const labelId = `rn-${card.id}-h`;
+
+ const copy = async () => {
+ if (!card.markdown) return;
+ try {
+ await navigator.clipboard.writeText(card.markdown);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 2000);
+ } catch {
+ // Clipboard blocked (plain http): the text stays selectable.
+ }
+ };
+
+ const save = async () => {
+ if (!onSaveToNotion || !card.markdown || saving === 'saving') return;
+ setSaving('saving');
+ setSaveError(null);
+ try {
+ await onSaveToNotion(card.markdown);
+ setSaving('saved');
+ } catch (e) {
+ setSaving('failed');
+ setSaveError(e instanceof Error ? e.message : 'saving didn’t go through');
+ }
+ };
+
+ return (
+ <div
+ data-dev-release-notes
+ className="kw-dialog kw-dialog-bottom fixed inset-0 z-50 flex items-end justify-center bg-black/70 backdrop-blur-sm sm:items-center sm:p-4"
+ onMouseDown={(e) => e.target === e.currentTarget && onClose()}
+ >
+ <div
+ ref={rootRef}
+ tabIndex={-1}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={labelId}
+ className="kw-dialog-panel flex max-h-[92vh] w-full flex-col rounded-t-2xl border border-zinc-800 bg-zinc-900 text-zinc-100 shadow-2xl outline-none sm:max-w-2xl sm:rounded-2xl"
+ >
+ <div className="flex items-start justify-between gap-3 border-b border-hairline p-4 sm:px-6">
+ <div className="min-w-0">
+ <h2 id={labelId} className="flex items-center gap-1.5 text-sm font-semibold">
+ <Sparkles size={15} aria-hidden="true" className="text-sky-300" />
+ Release notes draft
+ </h2>
+ {card.since_tag && (
+ <p className="mt-0.5 text-xs text-zinc-400">
+ Since <code className="font-mono text-zinc-300">{card.since_tag}</code>
+ </p>
+ )}
+ </div>
+ <button type="button" onClick={onClose} aria-label="Close" className="kw-focus flex h-11 w-11 items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100 sm:h-8 sm:w-8">
+ <X size={18} aria-hidden="true" />
+ </button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto p-4 sm:px-6" aria-live="polite" aria-busy={!ready || undefined}>
+ {card.status === 'pending' && (
+ <p className="flex items-center gap-2 text-meta text-zinc-400">
+ <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />
+ Writing the notes from what landed…
+ </p>
+ )}
+ {card.error && (
+ <p role="alert" className="text-meta text-bad">
+ Couldn’t write the notes: {card.error}
+ </p>
+ )}
+ {ready && (
+ <>
+ {card.whats_new && (
+ <div className="mb-3 rounded-xl border border-hairline bg-surface-main p-3">
+ <p className="text-2xs font-semibold uppercase tracking-wider text-zinc-400">What’s new</p>
+ <p className="mt-1 text-body text-zinc-100 [overflow-wrap:anywhere]">{card.whats_new}</p>
+ </div>
+ )}
+ <MarkdownRenderer content={card.markdown!} />
+ </>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2 border-t border-hairline p-4 sm:px-6">
+ <button type="button" onClick={copy} disabled={!ready} className="kw-btn-primary min-h-[44px] sm:min-h-0 max-sm:flex-1">
+ {copied ? <Check size={14} aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}
+ {copied ? 'Copied' : 'Copy'}
+ </button>
+ {onSaveToNotion && (
+ <button type="button" onClick={save} disabled={!ready || saving === 'saving' || saving === 'saved'} aria-busy={saving === 'saving' || undefined} className="kw-btn-ghost min-h-[44px] sm:min-h-0 max-sm:flex-1">
+ {saving === 'saved' ? 'Saved to Notion' : saving === 'saving' ? 'Saving…' : 'Save to Notion'}
+ </button>
+ )}
+ <button type="button" onClick={onDiscard} className="kw-btn-ghost min-h-[44px] text-zinc-400 sm:ml-auto sm:min-h-0 max-sm:flex-1">
+ <Trash2 size={14} aria-hidden="true" />
+ Discard
+ </button>
+ <span className="sr-only" aria-live="polite">
+ {copied ? 'Copied to the clipboard' : ''}
+ </span>
+ {saveError && (
+ <p role="alert" className="w-full text-meta text-bad">
+ Couldn’t save to Notion: {saveError}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/dev/ReviewCard.tsx b/frontend/src/components/dev/ReviewCard.tsx
new file mode 100644
index 00000000..22f4cbf7
--- /dev/null
+++ b/frontend/src/components/dev/ReviewCard.tsx
@@ -0,0 +1,462 @@
+import React, { useEffect, useReducer, useState } from 'react';
+import {
+ AlertTriangle,
+ Check,
+ FlaskConical,
+ GitPullRequest,
+ KeyRound,
+ Lock,
+ Package,
+ ShieldAlert,
+ ShieldCheck,
+ Target,
+ Wrench,
+ X,
+ Bug,
+ Code2,
+} from 'lucide-react';
+import type { DevFinding, FindingAction, ReviewCard as Review, ReviewCardProps, Severity, TamperFlag } from '../../dev/types';
+import {
+ DISMISS_REASONS,
+ clock,
+ closedDraft,
+ dismissReducer,
+ dismissedLine,
+ findingsSummary,
+ riskReasons,
+ undoLeft,
+} from '../../dev/logic';
+import { OutLink, SectionHead, Who, modelLabel, personText } from './parts';
+
+// Severity styling copied from results/Findings.tsx (design §5.6: "reuse as is").
+const DOT: Record<Severity, string> = { critical: 'bg-rose-500', high: 'bg-orange-500', medium: 'bg-amber-500', low: 'bg-sky-500' };
+const STRIPE: Record<Severity, string> = { critical: 'border-l-rose-500', high: 'border-l-orange-500', medium: 'border-l-amber-500', low: 'border-l-sky-500' };
+const SEV_WORD: Record<Severity, string> = { critical: 'Critical', high: 'High', medium: 'Medium', low: 'Low' };
+// S4 (WCAG 1.4.1): the severity is a word too, not only the dot's colour.
+const SEV_TONE: Record<Severity, string> = { critical: 'text-rose-300', high: 'text-rose-300', medium: 'text-amber-300', low: 'text-teal-300' };
+
+const RISK_BOX = {
+ high: { box: 'border-rose-300/35 bg-rose-300/[0.12]', pill: 'bg-rose-300 text-[#120e26]' },
+ medium: { box: 'border-amber-300/35 bg-amber-300/[0.12]', pill: 'bg-amber-300 text-[#120e26]' },
+ low: { box: 'border-teal-300/35 bg-teal-300/[0.12]', pill: 'bg-teal-300 text-[#120e26]' },
+} as const;
+
+const TAMPER_WORD: Record<TamperFlag['kind'], string> = {
+ deleted_assert: 'An assert was deleted',
+ skip: 'A test is skipped',
+ loosened: 'An expectation was loosened',
+ snapshot: 'A snapshot was rewritten',
+ coverage_drop: 'Coverage dropped',
+};
+
+const ref = (f: { file: string | null; line: number | null }) => (f.file ? `${f.file}${f.line !== null ? `:${f.line}` : ''}` : null);
+
+// ---------------------------------------------------------------------------------------------------
+
+const Tamper: React.FC<{ flag: TamperFlag }> = ({ flag }) => (
+ <div data-tamper={flag.kind} className="rounded-xl border border-amber-300/35 bg-amber-300/10 p-3">
+ <p className="flex items-center gap-1.5 text-[13px] font-semibold text-warn">
+ <AlertTriangle size={14} aria-hidden="true" />
+ A test was made easier to pass
+ </p>
+ <p className="mt-1 text-meta text-zinc-200 [overflow-wrap:anywhere]">
+ <span className="sr-only">{TAMPER_WORD[flag.kind]}. </span>
+ {flag.why}
+ </p>
+ {flag.excerpt && (
+ <figure className="mt-2 overflow-hidden rounded-lg border border-hairline bg-zinc-950/70">
+ <figcaption className="border-b border-hairline px-2 py-1 font-mono text-[11px] text-zinc-400 [overflow-wrap:anywhere]">{ref(flag)}</figcaption>
+ <pre className="overflow-x-auto py-1 font-mono text-[12px] leading-5" tabIndex={0} aria-label={`Diff excerpt from ${flag.file}`}>
+ {flag.excerpt.split('\n').map((l, i) => (
+ <div key={i} className={`px-2 ${l.startsWith('-') ? 'bg-rose-500/[0.12] text-rose-200' : l.startsWith('+') ? 'bg-teal-500/10 text-teal-200' : 'text-zinc-300'}`}>
+ <span className="sr-only">{l.startsWith('-') ? 'Removed: ' : l.startsWith('+') ? 'Added: ' : ''}</span>
+ {l}
+ </div>
+ ))}
+ </pre>
+ </figure>
+ )}
+ </div>
+);
+
+const SecTile: React.FC<{ icon: React.ReactNode; name: string; tool: string; state: 'pass' | 'hit' | 'not_run' | 'later'; text: string }> = ({ icon, name, tool, state, text }) => {
+ const look =
+ state === 'later'
+ ? 'border-dashed border-hairline-strong opacity-60'
+ : state === 'hit'
+ ? 'border-rose-300/50 bg-rose-300/10'
+ : 'border-hairline bg-surface-main';
+ const tone = state === 'pass' ? 'text-ok' : state === 'hit' ? 'text-bad' : 'text-zinc-400';
+ return (
+ <li data-sec={tool} data-state={state} className={`min-w-0 rounded-xl border p-3 ${look}`}>
+ <p className="flex items-center gap-1.5 text-[13px] font-semibold text-zinc-100">
+ <span aria-hidden="true" className="text-zinc-400">
+ {icon}
+ </span>
+ <span className="min-w-0 [overflow-wrap:anywhere]">{name}</span>
+ </p>
+ <p className="mt-0.5 text-2xs text-zinc-500">{tool}</p>
+ <p className={`mt-1 text-meta ${tone}`}>{text}</p>
+ </li>
+ );
+};
+
+const scanText = (s: { state: 'pass' | 'hit' | 'not_run'; count: number }, one: string, many: string, clean: string) =>
+ s.state === 'not_run' ? 'Not run' : s.state === 'pass' ? clean : `${s.count} ${s.count === 1 ? one : many} · see finding`;
+
+// ---------------------------------------------------------------------------------------------------
+
+interface FindingRowProps {
+ f: DevFinding;
+ author: string | null;
+ now: number;
+ busy: boolean;
+ act: (f: DevFinding, a: FindingAction) => Promise<void>;
+}
+
+const FindingRow: React.FC<FindingRowProps> = ({ f, author, now, busy, act }) => {
+ const [draft, send] = useReducer(dismissReducer, closedDraft);
+ const formId = `dismiss-${f.id}`;
+ const where = ref(f);
+
+ if (f.state === 'dismissed') {
+ return (
+ <li data-finding={f.id} data-state="dismissed" className={`rounded-xl border border-zinc-700/60 border-l-[3px] bg-zinc-900/40 px-3 py-2 text-xs ${STRIPE[f.severity]}`}>
+ <span className="text-zinc-400 line-through decoration-zinc-600">{f.title}</span>
+ <span className="ml-2 text-zinc-400">{dismissedLine(f)}</span>
+ </li>
+ );
+ }
+
+ const left = undoLeft(f, now);
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!draft.reason || draft.sending) return;
+ send({ type: 'submit' });
+ try {
+ await act(f, { action: 'dismiss', reason: draft.reason, ...(draft.note.trim() ? { note: draft.note.trim() } : {}) });
+ send({ type: 'done' });
+ } catch (err) {
+ send({ type: 'failed', error: err instanceof Error ? err.message : 'That didn’t go through. Try again.' });
+ }
+ };
+
+ return (
+ <li data-finding={f.id} data-state={f.state} className={`rounded-xl border border-zinc-700/60 border-l-[3px] bg-zinc-900/60 p-3 text-xs shadow-[var(--kws-shadow)] ${STRIPE[f.severity]}`}>
+ <div className="flex items-start gap-2">
+ <span className={`mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full ${DOT[f.severity]}`} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <div className="font-semibold leading-snug text-zinc-100 [overflow-wrap:anywhere]">
+ <span data-sev-word={f.severity} className={`mr-1.5 text-[10px] font-semibold uppercase tracking-wide ${SEV_TONE[f.severity]}`}>
+ {SEV_WORD[f.severity]}
+ <span className="sr-only">:</span>
+ </span>
+ {f.title}
+ </div>
+ {f.detail && <p className="mt-1 leading-relaxed text-zinc-400 [overflow-wrap:anywhere]">{f.detail}</p>}
+ {where && (
+ <div className="mt-1.5">
+ <code className="rounded bg-zinc-900 px-1.5 py-0.5 font-mono text-[11px] text-sky-300 [overflow-wrap:anywhere]">{where}</code>
+ </div>
+ )}
+ {f.fix && (
+ <p className="mt-1.5 leading-relaxed text-zinc-300 [overflow-wrap:anywhere]">
+ <span className="font-semibold text-zinc-200">Suggested fix:</span> {f.fix}
+ </p>
+ )}
+
+ <div className="mt-2 flex flex-wrap items-center gap-2" aria-live="polite">
+ {f.state === 'open' && !draft.open && (
+ <>
+ <button type="button" disabled={busy} onClick={() => void act(f, { action: 'fix' })} className="kw-btn-primary min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">
+ <Wrench size={13} aria-hidden="true" />
+ Fix it
+ </button>
+ <button type="button" disabled={busy} aria-expanded={false} aria-controls={formId} onClick={() => send({ type: 'open' })} className="kw-btn-ghost min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">
+ Dismiss
+ </button>
+ </>
+ )}
+ {f.state === 'open' && f.send_error && <span className="text-bad">Couldn’t send it: {f.send_error}</span>}
+ {f.state === 'sent' && (
+ <>
+ <span className="inline-flex items-center gap-1 text-ok">
+ <Check size={13} aria-hidden="true" />
+ Sent to {f.sent_to ?? author ?? 'the author'} as a task{clock(f.sent_at) ? ` · ${clock(f.sent_at)}` : ''}
+ </span>
+ {left > 0 && (
+ <button type="button" disabled={busy} onClick={() => void act(f, { action: 'undo_fix' })} className="kw-btn-ghost min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">
+ Undo <span className="text-zinc-400">({Math.ceil(left / 1000)} s)</span>
+ </button>
+ )}
+ </>
+ )}
+ </div>
+
+ {draft.open && (
+ <form id={formId} onSubmit={submit} aria-label={`Dismiss: ${f.title}`} className="mt-2 rounded-lg border border-hairline bg-surface-main p-2.5">
+ <fieldset disabled={draft.sending}>
+ <legend className="text-meta text-zinc-200">Why dismiss? Rigel learns from this.</legend>
+ <div role="radiogroup" aria-label="Reason" className="mt-2 flex flex-wrap gap-1.5">
+ {DISMISS_REASONS.map((r) => {
+ const on = draft.reason === r.id;
+ return (
+ <button
+ key={r.id}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ onClick={() => send({ type: 'reason', reason: r.id })}
+ className={`kw-focus min-h-[44px] rounded-full border px-3 text-xs sm:min-h-[28px] ${on ? 'border-sky-400 bg-sky-500/15 text-zinc-50' : 'border-hairline text-zinc-300 hover:border-hairline-strong'}`}
+ >
+ {r.label}
+ </button>
+ );
+ })}
+ </div>
+ <label className="mt-2 block text-2xs text-zinc-400">
+ Note (optional)
+ <textarea
+ value={draft.note}
+ onChange={(e) => send({ type: 'note', note: e.target.value })}
+ rows={2}
+ maxLength={500}
+ className="kw-focus mt-1 block w-full resize-y rounded-lg border border-hairline bg-surface-main px-2 py-1.5 text-xs text-zinc-100"
+ />
+ </label>
+ {draft.error && (
+ <p role="alert" className="mt-1 text-bad">
+ {draft.error}
+ </p>
+ )}
+ <div className="mt-2 flex flex-wrap gap-2">
+ <button type="submit" disabled={!draft.reason} aria-busy={draft.sending || undefined} className="kw-btn-primary min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">
+ {draft.sending ? 'Dismissing…' : 'Dismiss finding'}
+ </button>
+ <button type="button" onClick={() => send({ type: 'cancel' })} className="kw-btn-ghost min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">
+ Cancel
+ </button>
+ </div>
+ </fieldset>
+ </form>
+ )}
+ </div>
+ </div>
+ </li>
+ );
+};
+
+// ---------------------------------------------------------------------------------------------------
+
+/** One PR in review: risk, intent, tests, security and findings (design §5, parts 1–7). */
+export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding, sample = false, now: fixedNow }) => {
+ const [card, setCard] = useState<Review>(given);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [tick, setTick] = useState(() => Date.now());
+ useEffect(() => setCard(given), [given]);
+ const now = fixedNow ?? tick;
+
+ // Tick once a second only while an Undo is on screen.
+ const undoing = fixedNow === undefined && card.findings.some((f) => undoLeft(f, tick) > 0);
+ useEffect(() => {
+ if (!undoing) return;
+ const t = window.setInterval(() => setTick(Date.now()), 1000);
+ return () => window.clearInterval(t);
+ }, [undoing]);
+
+ const act = async (f: DevFinding, a: FindingAction) => {
+ if (busy) return;
+ setBusy(f.id);
+ try {
+ setCard(await onFinding(card.id, f.id, a));
+ setTick(Date.now());
+ } catch (err) {
+ if (a.action === 'dismiss') throw err;
+ const msg = err instanceof Error ? err.message : 'it didn’t go through';
+ setCard((c) => ({ ...c, findings: c.findings.map((x) => (x.id === f.id ? { ...x, send_error: msg } : x)) }));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const author = personText(card.author);
+ const authorModel = card.author ? modelLabel(card.author.engine, card.author.model) : null;
+ const reviewerModel = card.reviewer ? modelLabel(card.reviewer.engine, card.reviewer.model) : null;
+ const headingId = `review-${card.id || card.pr}-h`;
+ const tile = card.draft ? 'bg-zinc-500/15 text-zinc-300' : 'bg-teal-400/15 text-teal-300';
+ const summary = findingsSummary(card.findings);
+ const sec = card.security as Review['security'] & { osv?: unknown; semgrep?: unknown };
+
+ return (
+ <article data-dev-card="review" data-pr={card.pr} aria-labelledby={headingId} className="kw-card min-w-0 p-4">
+ {/* 1. Header */}
+ <header className="flex items-start gap-3">
+ <span className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-xl ${tile}`} aria-hidden="true">
+ <GitPullRequest size={16} />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <h3 id={headingId} className="min-w-0 text-title font-semibold text-zinc-50 [overflow-wrap:anywhere]">
+ #{card.pr} {card.title}
+ </h3>
+ {card.draft && <span className="kw-chip">Draft</span>}
+ {sample && <span className="kw-chip kw-chip-info">Sample PR</span>}
+ </div>
+ <div className="mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-meta text-zinc-400">
+ {card.branch && (
+ <code className="rounded-md border border-hairline bg-surface-main px-1.5 py-0.5 font-mono text-[11px] text-zinc-300 [overflow-wrap:anywhere]">
+ {card.branch}
+ {card.base && ` → ${card.base}`}
+ </code>
+ )}
+ {author && (
+ <span className="inline-flex flex-wrap items-center gap-1">
+ by <Who name={author.name} />
+ {authorModel && <span>on {authorModel}</span>}
+ </span>
+ )}
+ {card.reviewer && (
+ <span className="inline-flex flex-wrap items-center gap-1">
+ <span aria-hidden="true">·</span> reviewed by <Who name={card.reviewer.name} />
+ {reviewerModel && <span>on {reviewerModel}</span>}
+ </span>
+ )}
+ </div>
+ <div className="mt-1.5 flex flex-wrap gap-1.5">
+ {card.reviewer && (card.same_engine ? <span className="kw-chip kw-chip-warn">Same engine as the author</span> : <span className="kw-chip kw-chip-accent">Different engine from the author</span>)}
+ {!card.reviewer && <span className="kw-chip kw-chip-warn">{card.note ?? 'No reviewer yet'}</span>}
+ </div>
+ </div>
+ </header>
+
+ {card.status === 'pending' && <p className="mt-3 text-meta text-zinc-400">Reviewing this PR…</p>}
+ {card.error && (
+ <p className="mt-3 text-meta text-zinc-400">
+ The review didn’t finish: <span className="text-zinc-300">{card.error}</span>
+ </p>
+ )}
+
+ {/* 2. Risk */}
+ {card.risk && (
+ <div data-risk={card.risk.level} className={`mt-3 flex flex-wrap items-center gap-1.5 rounded-xl border p-2.5 ${RISK_BOX[card.risk.level].box}`}>
+ <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold ${RISK_BOX[card.risk.level].pill}`}>
+ <ShieldAlert size={13} aria-hidden="true" />
+ {card.risk.level === 'high' ? 'High risk' : card.risk.level === 'medium' ? 'Medium risk' : 'Low risk'}
+ </span>
+ {riskReasons(card.risk).map((r) => (
+ <span key={r} className="kw-chip">
+ {r}
+ </span>
+ ))}
+ </div>
+ )}
+
+ {/* 3. Intent */}
+ {card.intent && (
+ <section className="mt-4" aria-label="Did it do what was asked?">
+ <SectionHead icon={<Target size={12} aria-hidden="true" />}>Did it do what was asked?</SectionHead>
+ {card.intent.none ? (
+ <p className="text-meta text-zinc-400">No task to compare with. Checked against the PR description.</p>
+ ) : (
+ <p className="rounded-lg border border-hairline bg-surface-main px-3 py-2 text-meta text-zinc-300 [overflow-wrap:anywhere]">
+ <span className="font-semibold text-zinc-100">Asked ({card.intent.source}):</span> {card.intent.asked}
+ </p>
+ )}
+ {card.intent.rows.length > 0 && (
+ <ul role="list" className="mt-2 space-y-1.5">
+ {card.intent.rows.map((r, i) => (
+ <li key={i} data-intent={r.state} className="flex items-start gap-2 text-meta text-zinc-200">
+ <span
+ aria-hidden="true"
+ className={`mt-0.5 flex h-[18px] w-[18px] shrink-0 items-center justify-center rounded-full ${r.state === 'ok' ? 'bg-teal-400/20 text-teal-300' : r.state === 'missing' ? 'bg-rose-400/20 text-rose-300' : 'bg-amber-400/20 text-amber-300'}`}
+ >
+ {r.state === 'ok' ? <Check size={11} /> : r.state === 'missing' ? <X size={11} /> : <AlertTriangle size={10} />}
+ </span>
+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">
+ <span className="sr-only">{r.state === 'ok' ? 'Done: ' : r.state === 'missing' ? 'Missing: ' : 'Extra: '}</span>
+ {r.text}
+ </span>
+ {r.state === 'missing' && <span className="kw-chip kw-chip-bad shrink-0">Did less than asked</span>}
+ {r.state === 'extra' && <span className="kw-chip kw-chip-warn shrink-0">Did more than asked</span>}
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ )}
+
+ {/* 4. Tests */}
+ <section className="mt-4" aria-label="Tests">
+ <SectionHead icon={<FlaskConical size={12} aria-hidden="true" />}>Tests</SectionHead>
+ {card.tamper.flags.length > 0 ? (
+ <div className="space-y-2">
+ {card.tamper.flags.map((t, i) => (
+ <Tamper key={i} flag={t} />
+ ))}
+ </div>
+ ) : (
+ <p className="flex items-center gap-1.5 text-meta text-ok">
+ <Check size={13} aria-hidden="true" />
+ Tests changed with the code. Nothing loosened.
+ </p>
+ )}
+ {card.tamper.unread.length > 0 && (
+ <div data-tamper-unread={card.tamper.unread.length} className="mt-2 text-meta text-zinc-400">
+ <p className="flex items-center gap-1.5 text-warn">
+ <AlertTriangle size={13} aria-hidden="true" />
+ Couldn’t read {card.tamper.unread.length} {card.tamper.unread.length === 1 ? 'file' : 'files'}: GitHub sent no diff, so nothing in{' '}
+ {card.tamper.unread.length === 1 ? 'it' : 'them'} was checked.
+ </p>
+ <ul role="list" className="mt-1 space-y-0.5 pl-5">
+ {card.tamper.unread.map((p) => (
+ <li key={p} className="font-mono text-[11px] text-zinc-300 [overflow-wrap:anywhere]">
+ {p}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </section>
+
+ {/* 5. Security */}
+ <section className="mt-4" aria-label="Security checks">
+ <SectionHead icon={<ShieldCheck size={12} aria-hidden="true" />}>Security checks</SectionHead>
+ <ul role="list" className="grid grid-cols-1 gap-2 min-[420px]:grid-cols-2 lg:grid-cols-4">
+ <SecTile icon={<KeyRound size={13} />} name="Secrets" tool="Gitleaks" state={sec.secrets.state} text={scanText(sec.secrets, 'secret', 'secrets', 'None found')} />
+ <SecTile icon={<Package size={13} />} name="New packages" tool="Registry check" state={sec.packages.state} text={scanText(sec.packages, 'package', 'packages', 'All real')} />
+ <SecTile icon={<Bug size={13} />} name="Dependencies" tool="OSV" state="later" text="in 0.7.x" />
+ <SecTile icon={<Code2 size={13} />} name="Code patterns" tool="Semgrep" state="later" text="in 0.7.x" />
+ </ul>
+ </section>
+
+ {/* 6. Findings */}
+ <section className="mt-4" aria-label="Findings">
+ <SectionHead extra={summary ? <span className="normal-case tracking-normal text-zinc-500">· {summary}</span> : null}>Findings</SectionHead>
+ {card.findings.length === 0 ? (
+ <p className="text-meta text-zinc-400">{card.status === 'ready' ? 'No findings.' : 'No findings yet.'}</p>
+ ) : (
+ <ul role="list" className="space-y-1.5">
+ {card.findings.map((f) => (
+ <FindingRow key={f.id} f={f} author={author?.name ?? null} now={now} busy={busy !== null} act={act} />
+ ))}
+ </ul>
+ )}
+ </section>
+
+ {card.cut && <p className="mt-3 text-2xs text-zinc-400">{card.cut}</p>}
+
+ {/* 7. Footer: 0.7.0 is read only (D4), so there is no Post to GitHub button. */}
+ <footer data-review-footer className="mt-4 flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-hairline pt-3">
+ <span className="inline-flex min-w-0 items-center gap-1.5 text-xs text-zinc-400">
+ <Lock size={13} aria-hidden="true" className="shrink-0" />
+ Read only: nothing is posted to GitHub in this version.
+ </span>
+ {card.links.pr && (
+ <span className="text-meta sm:ml-auto">
+ <OutLink href={card.links.pr}>Open on GitHub</OutLink>
+ </span>
+ )}
+ </footer>
+ </article>
+ );
+};
diff --git a/frontend/src/components/dev/Rollup.tsx b/frontend/src/components/dev/Rollup.tsx
new file mode 100644
index 00000000..a5ff1ff7
--- /dev/null
+++ b/frontend/src/components/dev/Rollup.tsx
@@ -0,0 +1,116 @@
+import React from 'react';
+import { Check, Sparkles, X } from 'lucide-react';
+import type { RollupProps } from '../../dev/types';
+import { clock } from '../../dev/logic';
+
+const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
+
+/** "3 changes landed on main. Nothing needs you." (design §4). */
+export function rollupTitle(count: number, needsYou: number, branch: string): string {
+ const landed = `${plural(count, 'change', 'changes')} landed on ${branch}.`;
+ return `${landed} ${needsYou === 0 ? 'Nothing needs you.' : `${needsYou} ${needsYou === 1 ? 'needs' : 'need'} you.`}`;
+}
+
+/**
+ * Areas that need the person come first (stable). Five or more areas: the first two, then a "+N more" tile,
+ * so the grid stays one row; when more than two need the person, all of those show and only quiet ones fold.
+ */
+export function rollupTiles<T extends { area: string }>(areas: T[], needsYou: string[] = []): { shown: T[]; more: number } {
+ const needs = (a: T) => needsYou.includes(a.area);
+ const sorted = [...areas.filter(needs), ...areas.filter((a) => !needs(a))];
+ if (sorted.length < 5) return { shown: sorted, more: 0 };
+ const keep = Math.max(2, sorted.filter(needs).length);
+ return { shown: sorted.slice(0, keep), more: sorted.length - keep };
+}
+
+/** The "Since you last looked" card at the top of What landed. */
+export const Rollup: React.FC<RollupProps> = ({ rollup, last_tag, last_merge, branch = 'main', needsYouAreas = [], onDraftNotes, onMarkSeen, drafting = false, marking = false }) => {
+ const since = clock(rollup.since);
+ const until = clock(rollup.until);
+ const range = since && until ? `Since you last looked · ${since} → ${until}` : until ? `Everything so far · up to ${until}` : 'Since you last looked';
+
+ if (rollup.count === 0) {
+ const at = last_merge ? clock(last_merge.merged_at) : null;
+ return (
+ <section data-dev-rollup="empty" aria-label="Since you last looked" className="kw-card p-4">
+ <p className="text-meta text-zinc-400">{range}</p>
+ <p className="mt-1 text-body text-zinc-100">
+ Nothing landed since you last looked.
+ {last_merge && ` Last merge: #${last_merge.pr}${at ? `, ${at}` : ''}.`}
+ </p>
+ </section>
+ );
+ }
+
+ const { shown, more } = rollupTiles(rollup.areas, needsYouAreas);
+ const title = rollupTitle(rollup.count, rollup.needs_you, branch);
+ return (
+ <section data-dev-rollup={rollup.needs_you > 0 ? 'needs-you' : 'quiet'} aria-label="Since you last looked" className="kw-card p-4">
+ <div className="flex flex-wrap items-start justify-between gap-x-3 gap-y-2">
+ <div className="min-w-0">
+ <p className="text-meta text-zinc-400">{range}</p>
+ <h3 className="mt-0.5 text-title font-semibold text-zinc-50">{title}</h3>
+ </div>
+ {rollup.main_green === true && (
+ <span className="kw-chip kw-chip-ok shrink-0">
+ <Check size={12} aria-hidden="true" />
+ {branch} is green
+ </span>
+ )}
+ {rollup.main_green === false && (
+ <span className="kw-chip kw-chip-bad shrink-0">
+ <X size={12} aria-hidden="true" />
+ {branch} is red
+ </span>
+ )}
+ </div>
+
+ <ul role="list" className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-3">
+ {shown.map((a) => {
+ const warn = needsYouAreas.includes(a.area);
+ return (
+ <li
+ key={a.area}
+ data-area={a.area}
+ data-needs-you={warn || undefined}
+ className={`min-w-0 rounded-xl border bg-surface-main p-3 ${warn ? 'border-amber-300/50' : 'border-hairline'}`}
+ >
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="min-w-0 text-[13px] font-semibold text-zinc-100 [overflow-wrap:anywhere]">{a.area}</span>
+ <span className="shrink-0 text-meta text-zinc-300" aria-label={plural(a.count, 'change', 'changes')}>
+ {a.count}
+ </span>
+ </div>
+ <p className="mt-1 text-meta text-zinc-400 [overflow-wrap:anywhere]">{a.first_headline}</p>
+ {warn && <p className="mt-1 text-2xs font-semibold text-warn">Needs you</p>}
+ </li>
+ );
+ })}
+ {more > 0 && (
+ <li data-area-more className="flex items-center rounded-xl border border-hairline bg-surface-main p-3 text-meta text-zinc-300">
+ +{more} more {more === 1 ? 'area' : 'areas'}
+ </li>
+ )}
+ </ul>
+
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ <button type="button" onClick={onDraftNotes} disabled={drafting} aria-busy={drafting || undefined} className="kw-btn-primary min-h-[44px] sm:min-h-0 max-sm:flex-1">
+ <Sparkles size={14} aria-hidden="true" />
+ {drafting ? 'Drafting…' : 'Draft release notes'}
+ </button>
+ <button type="button" onClick={onMarkSeen} disabled={marking} aria-busy={marking || undefined} className="kw-btn-ghost min-h-[44px] sm:min-h-0 max-sm:flex-1">
+ {marking ? 'Marking…' : 'Mark all seen'}
+ </button>
+ {/* The "Send me this every morning" link is 0.7.x (plan §1): hidden. */}
+ <p className="w-full text-meta text-zinc-400 sm:ml-auto sm:w-auto">
+ {plural(rollup.count, 'change', 'changes')}
+ {last_tag && (
+ <>
+ {' '}since <code className="font-mono text-zinc-300">{last_tag}</code>
+ </>
+ )}
+ </p>
+ </div>
+ </section>
+ );
+};
diff --git a/frontend/src/components/dev/parts.tsx b/frontend/src/components/dev/parts.tsx
new file mode 100644
index 00000000..210d0828
--- /dev/null
+++ b/frontend/src/components/dev/parts.tsx
@@ -0,0 +1,81 @@
+import React from 'react';
+import { ExternalLink } from 'lucide-react';
+import { ModernAvatar } from '../ModernAvatar';
+import type { DevPerson, RiskLevel } from '../../dev/types';
+import { RISK_WORD } from '../../dev/logic';
+
+/** "Claude Opus" from a label, or a model id like claude-opus-5-5, else the engine's name. */
+export function modelLabel(engine: string | null, model: string | null): string | null {
+ if (model && /\s/.test(model)) return model;
+ const m = model?.match(/^claude-(opus|sonnet|haiku)/i);
+ if (m) return `Claude ${m[1][0].toUpperCase()}${m[1].slice(1).toLowerCase()}`;
+ const names: Record<string, string> = { claude: 'Claude', codex: 'Codex', grok: 'Grok', ollama: 'Ollama' };
+ return engine ? names[engine] ?? engine : null;
+}
+
+export const RISK_CHIP: Record<RiskLevel, string> = { low: 'kw-chip-ok', medium: 'kw-chip-warn', high: 'kw-chip-bad' };
+
+export const RiskChip: React.FC<{ level: RiskLevel }> = ({ level }) => <span className={`kw-chip ${RISK_CHIP[level]}`}>{RISK_WORD[level]}</span>;
+
+/** A 16 px avatar plus the name; the avatar is decoration, the name is read. */
+export const Who: React.FC<{ name: string; strong?: boolean }> = ({ name, strong = true }) => (
+ <span className="inline-flex items-center gap-1 align-middle">
+ <span aria-hidden="true" className="inline-flex shrink-0">
+ <ModernAvatar name={name} size={16} />
+ </span>
+ <span className={strong ? 'font-medium text-zinc-100' : ''}>{name}</span>
+ </span>
+);
+
+export const personText = (p: DevPerson | null) => {
+ if (!p) return null;
+ if (p.kind === 'person') return { name: p.name, sub: null };
+ const m = modelLabel(p.engine, p.model);
+ return { name: p.name, sub: m ? `bot · ${m}` : 'bot' };
+};
+
+/** An https link that opens in a new tab and says so. */
+export const OutLink: React.FC<{ href: string; children: React.ReactNode; className?: string }> = ({ href, children, className = '' }) => (
+ <a
+ href={href}
+ target="_blank"
+ rel="noreferrer noopener"
+ className={`kw-focus inline-flex items-center gap-1 rounded text-sky-300 hover:text-sky-200 ${className}`}
+ >
+ {children}
+ <ExternalLink size={12} aria-hidden="true" />
+ <span className="sr-only">(opens in a new tab)</span>
+ </a>
+);
+
+export const SectionHead: React.FC<{ icon?: React.ReactNode; children: React.ReactNode; extra?: React.ReactNode }> = ({ icon, children, extra }) => (
+ <h4 className="mb-2 flex flex-wrap items-center gap-1.5 text-2xs font-semibold uppercase tracking-wider text-zinc-400">
+ {icon}
+ <span>{children}</span>
+ {extra}
+ </h4>
+);
+
+/**
+ * Drawn in place of a card the renderer can't trust (wrong shape): the PR number and title as plain text
+ * and the GitHub link, nothing computed.
+ */
+export const CardFallback: React.FC<{ raw: unknown }> = ({ raw }) => {
+ const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>;
+ const pr = typeof o.pr === 'number' ? o.pr : null;
+ const title = typeof o.title === 'string' ? o.title : typeof o.headline === 'string' ? o.headline : null;
+ const links = (o.links && typeof o.links === 'object' ? o.links : {}) as Record<string, unknown>;
+ const href = typeof links.pr === 'string' && /^https:\/\//.test(links.pr) ? links.pr : null;
+ return (
+ <div data-dev-card="fallback" className="kw-card p-4 text-body text-zinc-300">
+ <span className="[overflow-wrap:anywhere]">{pr !== null ? `PR #${pr}` : 'A card'}{title ? `: ${title}` : ''}</span>
+ <span className="text-zinc-500"> · This card couldn’t be shown.</span>
+ {href && (
+ <>
+ {' '}
+ <OutLink href={href}>Open on GitHub</OutLink>
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/dev/fixtures.ts b/frontend/src/dev/fixtures.ts
new file mode 100644
index 00000000..92b26242
--- /dev/null
+++ b/frontend/src/dev/fixtures.ts
@@ -0,0 +1,179 @@
+// Fixtures for the Dev mode renderers: the route JSON shapes of impl/lin.md with the cards Vega's generator
+// wrote for #290, #301 and #303 (fixtures/vega-examples.json, copied unchanged from impl/ at round 3), plus #288 and #289 from the design
+// mock (screen 3) and #294 as the "Sample PR" review (screen 4). Tests and the screenshot page use these;
+// the app never imports them. Names are kwant's own bots; nothing here is a real key, token or email.
+
+import vega from './fixtures/vega-examples.json';
+
+const row = (id: string, card: Record<string, unknown>, status = 'ready') => ({ id, status, created_at: '2026-11-05T01:00:00Z', ...card });
+
+/** A fixed clock for tests and shots: 2026-11-05 01:00 UTC. */
+export const FIXTURE_NOW = Date.parse('2026-11-05T01:00:00Z');
+
+const ada = { kind: 'bot', name: 'Ada', engine: 'claude', model: 'Claude Opus' };
+const pixel = { kind: 'bot', name: 'Pixel', engine: 'claude', model: 'Claude Sonnet' };
+const rigel = { id: 'kw_demo_rigel', name: 'Rigel', engine: 'codex', model: 'Codex' };
+const gh = (n: number) => `https://github.com/alexsergivan/kwant/pull/${n}`;
+
+const [v290, v301, v303] = vega as { pr: number; landed: Record<string, unknown>; review: Record<string, unknown> }[];
+
+/** #288 has an open follow-up (N3): never Verified. */
+export const LANDED_288 = row('dvc_288', {
+ kind: 'landed', pr: 288, sha: '9be1c40', merged_at: '2026-11-04T18:48:00Z', merged_by: 'Oleks', written_by: pixel,
+ area: 'Live activity', headline: 'Live activity hides secrets split across chunks', meta: 'redaction code · 249 lines',
+ for_you: "If a bot's thinking spells a password over two chunks, or puts it inside a credential object, the live view now shows dots instead. Ships to the apps in 0.6.11.",
+ under_hood: { summary: 'The redactor now keeps a short tail of the last chunk and checks it together with the next one.', files: [
+ { path: 'src/server/activity.rs', add: 141, del: 9 }, { path: 'src/server/redact.rs', add: 58, del: 4 },
+ { path: 'tests/activity_redact_test.rs', add: 44, del: 0 }, { path: 'docs/live-activity.md', add: 6, del: 2 } ] },
+ risk: { level: 'medium', reasons: ['Security path: redaction', '+249 −15 in 4 files'] },
+ tests: { state: 'passed', summary: '3 checks passed' }, reviewed_by: 'Rigel',
+ follow_ups: [{ text: 'password: X, Bearer/Basic headers and quoted values with spaces still show live. With Pixel.', ref: '#288 N3' }],
+ verified: false, links: { pr: gh(288), commit: 'https://github.com/alexsergivan/kwant/commit/9be1c40', ci: null }, cut: null,
+});
+
+export const LANDED_289 = row('dvc_289', {
+ kind: 'landed', pr: 289, sha: '2f6d0aa', merged_at: '2026-11-04T18:32:00Z', merged_by: 'Oleks', written_by: ada,
+ area: 'Spaces rail', headline: "The open space's ring isn't cut off any more",
+ for_you: 'The ring around the open space and its unread badge now show in full on the rail. Live on kwant.jumpin.games.',
+ under_hood: { summary: 'The rail no longer clips its children; the ring moved inside the tile.', files: [{ path: 'frontend/src/components/Spaces.tsx', add: 5, del: 2 }] },
+ risk: { level: 'low', reasons: ['+5 −2 in 1 file'] }, tests: { state: 'passed', summary: '3 checks passed' }, reviewed_by: 'Rigel',
+ follow_ups: [], verified: true, links: { pr: gh(289), commit: null, ci: null }, cut: null,
+});
+
+export const LANDED_290 = row('dvc_290', v290.landed);
+export const LANDED_301 = row('dvc_301', v301.landed);
+export const LANDED_303 = row('dvc_303', v303.landed);
+
+/** §3.6 item 12: no writer text. Headline = the PR title; area, for_you, summary are null. */
+export const LANDED_NO_TEXT = row('dvc_311', {
+ kind: 'landed', pr: 311, sha: 'a1b2c3d', merged_at: '2026-11-03T10:05:00Z', merged_by: 'Oleks', written_by: { kind: 'person', name: 'Oleks' },
+ title: 'Bump vite to 6.4.4', headline: null, area: null, for_you: null,
+ under_hood: { summary: null, files: [{ path: 'frontend/package-lock.json', add: 12, del: 12 }] },
+ risk: { level: 'low', reasons: ['+12 −12 in 1 file'] }, tests: { state: 'passed', summary: '3 checks passed' }, reviewed_by: null,
+ follow_ups: [], verified: false, links: { pr: gh(311), commit: null, ci: null }, cut: 'diff cut, 2 files not read',
+}, 'failed');
+(LANDED_NO_TEXT as Record<string, unknown>).error = 'The writer bot was over its daily cap';
+
+export const REVIEW_290 = row('dvr_290', v290.review);
+export const REVIEW_301 = row('dvr_301', v301.review);
+export const REVIEW_303 = row('dvr_303', v303.review);
+export const REVIEW_289 = row('dvr_289', { kind: 'review', pr: 289, title: 'Spaces rail ring', author: ada, reviewer: rigel, same_engine: false, findings: [] });
+
+/** #294, sample review content (design §5, screen 4). Shown with the "Sample PR" chip. */
+export const REVIEW_294 = row('dvr_294', {
+ kind: 'review', pr: 294, title: 'Live redaction: catch password: X, Bearer/Basic and quoted values', branch: 'pixel-live-redact-n3', base: 'main', draft: false,
+ author: pixel, reviewer: rigel, same_engine: false, note: null,
+ risk: { level: 'high', reasons: ['Security path: redaction', 'A test was loosened', 'Changed a file outside the task', '+212 −40 in 5 files'] },
+ intent: { source: 'N3', asked: 'hide password: X, Bearer/Basic headers and quoted values with spaces in live activity.', none: false, rows: [
+ { state: 'ok', text: 'password: X is hidden' }, { state: 'ok', text: 'Bearer and Basic headers are hidden' },
+ { state: 'missing', text: 'Quoted values with spaces still show the part after the space' },
+ { state: 'extra', text: 'Also rewords a log line in src/drivers/browser.rs' } ] },
+ tamper: { flags: [{ kind: 'loosened', file: 'src/server/activity.rs', line: 418,
+ why: 'redacts_bearer_header used to check the exact hidden line. Now it only checks that "Bearer" appears, so a leak would still pass. A new #[ignore] skips redacts_quoted_value.',
+ excerpt: '- assert_eq!(out, "Authorization: Bearer ••••");\n+ assert!(out.contains("Bearer"));' }] },
+ security: { secrets: { state: 'pass', count: 0 }, packages: { state: 'pass', count: 0 }, osv: { state: 'later' }, semgrep: { state: 'later' } },
+ findings: [
+ { id: 'f1', severity: 'high', title: 'Quoted values with spaces still leak in live activity', file: 'src/drivers/activity.rs', line: 212,
+ detail: 'The new pattern stops at the first space, so token="abc def" shows def.', fix: 'match up to the closing quote, and un-ignore redacts_quoted_value.',
+ source: 'review', state: 'open', sent_at: null, dismissed: null },
+ { id: 'f2', severity: 'medium', title: 'A test was weakened instead of the code being fixed', file: 'src/server/activity.rs', line: 418,
+ detail: 'redacts_bearer_header now passes even if the header leaks.', fix: 'Put the exact assert back.',
+ source: 'tamper', state: 'sent', sent_at: '2026-11-05T00:59:55Z', sent_to: 'Pixel', dismissed: null },
+ { id: 'f3', severity: 'low', title: 'Unrelated change in browser.rs', file: 'src/drivers/browser.rs', line: 88,
+ detail: 'A log line was reworded. Move it to its own PR or drop it.', fix: null, source: 'review', state: 'open', sent_at: null, dismissed: null },
+ ],
+ cut: null, links: { pr: gh(294), commit: null, ci: null },
+});
+
+/** §3.6 item 10: no second bot in the space. */
+export const REVIEW_NO_REVIEWER = row('dvr_312', {
+ kind: 'review', pr: 312, title: 'Dev mode: landed and review cards', branch: 'vega-dev-cards', base: 'main', draft: true,
+ author: { kind: 'bot', name: 'Vega', engine: 'claude', model: 'Claude Opus' }, reviewer: null, same_engine: false,
+ note: 'No reviewer: add a second bot to this space',
+ risk: { level: 'medium', reasons: ['Has a migration', '+1840 −12 in 14 files'] }, intent: null, tamper: { flags: [], unread: ['Cargo.lock', 'frontend/package-lock.json'] },
+ security: { secrets: { state: 'not_run', count: 0 }, packages: { state: 'not_run', count: 0 } }, findings: [],
+ cut: 'diff cut, 3 files not read', links: { pr: gh(312), commit: null, ci: null },
+});
+
+export const LANDED_ROUTE = {
+ cards: [LANDED_303, LANDED_301, LANDED_290, LANDED_288, LANDED_289],
+ rollup: { since: '2026-11-04T17:40:00Z', until: '2026-11-05T01:00:00Z', count: 5, needs_you: 2, main_green: true, areas: [
+ { area: 'Chat', count: 1, first_headline: 'A 👍 or 👎 reaches the bot once' },
+ { area: 'Sidebar', count: 2, first_headline: 'Long bot names wrap between words, not inside them' },
+ { area: 'Live activity', count: 1, first_headline: 'Live activity hides secrets split across chunks' },
+ { area: 'Spaces rail', count: 1, first_headline: "The open space's ring isn't cut off any more" } ] },
+ last_tag: 'mac-v0.6.10',
+};
+
+export const ROLLUP_QUIET = {
+ since: '2026-11-04T17:40:00Z', until: '2026-11-04T19:51:00Z', count: 3, needs_you: 0, main_green: true, areas: [
+ { area: 'Sidebar', count: 1, first_headline: 'Bot rows stop jumping on hover' },
+ { area: 'Live activity', count: 1, first_headline: 'Secrets split across chunks are hidden' },
+ { area: 'Spaces rail', count: 1, first_headline: "The open space's ring isn't cut off" } ] };
+
+export const ROLLUP_EMPTY = { since: '2026-11-05T00:30:00Z', until: '2026-11-05T01:00:00Z', count: 0, needs_you: 0, main_green: true, areas: [] };
+
+export const ROLLUP_MANY = { ...ROLLUP_QUIET, count: 7, main_green: false, areas: [
+ ...ROLLUP_QUIET.areas, { area: 'Chat', count: 2, first_headline: 'A reaction reaches the bot once' },
+ { area: 'Settings', count: 1, first_headline: 'Backup command field' }, { area: 'Docs', count: 1, first_headline: 'Dev mode guide' } ] };
+
+export const RELEASE_PENDING = row('dvc_rn1', { kind: 'release_notes' }, 'pending');
+export const RELEASE_READY = row('dvc_rn1', {
+ kind: 'release_notes', since_tag: 'mac-v0.6.12',
+ whats_new: 'Sidebar rows hold still, long names wrap between words, and reactions reach a bot once.',
+ markdown: '## What changed since mac-v0.6.12\n\n### Sidebar\n- Rows stop jumping on hover (#290)\n- Long bot names wrap between words, not inside them (#301)\n\n### Chat\n- A reaction reaches the bot once, even in the same second as its reply (#303)\n',
+});
+
+// ---- Production floor (approval cards) ----
+
+const floorApproval = (id: string, bot: string, command: string, prod_floor: Record<string, unknown>, cwd = '~/work/kwant-deploy') => ({
+ id, tool_name: 'execute_shell',
+ details: { source: 'local_shell', kwant_name: bot, arguments: { command, cwd }, prod_floor: { space_id: 's_kwant', ...prod_floor } },
+});
+
+export const FLOOR_DEPLOY_FRESH = floorApproval('ap_1', 'Pixel', './scripts/deploy_test.sh 4049325', {
+ kind: 'deploy', why: 'a deploy to the test server', needs_backup: false,
+ blast: [['Where', 'kwant.jumpin.games · production'], ['What changes', 'App 51f9141 → 4049325 · 1 change: #290 sidebar hover'],
+ ['Downtime', 'About 20 s while the container restarts'], ['Data', 'Nothing deleted. Database and uploads stay.'],
+ ['If it fails', 'Health check fails → it goes back to 51f9141 on its own']],
+ backup: { state: 'fresh', age_s: 14, bytes: 412_000_000, path: '/home/demo/backups/backup-2026-11-04-pre-4049325.tgz', error: null },
+});
+
+export const FLOOR_DESTRUCTIVE = floorApproval('ap_2', 'Lin', 'sqlite3 data/kwant.db "DROP TABLE dev_cards_v0;"', {
+ kind: 'destructive', why: 'a database command that runs DROP TABLE', needs_backup: true,
+ blast: [['Where', 'kwant.jumpin.games database · production'], ['Data', "Table dev_cards_v0 · 1,284 rows. Can't be undone without a backup."]],
+ backup: { state: 'old', age_s: 3 * 3600, bytes: 412_000_000, path: '/home/demo/backups/backup-old.tgz', error: null },
+}, '~/work/kwant');
+
+export const FLOOR_MIGRATION = floorApproval('ap_3', 'Vega', './scripts/deploy_test.sh 7c41e0a', {
+ kind: 'deploy_migration', why: 'a deploy that changes the database', needs_backup: true,
+ blast: [['Where', 'kwant.jumpin.games · production'], ['What changes', 'App 4049325 → 7c41e0a · 1 change: #301 risk reasons'],
+ ['Migration', '0031_landed_risk.sql · adds 1 column to landed_cards · has a way back'],
+ ['If it fails', 'The app goes back on its own. The database goes back only from a backup.']],
+ backup: { state: 'old', age_s: 41 * 60, bytes: 412_000_000, path: null, error: null },
+});
+
+export const FLOOR_DEPLOY_OLD = floorApproval('ap_4', 'Iris', './scripts/deploy_test.sh 9a2d5f3', {
+ kind: 'deploy', why: 'a deploy to the test server', needs_backup: false,
+ blast: [['Where', 'kwant.jumpin.games · production'], ['What changes', 'App 7c41e0a → 9a2d5f3 · 1 change: #292 reactions'],
+ ['Data', 'No migration. Database and uploads stay.']],
+ backup: { state: 'old', age_s: 3 * 3600, bytes: 412_000_000, path: null, error: null },
+});
+
+export const FLOOR_PAGES = floorApproval('ap_5', 'Pixel', 'npx wrangler pages deploy site/dist', {
+ kind: 'deploy', why: 'a Cloudflare Pages deploy', needs_backup: false,
+ blast: [['Where', 'kwant.si · production'], ['Key used', 'Cloudflare · production']],
+ backup: { state: 'no_data', age_s: null, bytes: null, path: null, error: null },
+});
+
+export const FLOOR_NO_COMMAND = floorApproval('ap_6', 'Lin', 'psql -c "DELETE FROM sessions"', {
+ kind: 'destructive', why: 'a database command that runs DELETE without WHERE', needs_backup: true,
+ blast: [['Where', 'db.example.com · production']],
+ backup: { state: 'no_command', age_s: null, bytes: null, path: null, error: null },
+});
+
+export const FLOOR_FAILED = floorApproval('ap_7', 'Lin', 'sqlite3 data/kwant.db "DROP TABLE old_x;"', {
+ kind: 'destructive', why: 'a database command that runs DROP TABLE', needs_backup: true,
+ blast: [['Where', 'kwant.jumpin.games database · production']],
+ backup: { state: 'failed', age_s: null, bytes: null, path: null, error: 'disk full' },
+});
diff --git a/frontend/src/dev/fixtures/vega-examples.json b/frontend/src/dev/fixtures/vega-examples.json
new file mode 100644
index 00000000..07425f62
--- /dev/null
+++ b/frontend/src/dev/fixtures/vega-examples.json
@@ -0,0 +1,381 @@
+[
+ {
+ "landed": {
+ "area": "Sidebar",
+ "cut": null,
+ "follow_ups": [],
+ "for_you": "Hovering a bot no longer pushes its name onto a second line, so the list stays still.",
+ "headline": "Sidebar rows stop jumping on hover",
+ "kind": "landed",
+ "links": {
+ "ci": "https://github.com/alexsergivan/kwant/actions/runs/41891504299/job/126790334867",
+ "commit": "https://github.com/alexsergivan/kwant/commit/4049325ddcd05aec5d2b442826d20fbd5cc8c066",
+ "pr": "https://github.com/alexsergivan/kwant/pull/290"
+ },
+ "merged_at": "2026-11-04T19:26:30Z",
+ "merged_by": "Oleks",
+ "pr": 290,
+ "reviewed_by": "Rigel",
+ "risk": {
+ "level": "low",
+ "reasons": [
+ "Small change, tests nearby",
+ "+27 −9 in 2 files"
+ ]
+ },
+ "sha": "4049325",
+ "tests": {
+ "state": "passed",
+ "summary": "3 checks passed"
+ },
+ "under_hood": {
+ "files": [
+ {
+ "add": 10,
+ "del": 6,
+ "path": "frontend/src/components/Sidebar.tsx"
+ },
+ {
+ "add": 17,
+ "del": 3,
+ "path": "frontend/tests/polish063.test.mjs"
+ }
+ ],
+ "summary": "Only the sidebar's CSS changed: the hover space moved from the name to the status line, and a test pins it."
+ },
+ "verified": true,
+ "written_by": {
+ "engine": "claude",
+ "kind": "bot",
+ "model": "claude-opus-5-5",
+ "name": "Ada"
+ }
+ },
+ "pr": 290,
+ "review": {
+ "author": {
+ "engine": "claude",
+ "kind": "bot",
+ "model": "claude-opus-5-5",
+ "name": "Ada"
+ },
+ "base": "main",
+ "branch": "ada-row-hover",
+ "cut": null,
+ "draft": false,
+ "findings": [],
+ "intent": {
+ "asked": "Sidebar: hovering a bot row no longer wraps its name or changes the row's height",
+ "none": true,
+ "rows": [
+ {
+ "state": "ok",
+ "text": "Does what the PR description says"
+ }
+ ],
+ "source": "pr"
+ },
+ "kind": "review",
+ "pr": 290,
+ "reviewer": {
+ "engine": "codex",
+ "id": "kw_demo_rigel",
+ "model": "auto",
+ "name": "Rigel"
+ },
+ "risk": {
+ "level": "low",
+ "reasons": [
+ "Small change, tests nearby",
+ "+27 −9 in 2 files"
+ ]
+ },
+ "same_engine": false,
+ "security": {
+ "osv": {
+ "state": "later"
+ },
+ "packages": {
+ "count": 0,
+ "state": "not_run"
+ },
+ "secrets": {
+ "count": 0,
+ "state": "not_run"
+ },
+ "semgrep": {
+ "state": "later"
+ }
+ },
+ "tamper": {
+ "flags": [],
+ "unread": []
+ },
+ "title": "Sidebar: hovering a bot row no longer wraps its name or changes the row's height"
+ }
+ },
+ {
+ "landed": {
+ "area": "Sidebar",
+ "cut": null,
+ "follow_ups": [],
+ "for_you": "A name like \"Researcher\" next to \"Needs you\" stays whole; very long words end in \"…\" and the full name is in the tooltip.",
+ "headline": "Long bot names wrap between words, not inside them",
+ "kind": "landed",
+ "links": {
+ "ci": "https://github.com/alexsergivan/kwant/actions/runs/41929248024/job/126922241066",
+ "commit": "https://github.com/alexsergivan/kwant/commit/fd51f46faf1d6e6cf79b39058c56ec39706346b7",
+ "pr": "https://github.com/alexsergivan/kwant/pull/301"
+ },
+ "merged_at": "2026-11-04T23:37:23Z",
+ "merged_by": "Oleks",
+ "pr": 301,
+ "reviewed_by": "Rigel",
+ "risk": {
+ "level": "low",
+ "reasons": [
+ "Small change, tests nearby",
+ "+132 −13 in 3 files"
+ ]
+ },
+ "sha": "fd51f46",
+ "tests": {
+ "state": "passed",
+ "summary": "3 checks passed"
+ },
+ "under_hood": {
+ "files": [
+ {
+ "add": 26,
+ "del": 12,
+ "path": "frontend/src/components/Sidebar.tsx"
+ },
+ {
+ "add": 2,
+ "del": 1,
+ "path": "frontend/tests/ia.test.mjs"
+ },
+ {
+ "add": 104,
+ "del": 0,
+ "path": "frontend/tests/nameWrap.test.mjs"
+ }
+ ],
+ "summary": "The name line now wraps only at spaces or hyphens on up to two lines; \"Needs you\" becomes a small hand icon. New tests cover the wrap rule."
+ },
+ "verified": true,
+ "written_by": {
+ "engine": "claude",
+ "kind": "bot",
+ "model": "claude-opus-5-5",
+ "name": "Pixel"
+ }
+ },
+ "pr": 301,
+ "review": {
+ "author": {
+ "engine": "claude",
+ "kind": "bot",
+ "model": "claude-opus-5-5",
+ "name": "Pixel"
+ },
+ "base": "main",
+ "branch": "pixel-name-wrap",
+ "cut": null,
+ "draft": false,
+ "findings": [],
+ "intent": {
+ "asked": "Sidebar: a bot's name wraps only between words; Needs you is a compact hand",
+ "none": true,
+ "rows": [
+ {
+ "state": "ok",
+ "text": "Does what the PR description says"
+ }
+ ],
+ "source": "pr"
+ },
+ "kind": "review",
+ "pr": 301,
+ "reviewer": {
+ "engine": "codex",
+ "id": "kw_demo_rigel",
+ "model": "auto",
+ "name": "Rigel"
+ },
+ "risk": {
+ "level": "low",
+ "reasons": [
+ "Small change, tests nearby",
+ "+132 −13 in 3 files"
+ ]
+ },
+ "same_engine": false,
+ "security": {
+ "osv": {
+ "state": "later"
+ },
+ "packages": {
+ "count": 0,
+ "state": "not_run"
+ },
+ "secrets": {
+ "count": 0,
+ "state": "not_run"
+ },
+ "semgrep": {
+ "state": "later"
+ }
+ },
+ "tamper": {
+ "flags": [],
+ "unread": []
+ },
+ "title": "Sidebar: a bot's name wraps only between words; Needs you is a compact hand"
+ }
+ },
+ {
+ "landed": {
+ "area": "Chat",
+ "cut": null,
+ "follow_ups": [
+ {
+ "ref": "#303 f1",
+ "text": "A turn that fails after its prompt loses the reaction"
+ }
+ ],
+ "for_you": "When you react to a bot's message, its next turn hears about it once, even if you reacted in the same second as its reply.",
+ "headline": "A 👍 or 👎 reaches the bot once",
+ "kind": "landed",
+ "links": {
+ "ci": "https://github.com/alexsergivan/kwant/actions/runs/41935033589/job/126941762796",
+ "commit": "https://github.com/alexsergivan/kwant/commit/0cc0cfc9f54ea29f4048e8782d001c3886de7e79",
+ "pr": "https://github.com/alexsergivan/kwant/pull/303"
+ },
+ "merged_at": "2026-11-05T00:00:19Z",
+ "merged_by": "Oleks",
+ "pr": 303,
+ "reviewed_by": "Rigel",
+ "risk": {
+ "level": "medium",
+ "reasons": [
+ "Has a migration",
+ "+126 −7 in 4 files"
+ ]
+ },
+ "sha": "0cc0cfc",
+ "tests": {
+ "state": "passed",
+ "summary": "3 checks passed"
+ },
+ "under_hood": {
+ "files": [
+ {
+ "add": 3,
+ "del": 2,
+ "path": "docs/reactions-and-replies.md"
+ },
+ {
+ "add": 92,
+ "del": 4,
+ "path": "src/db/reactions.rs"
+ },
+ {
+ "add": 5,
+ "del": 1,
+ "path": "src/server/reactions.rs"
+ },
+ {
+ "add": 26,
+ "del": 0,
+ "path": "tests/reactions_replies_test.rs"
+ }
+ ],
+ "summary": "Reactions are now marked told when they go into a turn's note, instead of being compared by second-precision timestamps. A migration adds the told column."
+ },
+ "verified": false,
+ "written_by": {
+ "engine": "claude",
+ "kind": "bot",
+ "model": "claude-opus-5-5",
+ "name": "Pixel"
+ }
+ },
+ "pr": 303,
+ "review": {
+ "author": {
+ "engine": "claude",
+ "kind": "bot",
+ "model": "claude-opus-5-5",
+ "name": "Pixel"
+ },
+ "base": "main",
+ "branch": "vega-reaction-told-once",
+ "cut": null,
+ "draft": false,
+ "findings": [
+ {
+ "detail": "mark_told runs while the note is built, before the turn runs. If the turn then fails, the reaction is marked told but the bot never heard it.",
+ "dismissed": null,
+ "file": "src/server/reactions.rs",
+ "fix": "Mark the reactions told after the turn finishes, or unmark them when it fails.",
+ "id": "f1",
+ "line": 213,
+ "sent_at": null,
+ "severity": "medium",
+ "source": "review",
+ "state": "open",
+ "title": "A turn that fails after its prompt loses the reaction"
+ }
+ ],
+ "intent": {
+ "asked": "Tell a 👍/👎 to the bot's next turn once, even in the same second as its reply",
+ "none": true,
+ "rows": [
+ {
+ "state": "ok",
+ "text": "Does what the PR description says"
+ }
+ ],
+ "source": "pr"
+ },
+ "kind": "review",
+ "pr": 303,
+ "reviewer": {
+ "engine": "codex",
+ "id": "kw_demo_rigel",
+ "model": "auto",
+ "name": "Rigel"
+ },
+ "risk": {
+ "level": "medium",
+ "reasons": [
+ "Has a migration",
+ "+126 −7 in 4 files"
+ ]
+ },
+ "same_engine": false,
+ "security": {
+ "osv": {
+ "state": "later"
+ },
+ "packages": {
+ "count": 0,
+ "state": "not_run"
+ },
+ "secrets": {
+ "count": 0,
+ "state": "not_run"
+ },
+ "semgrep": {
+ "state": "later"
+ }
+ },
+ "tamper": {
+ "flags": [],
+ "unread": []
+ },
+ "title": "Tell a 👍/👎 to the bot's next turn once, even in the same second as its reply"
+ }
+ }
+]
\ No newline at end of file
diff --git a/frontend/src/dev/logic.ts b/frontend/src/dev/logic.ts
new file mode 100644
index 00000000..134ef81f
--- /dev/null
+++ b/frontend/src/dev/logic.ts
@@ -0,0 +1,347 @@
+// Pure rules behind the Dev mode renderers, kept out of the components so the node tests can pin them:
+// the Verified sticker (§3.6 item 14, design §4), the production-floor backup state machine (design §6,
+// all seven cases), the 500 ms Allow guard, the Fix it undo window and the dismiss flow (design §5.6).
+
+import type {
+ BackupResult,
+ DevFinding,
+ DismissReason,
+ FloorBackup,
+ LandedCard,
+ ProdFloor,
+ ReviewCard,
+ RiskLevel,
+} from './types';
+
+// ---------------------------------------------------------------------------------------------------
+// Time and numbers (display only: nothing here computes a new figure from the data)
+
+const pad = (n: number) => String(n).padStart(2, '0');
+
+/** "19:26" in the viewer's own time zone, or null. */
+export function clock(iso: string | null): string | null {
+ if (!iso) return null;
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? null : `${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+const dayKey = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+
+/** "Today", "Yesterday", or "Mon 2 Nov" for a landed card's day separator. */
+export function dayLabel(iso: string | null, now: number): string {
+ if (!iso) return 'Earlier';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return 'Earlier';
+ const today = new Date(now);
+ const yesterday = new Date(now);
+ yesterday.setDate(yesterday.getDate() - 1);
+ if (dayKey(d) === dayKey(today)) return 'Today';
+ if (dayKey(d) === dayKey(yesterday)) return 'Yesterday';
+ const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
+ const mo = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
+ return `${wd} ${d.getDate()} ${mo}${d.getFullYear() !== today.getFullYear() ? ` ${d.getFullYear()}` : ''}`;
+}
+
+/** Cards grouped under day separators, keeping the server's order (newest first). */
+export function byDay<T extends { merged_at: string | null }>(cards: T[], now: number): { label: string; cards: T[] }[] {
+ const out: { label: string; cards: T[] }[] = [];
+ for (const c of cards) {
+ const label = dayLabel(c.merged_at, now);
+ const last = out[out.length - 1];
+ if (last && last.label === label) last.cards.push(c);
+ else out.push({ label, cards: [c] });
+ }
+ return out;
+}
+
+/** "14 s", "41 min", "3 h", "2 days". */
+export function age(seconds: number): string {
+ const s = Math.max(0, Math.floor(seconds));
+ if (s < 60) return `${s} s`;
+ if (s < 3600) return `${Math.floor(s / 60)} min`;
+ if (s < 48 * 3600) return `${Math.floor(s / 3600)} h`;
+ return `${Math.floor(s / 86400)} days`;
+}
+
+/** "412 MB" from the byte count the server gave. */
+export function size(bytes: number | null): string | null {
+ if (bytes === null) return null;
+ if (bytes < 1000) return `${bytes} B`;
+ if (bytes < 1e6) return `${Math.round(bytes / 1e3)} KB`;
+ if (bytes < 1e9) return `${Math.round(bytes / 1e6)} MB`;
+ return `${(bytes / 1e9).toFixed(1)} GB`;
+}
+
+export const fileName = (path: string | null) => (path ? path.split('/').pop() || path : null);
+
+export const RISK_WORD: Record<RiskLevel, string> = { low: 'Low risk', medium: 'Medium risk', high: 'High risk' };
+
+/** Design §5.2: a badge never stands alone. Low with no signals reads "Small change, tests nearby". */
+export function riskReasons(risk: { level: RiskLevel; reasons: string[] } | null): string[] {
+ if (!risk) return [];
+ return risk.reasons.length > 0 ? risk.reasons : risk.level === 'low' ? ['Small change, tests nearby'] : ['No reason given'];
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Verified sticker (§3.6 item 14)
+
+const sameName = (a: string | null | undefined, b: string | null | undefined) =>
+ !!a && !!b && a.trim().toLowerCase() === b.trim().toLowerCase();
+
+/** A finding is open until it is fixed or dismissed (item 14). One sent as a Fix it task is still open. */
+export const isOpen = (f: DevFinding) => f.state !== 'dismissed';
+
+/** Findings in a review that still need the person: open or sent, never dismissed. */
+export const openFindings = (review: ReviewCard | null | undefined) => (review ? review.findings.filter(isOpen).length : 0);
+
+/**
+ * The holo "Verified" sticker shows only when every one of these holds; the server's own `verified` is
+ * one of them, so the client can only ever be stricter than the server:
+ * - the server says verified;
+ * - CI is green (tests passed);
+ * - someone reviewed it in kwant, and the reviewer is not the author;
+ * - no follow-up is open;
+ * - if the PR's review card is known, it has a reviewer who isn't the author and no open finding.
+ * A pending or stale card never gets one.
+ */
+export function showVerified(card: LandedCard, reviews: ReviewCard[] = []): boolean {
+ if (!card.verified || card.status === 'pending' || card.status === 'stale') return false;
+ if (card.tests.state !== 'passed') return false;
+ if (!card.reviewed_by || sameName(card.reviewed_by, card.written_by?.name)) return false;
+ if (card.follow_ups.length > 0) return false;
+ const review = reviews.find((r) => r.pr === card.pr);
+ if (review) {
+ if (!review.reviewer || sameName(review.reviewer.name, review.author?.name)) return false;
+ if (review.findings.some(isOpen)) return false;
+ }
+ return true;
+}
+
+/** Areas the roll-up marks with a warn border: a card there has an open follow-up or red CI. */
+export function needsYouAreas(cards: LandedCard[]): string[] {
+ const out = new Set<string>();
+ for (const c of cards) if (c.area && (c.follow_ups.length > 0 || c.tests.state === 'failed')) out.add(c.area);
+ return [...out];
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Production floor: backup state machine (design §6)
+
+export const FRESH_S = 600;
+export const ALLOW_GUARD_MS = 500;
+
+/** What the card is doing locally on top of the server's backup state. */
+export interface FloorUi {
+ /** idle: as the server said. taking: a backup is running. done: a backup this card took is ok. failed: it failed. */
+ phase: 'idle' | 'taking' | 'done' | 'failed';
+ /** The backup the card took (done), with the epoch ms it finished. */
+ taken: { bytes: number | null; path: string | null; at: number } | null;
+ error: string | null;
+ /** Epoch ms when Allow appeared in place of Back up first; presses before +500 ms are ignored. */
+ armedAt: number | null;
+}
+
+export type FloorEvent =
+ | { type: 'backup_start' }
+ | { type: 'backup_done'; result: BackupResult; now: number }
+ | { type: 'backup_error'; error: string };
+
+export const initialFloorUi = (floor: ProdFloor): FloorUi => ({
+ phase: floor.backup.state === 'taking' ? 'taking' : floor.backup.state === 'failed' ? 'failed' : 'idle',
+ taken: null,
+ error: floor.backup.state === 'failed' ? floor.backup.error : null,
+ armedAt: null,
+});
+
+export function floorReducer(ui: FloorUi, ev: FloorEvent): FloorUi {
+ switch (ev.type) {
+ case 'backup_start':
+ // One backup at a time: a second press while one runs changes nothing.
+ return ui.phase === 'taking' ? ui : { ...ui, phase: 'taking', error: null, armedAt: null };
+ case 'backup_done':
+ if (ui.phase !== 'taking') return ui;
+ if (!ev.result.ok) return { ...ui, phase: 'failed', error: ev.result.error ?? 'no reason given', armedAt: null };
+ return { phase: 'done', taken: { bytes: ev.result.bytes, path: ev.result.path, at: ev.now }, error: null, armedAt: ev.now };
+ case 'backup_error':
+ return ui.phase !== 'taking' ? ui : { ...ui, phase: 'failed', error: ev.error, armedAt: null };
+ }
+}
+
+/** True once the new Allow may act: never in its first 500 ms. */
+export const allowReady = (ui: FloorUi, now: number) => ui.armedAt === null || now - ui.armedAt >= ALLOW_GUARD_MS;
+
+export type RowTone = 'ok' | 'warn' | 'bad' | 'neutral' | 'info';
+export type FloorCase = 'fresh' | 'old_plain' | 'just_taken' | 'no_data' | 'blocked' | 'no_command' | 'taking' | 'failed';
+
+export interface FloorView {
+ case: FloorCase;
+ tone: RowTone;
+ /** Bold lead, then the rest of the line. */
+ lead: string;
+ text: string;
+ /** The file name (mono) after the size, when known. */
+ file: string | null;
+ /** The main button: Allow, Back up first (in Allow's place), Try the backup again, or none. */
+ main: 'allow' | 'backup' | 'retry' | 'none';
+ /** A secondary Back up first beside Allow (plain deploy, old backup). */
+ secondaryBackup: boolean;
+ /** Every button waits (taking). */
+ busy: boolean;
+ /** The right-hand note. */
+ note: string;
+}
+
+/**
+ * The backup row and buttons for a floor card at time `now`. `mountedAt` is when the card got the
+ * server's `age_s`, so a fresh backup ages on screen and turns old after 10 minutes.
+ */
+export function floorView(floor: ProdFloor, ui: FloorUi, now: number, mountedAt: number = now): FloorView {
+ const b: FloorBackup = floor.backup;
+ const blockedNote = 'Nothing runs without a fresh backup.';
+ const plainNote = 'No “always allow” on the production floor.';
+ const note = floor.needs_backup ? blockedNote : plainNote;
+ const sz = (bytes: number | null) => (size(bytes) ? ` · ${size(bytes)}` : '');
+
+ if (ui.phase === 'taking') {
+ const pct = typeof b.percent === 'number' && b.state === 'taking' ? ` ${Math.round(b.percent)} %` : '';
+ return { case: 'taking', tone: 'info', lead: '', text: `Taking a backup…${pct}`, file: null, main: floor.needs_backup ? 'backup' : 'allow', secondaryBackup: !floor.needs_backup, busy: true, note };
+ }
+ if (ui.phase === 'failed') {
+ const why = (ui.error ?? 'no reason given').replace(/[.\s]+$/, '');
+ return { case: 'failed', tone: 'bad', lead: 'Backup failed:', text: ` ${why}.`, file: null, main: 'retry', secondaryBackup: false, busy: false, note: blockedNote };
+ }
+ if (ui.phase === 'done' && ui.taken) {
+ const secs = (now - ui.taken.at) / 1000;
+ if (secs <= FRESH_S) {
+ return { case: 'just_taken', tone: 'ok', lead: `Backup taken ${age(secs)} ago`, text: sz(ui.taken.bytes), file: null, main: 'allow', secondaryBackup: false, busy: false, note: plainNote };
+ }
+ }
+ if (b.state === 'no_data') {
+ return { case: 'no_data', tone: 'neutral', lead: '', text: 'Nothing to back up: this site has no database or uploads.', file: null, main: 'allow', secondaryBackup: false, busy: false, note: plainNote };
+ }
+ if (b.state === 'no_command' && floor.needs_backup) {
+ return { case: 'no_command', tone: 'bad', lead: 'No backup command.', text: ' Set a backup command in Dev mode settings.', file: null, main: 'none', secondaryBackup: false, busy: false, note: blockedNote };
+ }
+ const liveAge = b.age_s === null ? null : b.age_s + Math.max(0, now - mountedAt) / 1000;
+ const fresh = (b.state === 'fresh' || b.state === 'old') && liveAge !== null && liveAge <= FRESH_S;
+ if (fresh && liveAge !== null) {
+ return { case: 'fresh', tone: 'ok', lead: `Backup taken ${age(liveAge)} ago`, text: sz(b.bytes), file: fileName(b.path), main: 'allow', secondaryBackup: false, busy: false, note: plainNote };
+ }
+ const never = liveAge === null || b.state === 'none' || b.state === 'no_command';
+ if (floor.needs_backup) {
+ return { case: 'blocked', tone: 'bad', lead: never ? 'No backup yet.' : 'No fresh backup.', text: never ? '' : ` The last one is ${age(liveAge!)} old.`, file: null, main: 'backup', secondaryBackup: false, busy: false, note: blockedNote };
+ }
+ return {
+ case: 'old_plain',
+ tone: 'warn',
+ lead: never ? 'No backup yet.' : `Last backup ${age(liveAge!)} ago.`,
+ text: ' No data changes, so you can still allow it.',
+ file: null,
+ main: 'allow',
+ // Without a backup command there is nothing to run, so only Allow and Deny.
+ secondaryBackup: b.state !== 'no_command',
+ busy: false,
+ note: plainNote,
+ };
+}
+
+/** Header verb per floor kind (design §6). */
+export function floorHeader(floor: ProdFloor, bot: string): string {
+ const what: Record<ProdFloor['kind'], string> = {
+ deploy: 'deploy',
+ deploy_migration: 'deploy a database change',
+ push_main: 'push to main',
+ force_push: 'force push',
+ delete_ref: 'delete a branch',
+ destructive: 'delete data',
+ prod_key: 'use a production key',
+ };
+ return `Production floor: ${bot} wants to ${what[floor.kind]}`;
+}
+
+export function floorSubline(floor: ProdFloor): string {
+ if (floor.kind === 'deploy_migration') return 'This deploy changes the database, so it counts as destructive: it needs a backup from the last 10 minutes first.';
+ if (floor.kind === 'destructive') return 'Destructive commands need a backup from the last 10 minutes first.';
+ if (floor.kind === 'deploy') return 'Dev mode is on, so deploys always ask you, even with approvals off.';
+ if (floor.kind === 'prod_key') return 'Dev mode is on, so a production key always asks you, even with approvals off.';
+ return 'Dev mode is on, so this always asks you, even with approvals off.';
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Findings: Fix it undo window and the dismiss flow (design §5.6)
+
+export const UNDO_MS = 10_000;
+
+/** Ms left to undo a Fix it, or 0. */
+export function undoLeft(f: DevFinding, now: number): number {
+ if (f.state !== 'sent' || !f.sent_at || f.task_id) return 0;
+ const at = Date.parse(f.sent_at);
+ return Number.isNaN(at) ? 0 : Math.max(0, at + UNDO_MS - now);
+}
+
+export const DISMISS_REASONS: { id: DismissReason; label: string }[] = [
+ { id: 'not_a_problem', label: 'Not a problem' },
+ { id: 'fine_here', label: 'Fine in this PR' },
+ { id: 'later', label: 'I’ll fix it later' },
+ { id: 'wrong', label: 'Wrong' },
+];
+
+export const reasonLabel = (r: DismissReason) => DISMISS_REASONS.find((x) => x.id === r)?.label ?? r;
+
+/** "Dismissed · Fine in this PR · you". `by` is "person" from the server (§3.6 item 4). */
+export function dismissedLine(f: DevFinding): string {
+ const d = f.dismissed;
+ if (!d) return 'Dismissed';
+ const by = !d.by || d.by === 'person' ? 'you' : d.by;
+ return `Dismissed · ${reasonLabel(d.reason)} · ${by}`;
+}
+
+/** The inline dismiss form's own state. */
+export interface DismissDraft {
+ open: boolean;
+ reason: DismissReason | null;
+ note: string;
+ sending: boolean;
+ error: string | null;
+}
+
+export type DismissEvent =
+ | { type: 'open' }
+ | { type: 'cancel' }
+ | { type: 'reason'; reason: DismissReason }
+ | { type: 'note'; note: string }
+ | { type: 'submit' }
+ | { type: 'failed'; error: string }
+ | { type: 'done' };
+
+export const closedDraft: DismissDraft = { open: false, reason: null, note: '', sending: false, error: null };
+
+export function dismissReducer(d: DismissDraft, ev: DismissEvent): DismissDraft {
+ switch (ev.type) {
+ case 'open':
+ return { ...closedDraft, open: true };
+ case 'cancel':
+ case 'done':
+ return closedDraft;
+ case 'reason':
+ return d.open && !d.sending ? { ...d, reason: ev.reason, error: null } : d;
+ case 'note':
+ return d.open && !d.sending ? { ...d, note: ev.note.slice(0, 500) } : d;
+ case 'submit':
+ // A reason is required; a second submit while one is in flight is ignored.
+ return d.open && d.reason && !d.sending ? { ...d, sending: true, error: null } : d;
+ case 'failed':
+ return { ...d, sending: false, error: ev.error };
+ }
+}
+
+
+/** "1 high, 1 medium, 1 low" over the findings that are not dismissed. */
+export function findingsSummary(findings: DevFinding[]): string {
+ const order = ['critical', 'high', 'medium', 'low'] as const;
+ return order
+ .map((s) => [s, findings.filter((f) => f.severity === s && f.state !== 'dismissed').length] as const)
+ .filter(([, n]) => n > 0)
+ .map(([s, n]) => `${n} ${s}`)
+ .join(', ');
+}
diff --git a/frontend/src/dev/types.ts b/frontend/src/dev/types.ts
new file mode 100644
index 00000000..62417860
--- /dev/null
+++ b/frontend/src/dev/types.ts
@@ -0,0 +1,431 @@
+// Dev mode card types (plan §3.4 plus the §3.6 amendments) and the props the Dev desk passes to the
+// renderers in components/dev/. Iris owns this file; Pixel's DevDesk.tsx mounts the renderers with these
+// props. The GET routes return `{...card, id, kind, status, created_at}` (impl/lin.md "Card").
+//
+// Every parse* below takes the route's raw JSON and returns a typed card, or null when the card is not
+// one the renderer can draw honestly (wrong kind, no PR number). The desk then shows the plain fallback
+// row (`CardFallback`). Strings are trimmed to a sane length and never rendered as HTML.
+
+export type CardStatus = 'pending' | 'ready' | 'failed' | 'stale';
+export type RiskLevel = 'low' | 'medium' | 'high';
+
+/** Who wrote a PR: a kwant bot (with its engine) or a person. */
+export interface DevPerson {
+ kind: 'bot' | 'person';
+ name: string;
+ engine: string | null;
+ model: string | null;
+}
+
+export interface DevRisk {
+ level: RiskLevel;
+ /** Always at least one reason on screen; the renderer adds "Small change, tests nearby" for low with none. */
+ reasons: string[];
+}
+
+export interface DevLinks {
+ pr: string | null;
+ commit: string | null;
+ ci: string | null;
+}
+
+interface CardBase {
+ id: string;
+ status: CardStatus;
+ created_at: string | null;
+ /** §3.6 item 9: a failed card says why and keeps its rule-based parts. */
+ error: string | null;
+}
+
+export interface LandedCard extends CardBase {
+ kind: 'landed';
+ pr: number;
+ sha: string;
+ merged_at: string | null;
+ merged_by: string | null;
+ written_by: DevPerson | null;
+ /** §3.6 item 12: null when no text was written; the headline is then the PR title. */
+ area: string | null;
+ headline: string;
+ for_you: string | null;
+ under_hood: { summary: string | null; files: { path: string; add: number; del: number }[] };
+ risk: DevRisk | null;
+ tests: { state: 'passed' | 'failed' | 'none' | 'unknown'; summary: string | null };
+ reviewed_by: string | null;
+ follow_ups: { text: string; ref: string | null }[];
+ /** The server's flag. The sticker is shown only when `showVerified` (dev/logic.ts) also agrees. */
+ verified: boolean;
+ links: DevLinks;
+ /** §3.6 item 11: "diff cut, N files not read". */
+ cut: string | null;
+ /** Optional one-line meta beside the chips, e.g. "redaction code · 249 lines". */
+ meta: string | null;
+}
+
+export type IntentState = 'ok' | 'missing' | 'extra';
+export type TamperKind = 'deleted_assert' | 'skip' | 'loosened' | 'snapshot' | 'coverage_drop';
+export type ScanState = 'pass' | 'hit' | 'not_run';
+export type Severity = 'critical' | 'high' | 'medium' | 'low';
+export type DismissReason = 'not_a_problem' | 'fine_here' | 'later' | 'wrong';
+
+export interface DevFinding {
+ id: string;
+ severity: Severity;
+ title: string;
+ file: string | null;
+ line: number | null;
+ detail: string | null;
+ fix: string | null;
+ source: 'review' | 'gitleaks' | 'packages' | 'tamper';
+ state: 'open' | 'sent' | 'dismissed';
+ sent_at: string | null;
+ /** §3.6 item 4. */
+ sent_to: string | null;
+ task_id: string | null;
+ send_error: string | null;
+ dismissed: { reason: DismissReason; note: string; by: string; at: string | null } | null;
+}
+
+export interface TamperFlag {
+ kind: TamperKind;
+ file: string;
+ line: number | null;
+ excerpt: string;
+ why: string;
+}
+
+export interface ReviewCard extends CardBase {
+ kind: 'review';
+ pr: number;
+ title: string;
+ branch: string | null;
+ base: string | null;
+ draft: boolean;
+ author: DevPerson | null;
+ /** §3.6 item 10: null when no second bot could review; `note` then says so. */
+ /** Round 3 (vega.md): `id` is the reviewing bot's id; the server's Verified compares it with the author's. */
+ reviewer: { id: string | null; name: string; engine: string | null; model: string | null } | null;
+ note: string | null;
+ same_engine: boolean;
+ risk: DevRisk | null;
+ intent: { source: string; asked: string; rows: { state: IntentState; text: string }[]; none: boolean } | null;
+ /** `unread`: files GitHub sent no diff for, so nothing in them was checked (round 3, V-T5). */
+ tamper: { flags: TamperFlag[]; unread: string[] };
+ security: {
+ secrets: { state: ScanState; count: number };
+ packages: { state: ScanState; count: number };
+ };
+ findings: DevFinding[];
+ cut: string | null;
+ links: DevLinks;
+}
+
+export interface ReleaseNotesCard extends CardBase {
+ kind: 'release_notes';
+ since_tag: string | null;
+ markdown: string | null;
+ whats_new: string | null;
+}
+
+export type DevCard = LandedCard | ReviewCard | ReleaseNotesCard;
+
+/** `GET /api/spaces/:id/dev/landed` → rollup. */
+export interface DevRollup {
+ since: string | null;
+ until: string | null;
+ count: number;
+ needs_you: number;
+ main_green: boolean | null;
+ areas: { area: string; count: number; first_headline: string }[];
+}
+
+// ---- Production floor (approval `details.prod_floor`, impl/lin.md) ----
+
+export type FloorKind = 'push_main' | 'force_push' | 'delete_ref' | 'deploy' | 'deploy_migration' | 'destructive' | 'prod_key';
+export type BackupState = 'fresh' | 'old' | 'none' | 'no_data' | 'no_command' | 'taking' | 'failed';
+
+export interface FloorBackup {
+ state: BackupState;
+ age_s: number | null;
+ bytes: number | null;
+ path: string | null;
+ error: string | null;
+ /** Only while taking, when the server reports it. */
+ percent?: number | null;
+}
+
+export interface ProdFloor {
+ kind: FloorKind;
+ why: string;
+ blast: [string, string][];
+ needs_backup: boolean;
+ space_id: string | null;
+ backup: FloorBackup;
+}
+
+/** `POST /api/spaces/:id/dev/backup`. */
+export interface BackupResult {
+ id: string | null;
+ ok: boolean;
+ path: string | null;
+ bytes: number | null;
+ taken_at: string | null;
+ error: string | null;
+}
+
+// ---- Props (agreed with Pixel through this file) ----
+
+export type FindingAction = { action: 'fix' } | { action: 'undo_fix' } | { action: 'dismiss'; reason: DismissReason; note?: string };
+
+export interface RollupProps {
+ rollup: DevRollup;
+ last_tag: string | null;
+ /** For the empty state: "Last merge: #290, 19:26." The newest landed card, if any. */
+ last_merge: { pr: number; merged_at: string | null } | null;
+ /** The watched branch: "3 changes landed on main". Defaults to "main". */
+ branch?: string;
+ /** Areas whose tile gets the warn border: `needsYouAreas(cards)` from dev/logic.ts. */
+ needsYouAreas?: string[];
+ onDraftNotes: () => void;
+ onMarkSeen: () => void;
+ /** True while a release-notes draft is being written (the button waits). */
+ drafting?: boolean;
+ /** True while the mark-seen POST is in flight (the button waits, like `drafting`). */
+ marking?: boolean;
+}
+
+export interface LandedListProps {
+ cards: LandedCard[];
+ /** Review cards of the same space, for the Verified rule (§3.6 item 14). */
+ reviews: ReviewCard[];
+ /** Epoch ms; tests and shots pass a fixed clock. */
+ now?: number;
+ /** Opens the PR's review card ("1 finding open in the review · Open review"); the link hides without it. */
+ onOpenReview?: (pr: number) => void;
+}
+
+export interface ReviewCardProps {
+ card: ReviewCard;
+ /** Sends a finding action (`POST /api/dev/cards/:id/findings/:fid`) and resolves with the new card, or throws. */
+ onFinding: (cardId: string, findingId: string, action: FindingAction) => Promise<ReviewCard>;
+ /** Shows the "Sample PR" chip (design §5: the #294 sample). */
+ sample?: boolean;
+ now?: number;
+}
+
+export interface ReleaseNotesSheetProps {
+ card: ReleaseNotesCard;
+ /** Show "Save to Notion" only when Notion is connected; otherwise pass undefined and it's hidden. */
+ onSaveToNotion?: (markdown: string) => Promise<void>;
+ onDiscard: () => void;
+ onClose: () => void;
+}
+
+// ---- Parsing ----
+
+const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
+const str = (v: unknown, max = 2000): string | null => (typeof v === 'string' && v.trim() !== '' ? v.slice(0, max) : null);
+const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+const oneOf = <T extends string>(v: unknown, all: readonly T[], fallback: T): T => (all.includes(v as T) ? (v as T) : fallback);
+const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
+
+const STATUSES = ['pending', 'ready', 'failed', 'stale'] as const;
+const LEVELS = ['low', 'medium', 'high'] as const;
+
+function base(raw: Record<string, unknown>): CardBase {
+ return {
+ id: str(raw.id, 200) ?? '',
+ status: oneOf(raw.status, STATUSES, 'ready'),
+ created_at: str(raw.created_at, 64),
+ error: str(raw.error, 400),
+ };
+}
+
+function person(v: unknown): DevPerson | null {
+ if (!isObj(v)) return null;
+ const name = str(v.name, 80);
+ if (!name) return null;
+ return { kind: v.kind === 'person' ? 'person' : 'bot', name, engine: str(v.engine, 40), model: str(v.model, 80) };
+}
+
+function risk(v: unknown): DevRisk | null {
+ if (!isObj(v) || !LEVELS.includes(v.level as RiskLevel)) return null;
+ return { level: v.level as RiskLevel, reasons: arr(v.reasons).map((r) => str(r, 120)).filter((r): r is string => !!r) };
+}
+
+function links(v: unknown): DevLinks {
+ // Only https links reach an href (lin.md: links are https-only server-side too).
+ const https = (u: unknown) => {
+ const s = str(u, 1000);
+ return s && /^https:\/\//.test(s) ? s : null;
+ };
+ const o = isObj(v) ? v : {};
+ return { pr: https(o.pr), commit: https(o.commit), ci: https(o.ci) };
+}
+
+export function parseLanded(raw: unknown): LandedCard | null {
+ if (!isObj(raw) || raw.kind !== 'landed') return null;
+ const pr = num(raw.pr);
+ if (pr === null) return null;
+ const uh = isObj(raw.under_hood) ? raw.under_hood : {};
+ const tests = isObj(raw.tests) ? raw.tests : {};
+ return {
+ ...base(raw),
+ kind: 'landed',
+ pr,
+ sha: (str(raw.sha, 40) ?? '').slice(0, 7),
+ merged_at: str(raw.merged_at, 64),
+ merged_by: str(raw.merged_by, 80),
+ written_by: person(raw.written_by),
+ area: str(raw.area, 60),
+ headline: str(raw.headline, 200) ?? str(raw.title, 200) ?? `PR #${pr}`,
+ for_you: str(raw.for_you, 600),
+ under_hood: {
+ summary: str(uh.summary, 600),
+ files: arr(uh.files)
+ .filter(isObj)
+ .map((f) => ({ path: str(f.path, 400) ?? '', add: num(f.add) ?? 0, del: num(f.del) ?? 0 }))
+ .filter((f) => f.path),
+ },
+ risk: risk(raw.risk),
+ tests: { state: oneOf(tests.state, ['passed', 'failed', 'none', 'unknown'] as const, 'unknown'), summary: str(tests.summary, 120) },
+ reviewed_by: str(raw.reviewed_by, 80),
+ follow_ups: arr(raw.follow_ups)
+ .filter(isObj)
+ .map((f) => ({ text: str(f.text, 400) ?? '', ref: str(f.ref, 40) }))
+ .filter((f) => f.text),
+ verified: raw.verified === true,
+ links: links(raw.links),
+ cut: str(raw.cut, 120),
+ meta: str(raw.meta, 80),
+ };
+}
+
+function finding(v: unknown): DevFinding | null {
+ if (!isObj(v)) return null;
+ const id = str(v.id, 80);
+ const title = str(v.title, 200);
+ if (!id || !title) return null;
+ const d = isObj(v.dismissed) ? v.dismissed : null;
+ return {
+ id,
+ title,
+ severity: oneOf(v.severity, ['critical', 'high', 'medium', 'low'] as const, 'low'),
+ file: str(v.file, 400),
+ line: num(v.line),
+ detail: str(v.detail, 1200),
+ fix: str(v.fix, 600),
+ source: oneOf(v.source, ['review', 'gitleaks', 'packages', 'tamper'] as const, 'review'),
+ state: oneOf(v.state, ['open', 'sent', 'dismissed'] as const, 'open'),
+ sent_at: str(v.sent_at, 64),
+ sent_to: str(v.sent_to, 80),
+ task_id: str(v.task_id, 80),
+ send_error: str(v.send_error, 200),
+ dismissed: d
+ ? { reason: oneOf(d.reason, ['not_a_problem', 'fine_here', 'later', 'wrong'] as const, 'not_a_problem'), note: str(d.note, 500) ?? '', by: str(d.by, 80) ?? 'person', at: str(d.at, 64) }
+ : null,
+ };
+}
+
+const scan = (v: unknown) => {
+ const o = isObj(v) ? v : {};
+ return { state: oneOf(o.state, ['pass', 'hit', 'not_run'] as const, 'not_run'), count: num(o.count) ?? 0 };
+};
+
+export function parseReview(raw: unknown): ReviewCard | null {
+ if (!isObj(raw) || raw.kind !== 'review') return null;
+ const pr = num(raw.pr);
+ if (pr === null) return null;
+ const intent = isObj(raw.intent) ? raw.intent : null;
+ const rv = isObj(raw.reviewer) ? raw.reviewer : null;
+ const sec = isObj(raw.security) ? raw.security : {};
+ return {
+ ...base(raw),
+ kind: 'review',
+ pr,
+ title: str(raw.title, 300) ?? `PR #${pr}`,
+ branch: str(raw.branch, 200),
+ base: str(raw.base, 200),
+ draft: raw.draft === true,
+ author: person(raw.author),
+ reviewer: rv && str(rv.name, 80) ? { id: str(rv.id, 120), name: str(rv.name, 80)!, engine: str(rv.engine, 40), model: str(rv.model, 80) } : null,
+ note: str(raw.note, 200),
+ same_engine: raw.same_engine === true,
+ risk: risk(raw.risk),
+ intent: intent
+ ? {
+ source: str(intent.source, 40) ?? 'pr',
+ asked: str(intent.asked, 600) ?? '',
+ none: intent.none === true,
+ rows: arr(intent.rows)
+ .filter(isObj)
+ .map((r) => ({ state: oneOf(r.state, ['ok', 'missing', 'extra'] as const, 'ok'), text: str(r.text, 300) ?? '' }))
+ .filter((r) => r.text),
+ }
+ : null,
+ tamper: {
+ flags: arr(isObj(raw.tamper) ? raw.tamper.flags : [])
+ .filter(isObj)
+ .map((f) => ({
+ kind: oneOf(f.kind, ['deleted_assert', 'skip', 'loosened', 'snapshot', 'coverage_drop'] as const, 'loosened'),
+ file: str(f.file, 400) ?? '',
+ line: num(f.line),
+ excerpt: str(f.excerpt, 2000) ?? '',
+ why: str(f.why, 400) ?? '',
+ })),
+ unread: arr(isObj(raw.tamper) ? raw.tamper.unread : [])
+ .map((p) => str(p, 400))
+ .filter((p): p is string => !!p),
+ },
+ security: { secrets: scan(sec.secrets), packages: scan(sec.packages) },
+ findings: arr(raw.findings).map(finding).filter((f): f is DevFinding => !!f),
+ cut: str(raw.cut, 120),
+ links: links(raw.links),
+ };
+}
+
+export function parseReleaseNotes(raw: unknown): ReleaseNotesCard | null {
+ if (!isObj(raw) || raw.kind !== 'release_notes') return null;
+ return { ...base(raw), kind: 'release_notes', since_tag: str(raw.since_tag, 80), markdown: str(raw.markdown, 20000), whats_new: str(raw.whats_new, 2000) };
+}
+
+const FLOOR_KINDS = ['push_main', 'force_push', 'delete_ref', 'deploy', 'deploy_migration', 'destructive', 'prod_key'] as const;
+const BACKUP_STATES = ['fresh', 'old', 'none', 'no_data', 'no_command', 'taking', 'failed'] as const;
+
+export function parseBackup(v: unknown): FloorBackup {
+ const b = isObj(v) ? v : {};
+ return {
+ state: oneOf(b.state, BACKUP_STATES, 'none'),
+ age_s: num(b.age_s),
+ bytes: num(b.bytes),
+ path: str(b.path, 400),
+ error: str(b.error, 200),
+ percent: num(b.percent),
+ };
+}
+
+/** `details.prod_floor` of an approval, or null when the card is not a production-floor card. */
+export function parseProdFloor(details: unknown): ProdFloor | null {
+ if (!isObj(details) || !isObj(details.prod_floor)) return null;
+ const p = details.prod_floor;
+ if (!FLOOR_KINDS.includes(p.kind as FloorKind)) return null;
+ const blast = arr(p.blast)
+ .filter((r): r is unknown[] => Array.isArray(r) && r.length === 2)
+ .map((r) => [str(r[0], 40), str(r[1], 400)] as const)
+ .filter((r): r is readonly [string, string] => !!r[0] && !!r[1])
+ .map((r) => [r[0], r[1]] as [string, string]);
+ return {
+ kind: p.kind as FloorKind,
+ why: str(p.why, 300) ?? '',
+ blast,
+ // Destructive and migration deploys always need one, whatever the payload says (§3.5).
+ needs_backup: p.needs_backup === true || p.kind === 'destructive' || p.kind === 'deploy_migration',
+ space_id: str(p.space_id, 80),
+ backup: parseBackup(p.backup),
+ };
+}
+
+export function parseBackupResult(v: unknown): BackupResult {
+ const b = isObj(v) ? v : {};
+ return { id: str(b.id, 80), ok: b.ok === true, path: str(b.path, 400), bytes: num(b.bytes), taken_at: str(b.taken_at, 64), error: str(b.error, 200) };
+}
diff --git a/frontend/tests/devCards.test.mjs b/frontend/tests/devCards.test.mjs
new file mode 100644
index 00000000..2a25e967
--- /dev/null
+++ b/frontend/tests/devCards.test.mjs
@@ -0,0 +1,623 @@
+// Dev mode renderers (0.7, Iris): the Verified sticker rules, the production-floor backup state machine
+// (all 7 cases), the 500 ms Allow guard and the findings Dismiss flow, plus parse and render checks.
+process.env.TZ = 'UTC';
+
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
+
+const m = await loadBundled(`
+ export * from './src/dev/types';
+ export * from './src/dev/logic';
+ export * as fx from './src/dev/fixtures';
+ export { LandedCard, LandedList } from './src/components/dev/LandedCard';
+ export { Rollup, rollupTitle, rollupTiles } from './src/components/dev/Rollup';
+ export { ReviewCard } from './src/components/dev/ReviewCard';
+ export { ReleaseNotesSheet } from './src/components/dev/ReleaseNotesSheet';
+ export { ProdFloorCard } from './src/components/dev/ProdFloorCard';
+ export { ModernApprovalCard } from './src/components/ModernApprovalCard';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { createRoot } from 'react-dom/client';
+ export { createElement } from 'react';
+`);
+const { fx } = m;
+const h = m.createElement;
+const html = (C, props) => m.renderToStaticMarkup(h(C, props));
+const NOW = fx.FIXTURE_NOW;
+
+const landed = (raw, over = {}) => ({ ...m.parseLanded(raw), ...over });
+const review = (raw, over = {}) => ({ ...m.parseReview(raw), ...over });
+
+// ---------------------------------------------------------------------------------------------------
+// DOM helpers
+
+const mounted = new Set();
+afterEach(() => {
+ for (const u of mounted) u();
+ document.body.replaceChildren();
+});
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mount = async (C, props) => {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ root.render(h(C, props));
+ await settle();
+ const u = () => {
+ if (!mounted.delete(u)) return;
+ root.unmount();
+ host.remove();
+ };
+ mounted.add(u);
+ return host;
+};
+const button = (host, text) => [...host.querySelectorAll('button')].find((b) => b.textContent.replace(/\s+/g, ' ').trim().startsWith(text));
+const click = async (el) => {
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+
+// ---------------------------------------------------------------------------------------------------
+// Parsing and null handling (§3.6 items 10, 12, 13)
+
+test('parsers keep the §3.6 nulls and reject other shapes', () => {
+ const c = m.parseLanded(fx.LANDED_NO_TEXT);
+ assert.equal(c.headline, 'Bump vite to 6.4.4', 'headline falls back to the PR title');
+ assert.equal(c.area, null);
+ assert.equal(c.for_you, null);
+ assert.equal(c.under_hood.summary, null);
+ assert.equal(c.status, 'failed');
+ assert.match(c.error, /daily cap/);
+ assert.equal(c.cut, 'diff cut, 2 files not read');
+ const r = m.parseReview(fx.REVIEW_NO_REVIEWER);
+ assert.equal(r.reviewer, null);
+ assert.match(r.note, /No reviewer/);
+ assert.equal(m.parseLanded({ kind: 'review', pr: 1 }), null);
+ assert.equal(m.parseLanded({ kind: 'landed' }), null, 'no PR number');
+ assert.equal(m.parseReview(null), null);
+ const odd = m.parseLanded({ ...fx.LANDED_289, links: { pr: 'javascript:alert(1)', commit: 'http://x', ci: null } });
+ assert.equal(odd.links.pr, null, 'only https links');
+ assert.equal(odd.links.commit, null);
+ const f = m.parseReview(fx.REVIEW_294).findings.find((x) => x.id === 'f2');
+ assert.equal(f.sent_to, 'Pixel');
+ assert.equal(f.task_id, null);
+});
+
+test('the floor parser forces needs_backup for destructive and migration deploys and drops bad blast rows', () => {
+ const d = m.parseProdFloor({ prod_floor: { kind: 'destructive', needs_backup: false, blast: [['Where', 'x'], ['bad'], [1, 2]], backup: {} } });
+ assert.equal(d.needs_backup, true);
+ assert.deepEqual(d.blast, [['Where', 'x']]);
+ assert.equal(d.backup.state, 'none');
+ assert.equal(m.parseProdFloor({ prod_floor: { kind: 'deploy_migration', backup: {} } }).needs_backup, true);
+ assert.equal(m.parseProdFloor({ prod_floor: { kind: 'launch_rockets' } }), null);
+ assert.equal(m.parseProdFloor({ source: 'local_shell' }), null);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Verified sticker (§3.6 item 14)
+
+test('Verified: CI green + reviewed by someone else + nothing open', () => {
+ const ok = landed(fx.LANDED_289);
+ assert.equal(m.showVerified(ok), true);
+ assert.equal(m.showVerified({ ...ok, verified: false }), false, 'the server has to agree');
+ assert.equal(m.showVerified({ ...ok, tests: { state: 'failed', summary: null } }), false, 'red CI');
+ assert.equal(m.showVerified({ ...ok, tests: { state: 'none', summary: null } }), false, 'no CI');
+ assert.equal(m.showVerified({ ...ok, reviewed_by: null }), false, 'no review');
+ assert.equal(m.showVerified({ ...ok, reviewed_by: 'ada ' }), false, 'reviewed by its own author (any case)');
+ assert.equal(m.showVerified(landed(fx.LANDED_288, { verified: true })), false, 'an open follow-up');
+ assert.equal(m.showVerified({ ...ok, status: 'stale' }), false);
+ assert.equal(m.showVerified({ ...ok, status: 'pending' }), false);
+});
+
+test('Verified: the PR review card can only take it away', () => {
+ const ok = landed(fx.LANDED_289);
+ const rv = review(fx.REVIEW_289);
+ assert.equal(m.showVerified(ok, [rv]), true);
+ const open = { ...rv, findings: [{ ...review(fx.REVIEW_294).findings[0] }] };
+ assert.equal(m.showVerified(ok, [open]), false, 'an open finding');
+ assert.equal(m.showVerified(ok, [{ ...open, findings: open.findings.map((f) => ({ ...f, state: 'dismissed' })) }]), true, 'dismissed is closed');
+ assert.equal(m.showVerified(ok, [{ ...open, findings: open.findings.map((f) => ({ ...f, state: 'sent' })) }]), false, 'sent as a task is still open (item 14)');
+ assert.equal(m.showVerified(ok, [{ ...rv, reviewer: null }]), false, 'no reviewer');
+ assert.equal(m.showVerified(ok, [{ ...rv, reviewer: { name: 'Ada', engine: null, model: null } }]), false, 'reviewer is the author');
+ assert.equal(m.showVerified(ok, [{ ...rv, pr: 999, reviewer: null }]), true, 'another PR’s review does not count');
+});
+
+test('the landed card shows the holo sticker only when Verified', () => {
+ const yes = html(m.LandedCard, { card: landed(fx.LANDED_289) });
+ assert.match(yes, /data-verified="true"/);
+ assert.match(yes, /kw-sticker[^"]*holo|holo/);
+ assert.match(yes, />Verified</);
+ const no = html(m.LandedCard, { card: landed(fx.LANDED_288) });
+ assert.doesNotMatch(no, /data-verified/);
+ assert.doesNotMatch(no, />Verified</);
+ assert.match(no, /1 follow-up open:/);
+ assert.match(no, /#288 N3/);
+});
+
+test('the landed card: plain words, the details fold, a failed card and day separators', () => {
+ const c = html(m.LandedCard, { card: landed(fx.LANDED_288) });
+ assert.match(c, /What changes for you/);
+ assert.match(c, /<details/);
+ assert.match(c, /Under the hood · 4 files, \+249 −15/);
+ assert.match(c, /Merged 18:48 by/);
+ assert.match(c, /Pixel<\/span><\/span><span>\(bot · Claude Sonnet\)/);
+ const f = html(m.LandedCard, { card: landed(fx.LANDED_NO_TEXT) });
+ assert.match(f, /Bump vite to 6\.4\.4/);
+ assert.match(f, /No plain-words text for this change/);
+ assert.doesNotMatch(f, /What changes for you/);
+ assert.match(f, /diff cut, 2 files not read/);
+ assert.doesNotMatch(f, /class="kw-chip">/, 'no area chip when area is null');
+ const list = html(m.LandedList, { cards: [landed(fx.LANDED_303), landed(fx.LANDED_288), landed(fx.LANDED_NO_TEXT)], reviews: [], now: NOW });
+ const days = [...list.matchAll(/<section aria-label="([^"]+)"/g)].map((x) => x[1]);
+ assert.deepEqual(days, ['Today', 'Yesterday', 'Tue 3 Nov']);
+});
+
+test('roll-up: title, needs-you tiles, +N more, the empty state, no routine link', () => {
+ assert.equal(m.rollupTitle(3, 0, 'main'), '3 changes landed on main. Nothing needs you.');
+ assert.equal(m.rollupTitle(1, 1, 'main'), '1 change landed on main. 1 needs you.');
+ const A = (...xs) => xs.map((area) => ({ area }));
+ assert.deepEqual(m.rollupTiles(A('a', 'b', 'c', 'd')), { shown: A('a', 'b', 'c', 'd'), more: 0 });
+ assert.deepEqual(m.rollupTiles(A('a', 'b', 'c', 'd', 'e', 'f')), { shown: A('a', 'b'), more: 4 });
+ const base = { last_tag: 'mac-v0.6.10', last_merge: null, branch: 'main', onDraftNotes() {}, onMarkSeen() {} };
+ const r = html(m.Rollup, { ...base, rollup: fx.LANDED_ROUTE.rollup, needsYouAreas: ['Live activity'] });
+ assert.match(r, /data-dev-rollup="needs-you"/);
+ assert.match(r, /data-area="Live activity" data-needs-you="true"/);
+ assert.match(r, /main is green/);
+ assert.doesNotMatch(r, /every morning/i);
+ assert.match(html(m.Rollup, { ...base, rollup: fx.ROLLUP_MANY }), /\+4 more areas/);
+ assert.match(html(m.Rollup, { ...base, rollup: fx.ROLLUP_MANY }), /main is red/);
+ const e = html(m.Rollup, { ...base, rollup: fx.ROLLUP_EMPTY, last_merge: { pr: 290, merged_at: '2026-11-04T19:26:00Z' } });
+ assert.match(e, /Nothing landed since you last looked\. Last merge: #290, 19:26\./);
+ assert.deepEqual(m.needsYouAreas(fx.LANDED_ROUTE.cards.map((c) => m.parseLanded(c))), ['Chat', 'Live activity']);
+
+ const { branch: _b, ...noBranch } = base;
+ assert.match(html(m.Rollup, { ...noBranch, rollup: fx.ROLLUP_QUIET }), /landed on main\./, 'branch defaults to main');
+ const waiting = html(m.Rollup, { ...base, rollup: fx.ROLLUP_QUIET, marking: true });
+ assert.match(waiting, /<button[^>]*disabled=""[^>]*aria-busy="true"[^>]*>Marking…<\/button>/, 'Mark all seen waits while marking');
+ assert.match(html(m.Rollup, { ...base, rollup: fx.ROLLUP_QUIET }), />Mark all seen<\/button>/);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Production floor: the backup state machine (design §6, all 7 cases)
+
+const floorOf = (approval) => m.parseProdFloor(approval.details);
+const viewOf = (approval, ui) => {
+ const f = floorOf(approval);
+ return m.floorView(f, ui ?? m.initialFloorUi(f), NOW, NOW);
+};
+
+test('backup case 1: a fresh backup lets Allow through', () => {
+ const v = viewOf(fx.FLOOR_DEPLOY_FRESH);
+ assert.equal(v.case, 'fresh');
+ assert.equal(v.main, 'allow');
+ assert.equal(v.secondaryBackup, false);
+ assert.equal(v.lead, 'Backup taken 14 s ago');
+ assert.equal(v.text, ' · 412 MB');
+ assert.equal(v.file, 'backup-2026-11-04-pre-4049325.tgz');
+});
+
+test('backup case 2: a plain deploy with an old backup offers Allow and Back up first', () => {
+ const v = viewOf(fx.FLOOR_DEPLOY_OLD);
+ assert.equal(v.case, 'old_plain');
+ assert.equal(v.tone, 'warn');
+ assert.equal(v.main, 'allow');
+ assert.equal(v.secondaryBackup, true);
+ assert.equal(`${v.lead}${v.text}`, 'Last backup 3 h ago. No data changes, so you can still allow it.');
+});
+
+test('backup case 3: just taken via Back up first, then it ages and goes old after 10 minutes', () => {
+ const f = floorOf(fx.FLOOR_MIGRATION);
+ let ui = m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' });
+ ui = m.floorReducer(ui, { type: 'backup_done', result: { id: 'b', ok: true, path: '/x/b.tgz', bytes: 412_000_000, taken_at: null, error: null }, now: NOW });
+ let v = m.floorView(f, ui, NOW + 3000, NOW);
+ assert.equal(v.case, 'just_taken');
+ assert.equal(v.lead, 'Backup taken 3 s ago');
+ assert.equal(v.main, 'allow');
+ v = m.floorView(f, ui, NOW + 11 * 60_000, NOW);
+ assert.equal(v.case, 'blocked', 'stale again after 10 minutes');
+ assert.equal(v.main, 'backup');
+});
+
+test('backup case 4: a site with no data has nothing to back up', () => {
+ const v = viewOf(fx.FLOOR_PAGES);
+ assert.equal(v.case, 'no_data');
+ assert.equal(v.tone, 'neutral');
+ assert.equal(v.main, 'allow');
+ assert.equal(v.text, 'Nothing to back up: this site has no database or uploads.');
+});
+
+test('backup case 5: destructive or migration with no fresh backup replaces Allow with Back up first', () => {
+ for (const [ap, text] of [[fx.FLOOR_DESTRUCTIVE, ' The last one is 3 h old.'], [fx.FLOOR_MIGRATION, ' The last one is 41 min old.']]) {
+ const v = viewOf(ap);
+ assert.equal(v.case, 'blocked');
+ assert.equal(v.tone, 'bad');
+ assert.equal(v.main, 'backup');
+ assert.equal(v.lead, 'No fresh backup.');
+ assert.equal(v.text, text);
+ assert.equal(v.note, 'Nothing runs without a fresh backup.');
+ }
+ const never = m.floorView({ ...floorOf(fx.FLOOR_DESTRUCTIVE), backup: { state: 'none', age_s: null, bytes: null, path: null, error: null } }, { phase: 'idle', taken: null, error: null, armedAt: null }, NOW);
+ assert.equal(never.lead, 'No backup yet.');
+ const nc = viewOf(fx.FLOOR_NO_COMMAND);
+ assert.equal(nc.case, 'no_command');
+ assert.equal(nc.main, 'none', 'nothing to run, so no main button');
+});
+
+test('backup case 6: taking disables every button and shows a percent only when the server sends one', () => {
+ const f = floorOf(fx.FLOOR_DESTRUCTIVE);
+ const ui = m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' });
+ assert.equal(m.floorReducer(ui, { type: 'backup_start' }), ui, 'a second press changes nothing');
+ let v = m.floorView(f, ui, NOW);
+ assert.equal(v.case, 'taking');
+ assert.equal(v.busy, true);
+ assert.equal(v.text, 'Taking a backup…');
+ v = m.floorView({ ...f, backup: { ...f.backup, state: 'taking', percent: 38 } }, ui, NOW);
+ assert.equal(v.text, 'Taking a backup… 38 %');
+});
+
+test('backup case 7: a failed backup never shows Allow, only Try the backup again', () => {
+ const v = viewOf(fx.FLOOR_FAILED);
+ assert.equal(v.case, 'failed');
+ assert.equal(`${v.lead}${v.text}`, 'Backup failed: disk full.');
+ assert.equal(v.main, 'retry');
+ const f = floorOf(fx.FLOOR_DESTRUCTIVE);
+ let ui = m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' });
+ ui = m.floorReducer(ui, { type: 'backup_done', result: { id: null, ok: false, path: null, bytes: null, taken_at: null, error: 'exit 1: no space' }, now: NOW });
+ assert.equal(ui.phase, 'failed');
+ assert.equal(ui.armedAt, null);
+ assert.equal(m.floorView(f, ui, NOW).main, 'retry');
+ ui = m.floorReducer(m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' }), { type: 'backup_error', error: 'A backup is running already' });
+ assert.equal(m.floorView(f, ui, NOW).text, ' A backup is running already.');
+});
+
+test('the floor card never offers "always allow", in any case', () => {
+ for (const ap of [fx.FLOOR_DEPLOY_FRESH, fx.FLOOR_DESTRUCTIVE, fx.FLOOR_MIGRATION, fx.FLOOR_DEPLOY_OLD, fx.FLOOR_PAGES, fx.FLOOR_NO_COMMAND, fx.FLOOR_FAILED]) {
+ const out = html(m.ModernApprovalCard, { approval: ap, onResolve() {} });
+ assert.match(out, /data-prod-floor=/);
+ assert.doesNotMatch(out, /Always Allow|Always this session/);
+ assert.match(out, /Production floor: /);
+ }
+ const fresh = html(m.ModernApprovalCard, { approval: fx.FLOOR_DEPLOY_FRESH, onResolve() {} });
+ assert.match(fresh, /Production floor: Pixel wants to deploy/);
+ assert.match(fresh, /Allow this deploy/);
+ assert.match(fresh, /<dt[^>]*>Downtime<\/dt>/);
+ assert.match(fresh, /aria-live="polite"/);
+ const mig = html(m.ModernApprovalCard, { approval: fx.FLOOR_MIGRATION, onResolve() {} });
+ assert.match(mig, /wants to deploy a database change/);
+ assert.doesNotMatch(mig, /Allow this deploy/, 'blocked: Allow is replaced');
+ assert.match(mig, /Back up first/);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// The 500 ms Allow guard
+
+test('allowReady: the Allow that replaced Back up first ignores its first 500 ms', () => {
+ const f = floorOf(fx.FLOOR_DESTRUCTIVE);
+ assert.equal(m.allowReady(m.initialFloorUi(f), NOW), true, 'an Allow that was there from the start is not guarded');
+ let ui = m.floorReducer(m.initialFloorUi(f), { type: 'backup_start' });
+ ui = m.floorReducer(ui, { type: 'backup_done', result: { id: 'b', ok: true, path: null, bytes: 1, taken_at: null, error: null }, now: NOW });
+ assert.equal(ui.armedAt, NOW);
+ assert.equal(m.allowReady(ui, NOW), false);
+ assert.equal(m.allowReady(ui, NOW + 499), false);
+ assert.equal(m.allowReady(ui, NOW + 500), true);
+});
+
+test('Back up first turns into Allow in place; a double press cannot run the command', async () => {
+ const realNow = Date.now;
+ let clock = NOW;
+ Date.now = () => clock;
+ try {
+ const calls = [];
+ let release;
+ const backupDone = new Promise((r) => (release = r));
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_DESTRUCTIVE,
+ onResolve: (id, d) => calls.push([id, d]),
+ onBackup: async () => {
+ await backupDone;
+ return { id: 'b1', ok: true, path: '/home/demo/backups/b1.tgz', bytes: 412_000_000, taken_at: null, error: null };
+ },
+ });
+ const main = host.querySelector('[data-floor-main]');
+ assert.equal(main.dataset.floorMain, 'backup');
+ assert.equal(main.textContent.trim(), 'Back up first');
+ await click(main);
+ assert.equal(host.querySelector('[data-backup-row]').dataset.backupRow, 'taking');
+ assert.equal(main.getAttribute('aria-disabled'), 'true', 'the main button waits');
+ assert.equal(main.hasAttribute('disabled'), false, 'and is never disabled, so it keeps focus (B2)');
+ assert.ok([...host.querySelectorAll('button')].filter((b) => b !== main).every((b) => b.disabled), 'every other button waits');
+ await click(main);
+ assert.deepEqual(calls, [], 'a press while busy does nothing');
+ release();
+ await settle();
+ const after = host.querySelector('[data-floor-main]');
+ assert.equal(after, main, 'the same element, changed in place');
+ assert.equal(after.dataset.floorMain, 'allow');
+ assert.equal(after.textContent.trim(), 'Allow');
+ assert.equal(host.querySelector('[data-backup-row]').dataset.backupRow, 'just_taken');
+ await click(after);
+ clock += 300;
+ await click(after);
+ assert.deepEqual(calls, [], 'presses in the first 500 ms are ignored');
+ clock += 250;
+ await click(after);
+ assert.deepEqual(calls, [['ap_2', 'allow_once']]);
+ } finally {
+ Date.now = realNow;
+ }
+});
+
+test('a failed backup from the card shows the error and Try the backup again', async () => {
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_MIGRATION,
+ onResolve() {},
+ onBackup: async () => {
+ throw new Error('Set a backup command in Dev mode settings');
+ },
+ });
+ await click(host.querySelector('[data-floor-main]'));
+ assert.equal(host.querySelector('[data-backup-row]').dataset.backupRow, 'failed');
+ assert.match(host.querySelector('[data-backup-row]').textContent, /Backup failed: Set a backup command in Dev mode settings\./);
+ assert.equal(host.querySelector('[data-floor-main]').textContent.trim(), 'Try the backup again');
+ assert.ok(!button(host, 'Allow'), 'Allow never appears after a failure');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Findings: Fix it, Undo and the Dismiss flow
+
+test('dismissReducer: a reason is required, a double submit is ignored, cancel resets', () => {
+ let d = m.dismissReducer(m.closedDraft, { type: 'open' });
+ assert.equal(d.open, true);
+ assert.equal(m.dismissReducer(d, { type: 'submit' }), d, 'no reason, no submit');
+ d = m.dismissReducer(d, { type: 'reason', reason: 'fine_here' });
+ d = m.dismissReducer(d, { type: 'note', note: 'x'.repeat(600) });
+ assert.equal(d.note.length, 500);
+ d = m.dismissReducer(d, { type: 'submit' });
+ assert.equal(d.sending, true);
+ assert.equal(m.dismissReducer(d, { type: 'submit' }), d, 'second submit ignored');
+ assert.equal(m.dismissReducer(d, { type: 'reason', reason: 'wrong' }), d, 'locked while sending');
+ d = m.dismissReducer(d, { type: 'failed', error: 'offline' });
+ assert.equal(d.sending, false);
+ assert.equal(d.error, 'offline');
+ assert.equal(d.reason, 'fine_here', 'the choice survives a failure');
+ assert.deepEqual(m.dismissReducer(d, { type: 'cancel' }), m.closedDraft);
+});
+
+test('dismissedLine and the comment count', () => {
+ const f = { ...review(fx.REVIEW_294).findings[0], state: 'dismissed', dismissed: { reason: 'fine_here', note: '', by: 'person', at: null } };
+ assert.equal(m.dismissedLine(f), 'Dismissed · Fine in this PR · you');
+ assert.equal(m.openFindings(review(fx.REVIEW_294)), 3, 'f1 and f3 open, f2 sent: all still open');
+ assert.equal(m.openFindings(null), 0);
+ assert.equal(m.findingsSummary(review(fx.REVIEW_294).findings), '1 high, 1 medium, 1 low');
+});
+
+test('undoLeft: 10 s after a Fix it, and none once a task exists', () => {
+ const f2 = review(fx.REVIEW_294).findings[1];
+ const at = Date.parse(f2.sent_at);
+ assert.equal(m.undoLeft(f2, at + 1000), 9000);
+ assert.equal(m.undoLeft(f2, at + 10_000), 0);
+ assert.equal(m.undoLeft({ ...f2, task_id: 't1' }, at + 1000), 0);
+ assert.equal(m.undoLeft({ ...f2, state: 'open' }, at), 0);
+});
+
+test('the Dismiss flow in the review card: reason, submit, collapsed line', async () => {
+ const card = review(fx.REVIEW_294);
+ const sent = [];
+ const onFinding = async (cardId, fid, action) => {
+ sent.push([cardId, fid, action]);
+ return { ...card, findings: card.findings.map((f) => (f.id === fid ? { ...f, state: 'dismissed', dismissed: { reason: action.reason, note: action.note ?? '', by: 'person', at: null } } : f)) };
+ };
+ const host = await mount(m.ReviewCard, { card, onFinding, sample: true, now: NOW });
+ const row = () => host.querySelector('[data-finding="f3"]');
+ await click(button(row(), 'Dismiss'));
+ const form = row().querySelector('form');
+ assert.ok(form, 'the inline form opens');
+ assert.match(form.textContent, /Why dismiss\? Rigel learns from this\./);
+ const submit = button(form, 'Dismiss finding');
+ assert.equal(submit.disabled, true, 'needs a reason');
+ await click(button(form, 'Fine in this PR'));
+ assert.equal(button(form, 'Fine in this PR').getAttribute('aria-checked'), 'true');
+ assert.equal(button(form, 'Dismiss finding').disabled, false);
+ form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.deepEqual(sent, [['dvr_294', 'f3', { action: 'dismiss', reason: 'fine_here' }]]);
+ assert.equal(row().dataset.state, 'dismissed');
+ assert.match(row().textContent, /Dismissed · Fine in this PR · you/);
+ assert.doesNotMatch(host.textContent, /Post to GitHub/);
+});
+
+test('Dismiss can be cancelled, and a failed dismiss keeps the form with the error', async () => {
+ const card = review(fx.REVIEW_294);
+ const host = await mount(m.ReviewCard, { card, now: NOW, onFinding: async () => { throw new Error('kwant is offline'); } });
+ const row = () => host.querySelector('[data-finding="f1"]');
+ await click(button(row(), 'Dismiss'));
+ await click(button(row(), 'Cancel'));
+ assert.equal(row().querySelector('form'), null);
+ await click(button(row(), 'Dismiss'));
+ await click(button(row(), 'Wrong'));
+ row().querySelector('form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
+ await settle();
+ assert.match(row().querySelector('[role="alert"]').textContent, /kwant is offline/);
+ assert.equal(row().dataset.state, 'open');
+});
+
+test('Fix it sends the finding and offers Undo for 10 s', async () => {
+ const card = review(fx.REVIEW_294);
+ const actions = [];
+ const host = await mount(m.ReviewCard, {
+ card,
+ now: Date.parse('2026-11-05T01:00:02Z'),
+ onFinding: async (_c, fid, a) => {
+ actions.push([fid, a.action]);
+ return { ...card, findings: card.findings.map((f) => (f.id === fid ? { ...f, state: a.action === 'fix' ? 'sent' : 'open', sent_to: 'Pixel', sent_at: '2026-11-05T01:00:00Z' } : f)) };
+ },
+ });
+ await click(button(host.querySelector('[data-finding="f1"]'), 'Fix it'));
+ const row = host.querySelector('[data-finding="f1"]');
+ assert.match(row.textContent, /Sent to Pixel as a task · 01:00/);
+ assert.match(button(row, 'Undo').textContent, /8 s/);
+ await click(button(row, 'Undo'));
+ assert.deepEqual(actions, [['f1', 'fix'], ['f1', 'undo_fix']]);
+});
+
+test('the review card: sample chip, tamper, security tiles in 0.7.x, read-only footer', () => {
+ const out = html(m.ReviewCard, { card: review(fx.REVIEW_294), onFinding: async () => review(fx.REVIEW_294), sample: true, now: NOW });
+ assert.match(out, /Sample PR/);
+ assert.match(out, /A test was made easier to pass/);
+ assert.match(out, /Different engine from the author/);
+ assert.match(out, /data-sec="OSV" data-state="later"/);
+ assert.match(out, /data-sec="Semgrep" data-state="later"/);
+ assert.equal((out.match(/in 0\.7\.x/g) ?? []).length >= 2, true);
+ assert.doesNotMatch(out, /Post to GitHub/, 'S2: no button that can never be pressed');
+ assert.match(out, /Read only: nothing is posted to GitHub in this version\./);
+ assert.match(out, /<footer data-review-footer[^>]*>[\s\S]*Open on GitHub[\s\S]*<\/footer>/);
+ assert.match(out, /Did less than asked/);
+ assert.match(out, /Did more than asked/);
+ const none = html(m.ReviewCard, { card: review(fx.REVIEW_NO_REVIEWER), onFinding: async () => review(fx.REVIEW_NO_REVIEWER) });
+ assert.match(none, /No reviewer: add a second bot to this space/);
+ assert.doesNotMatch(none, /Different engine/);
+ assert.match(none, /Draft/);
+});
+
+test('release notes: a pending state, then Copy and Discard; Save to Notion only when connected', () => {
+ const pend = html(m.ReleaseNotesSheet, { card: m.parseReleaseNotes(fx.RELEASE_PENDING), onDiscard() {}, onClose() {} });
+ assert.match(pend, /Writing the notes from what landed/);
+ assert.doesNotMatch(pend, /Save to Notion/);
+ const ready = html(m.ReleaseNotesSheet, { card: m.parseReleaseNotes(fx.RELEASE_READY), onDiscard() {}, onClose() {} });
+ assert.match(ready, /What’s new/);
+ assert.match(ready, />Copy</);
+ assert.match(ready, /Discard/);
+ assert.doesNotMatch(ready, /Save to Notion/);
+ assert.match(html(m.ReleaseNotesSheet, { card: m.parseReleaseNotes(fx.RELEASE_READY), onSaveToNotion: async () => {}, onDiscard() {}, onClose() {} }), /Save to Notion/);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Round 2: Mira's review of #314 (B1, B2, S1–S4) and Vega's round-3 shape
+
+test('round 3 shape: reviewer.id and tamper.unread parse; #303 with an open finding is not verified', () => {
+ const r = m.parseReview(fx.REVIEW_303);
+ assert.equal(r.reviewer.id, 'kw_demo_rigel');
+ assert.deepEqual(r.tamper.unread, []);
+ const none = m.parseReview(fx.REVIEW_NO_REVIEWER);
+ assert.deepEqual(none.tamper.unread, ['Cargo.lock', 'frontend/package-lock.json']);
+ const junk = m.parseReview({ ...fx.REVIEW_289, reviewer: { name: 'Rigel', id: 42 }, tamper: { flags: [], unread: ['', 7, 'a.rs'] } });
+ assert.equal(junk.reviewer.id, null, 'a non-string id is dropped');
+ assert.deepEqual(junk.tamper.unread, ['a.rs'], 'only non-empty paths');
+ assert.deepEqual(m.parseReview({ kind: 'review', pr: 1 }).tamper, { flags: [], unread: [] }, 'an older card without unread');
+ const l303 = m.parseLanded(fx.LANDED_303);
+ assert.equal(l303.verified, false);
+ assert.equal(m.showVerified(l303, [m.parseReview(fx.REVIEW_303)]), false);
+});
+
+test('review card lists the files GitHub sent no diff for', () => {
+ const out = html(m.ReviewCard, { card: review(fx.REVIEW_NO_REVIEWER), onFinding: async () => review(fx.REVIEW_NO_REVIEWER) });
+ assert.match(out, /data-tamper-unread="2"/);
+ assert.match(out, /Couldn’t read 2 files: GitHub sent no diff, so nothing in them was checked\./);
+ assert.match(out, />Cargo\.lock<\/li>/);
+ assert.doesNotMatch(html(m.ReviewCard, { card: review(fx.REVIEW_303), onFinding: async () => review(fx.REVIEW_303) }), /data-tamper-unread/);
+});
+
+test('B1: risk pills use the surface-main hex for their text, never text-surface-main', () => {
+ for (const level of ['high', 'medium', 'low']) {
+ const card = review(fx.REVIEW_294, { risk: { level, reasons: ['x'] } });
+ const out = html(m.ReviewCard, { card, onFinding: async () => card });
+ assert.match(out, /class="inline-flex items-center gap-1 rounded-full px-2 py-0\.5 text-xs font-semibold bg-(rose|amber|teal)-300 text-\[#120e26\]"/, level);
+ assert.doesNotMatch(out, /text-surface-main/, level);
+ }
+});
+
+test('B2: the main floor button is aria-disabled while busy, never disabled', async () => {
+ let release;
+ const done = new Promise((r) => (release = r));
+ const calls = [];
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_MIGRATION,
+ onResolve: (id, d) => calls.push([id, d]),
+ onBackup: async () => {
+ await done;
+ return { id: 'b', ok: true, path: null, bytes: 1, taken_at: null, error: null };
+ },
+ });
+ const main = host.querySelector('[data-floor-main]');
+ assert.equal(main.hasAttribute('aria-disabled'), false, 'not marked while idle');
+ main.focus();
+ await click(main);
+ assert.equal(main.getAttribute('aria-disabled'), 'true');
+ assert.equal(main.hasAttribute('disabled'), false);
+ assert.equal(document.activeElement, main, 'focus stays on the button while the backup runs');
+ assert.match(main.className, /aria-disabled:opacity-50 aria-disabled:cursor-not-allowed/);
+ release();
+ await settle();
+ assert.equal(main.hasAttribute('disabled'), false);
+ assert.equal(main.hasAttribute('aria-disabled'), false);
+ assert.equal(document.activeElement, main);
+ assert.deepEqual(calls, []);
+});
+
+test('B2: a backup started from the secondary Back up first puts focus on the main button', async () => {
+ const host = await mount(m.ModernApprovalCard, {
+ approval: fx.FLOOR_DEPLOY_OLD,
+ onResolve() {},
+ onBackup: async () => ({ id: 'b', ok: true, path: null, bytes: 1, taken_at: null, error: null }),
+ });
+ const secondary = button(host, 'Back up first');
+ assert.ok(secondary, 'the old-backup deploy offers the secondary button');
+ assert.notEqual(secondary, host.querySelector('[data-floor-main]'));
+ secondary.focus();
+ await click(secondary);
+ assert.equal(button(host, 'Back up first'), undefined, 'the secondary button is gone');
+ assert.equal(document.activeElement, host.querySelector('[data-floor-main]'), 'focus is on the main button, not <body>');
+});
+
+test('S1: a landed card with an open review finding never says Nothing to do', () => {
+ const card = landed(fx.LANDED_289);
+ const clean = html(m.LandedCard, { card, reviews: [review(fx.REVIEW_289)] });
+ assert.match(clean, /Nothing to do for you\./);
+ assert.doesNotMatch(clean, /data-findings-open/);
+ const f = review(fx.REVIEW_294).findings;
+ const one = html(m.LandedCard, { card, reviews: [review(fx.REVIEW_289, { findings: [f[0]] })] });
+ assert.doesNotMatch(one, /Nothing to do for you/);
+ assert.match(one, /<span class="font-semibold text-amber-300">1 finding open<\/span><span class="text-zinc-400">in the review<\/span>/);
+ assert.doesNotMatch(one, /Open review/, 'no link without a handler');
+ const opened = [];
+ const two = html(m.LandedCard, { card, reviews: [review(fx.REVIEW_289, { findings: [f[0], f[1], { ...f[2], state: 'dismissed' }] })], onOpenReview: (pr) => opened.push(pr) });
+ assert.match(two, /2 findings open/, 'plural; sent counts, dismissed does not');
+ assert.match(two, /<button type="button"[^>]*>Open review<\/button>/);
+});
+
+test('S1: Open review calls back with the PR number', async () => {
+ const opened = [];
+ const host = await mount(m.LandedCard, { card: landed(fx.LANDED_303), reviews: [review(fx.REVIEW_303)], onOpenReview: (pr) => opened.push(pr) });
+ assert.match(host.textContent, /1 finding open/);
+ await click(button(host, 'Open review'));
+ assert.deepEqual(opened, [303]);
+});
+
+test('S3: areas that need the person come first, and are never folded into +N more', () => {
+ const A = (...xs) => xs.map((area) => ({ area }));
+ assert.deepEqual(m.rollupTiles(A('a', 'b', 'c', 'd', 'e'), ['e']), { shown: A('e', 'a'), more: 3 });
+ assert.deepEqual(m.rollupTiles(A('a', 'b', 'c', 'd', 'e', 'f'), ['f', 'b', 'd']), { shown: A('b', 'd', 'f'), more: 3 }, 'all three show, stable');
+ assert.deepEqual(m.rollupTiles(A('a', 'b', 'c'), ['c']), { shown: A('c', 'a', 'b'), more: 0 });
+ const base = { last_tag: null, last_merge: null, branch: 'main', onDraftNotes() {}, onMarkSeen() {} };
+ const r = html(m.Rollup, { ...base, rollup: fx.ROLLUP_MANY, needsYouAreas: ['Docs'] });
+ assert.match(r, /data-area="Docs" data-needs-you="true"/, 'the last area is not hidden behind +N more');
+ assert.match(r, /\+4 more areas/);
+});
+
+test('S4: each finding says its severity as a word, not only by colour', () => {
+ const out = html(m.ReviewCard, { card: review(fx.REVIEW_294), onFinding: async () => review(fx.REVIEW_294) });
+ const words = [...out.matchAll(/<span data-sev-word="(\w+)" class="([^"]+)">(\w+)<span class="sr-only">:<\/span><\/span>/g)].map((x) => [x[1], x[3], x[2]]);
+ assert.deepEqual(words.map(([s, w]) => [s, w]), [['high', 'High'], ['medium', 'Medium'], ['low', 'Low']]);
+ for (const [, , cls] of words) assert.match(cls, /text-\[10px\] font-semibold uppercase tracking-wide text-(rose|amber|teal)-300/);
+});