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.

Truth Ledger UI: facts, disputes and citations on the board (C2)

Pixel (kwant bot)9bdc94d198ca
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 62165249..c45a43fe 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -344,7 +344,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// Opens the chat of a bot's newest open browser step; false when it has none.
const openHumanStepRef = useRef<(kwantId: string) => boolean>(() => false);
const openTargetRef = useRef<(t: ChatTarget) => boolean>(() => false);
- // A tier request is decided on the board's Needs-you list.
+ // A tier request or a fact dispute is decided on the board's Needs-you list.
const openBoardForTier = () => {
setShowMissions(true);
setShowConnections(false);
@@ -360,7 +360,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const target = { channel_id: n.channel_id, kwant_id: n.kwant_id };
// Failed routines and finished or slow delegations show in the app; the OS notification is for a hidden tab.
if (!document.hidden && (TOAST_KINDS as string[]).includes(n.kind)) {
- if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && n.kind !== 'tier_proposed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
+ if (n.kind !== 'routine_failed' && n.kind !== 'skill_proposed' && n.kind !== 'automation_suggested' && n.kind !== 'tier_proposed' && n.kind !== 'fact_disputed' && openCtxRef.current === (n.channel_id ?? n.kwant_id)) return;
const id = ++toastIdRef.current;
const action =
n.kind === 'routine_failed'
@@ -371,6 +371,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
? { label: 'Review', onClick: () => setIsRoutinesOpen(true) }
: n.kind === 'tier_proposed'
? { label: 'Review', onClick: openBoardForTier }
+ : n.kind === 'fact_disputed'
+ ? { label: 'Settle', onClick: openBoardForTier }
: n.kind === 'question_asked'
? { label: 'Answer', onClick: () => openQuestionRef.current(n.kwant_id) || openTargetRef.current(target) }
: n.kind === 'human_step'
@@ -390,6 +392,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
// A suggested routine is decided in Routines, not in the bot's chat
else if (n.kind === 'automation_suggested') setIsRoutinesOpen(true);
else if (n.kind === 'tier_proposed') openBoardForTier();
+ else if (n.kind === 'fact_disputed') openBoardForTier();
else if (n.kind === 'human_step' && openHumanStepRef.current(n.kwant_id)) {
setIsVmPaneOpen(true);
// A CAPTCHA lands straight in the solve view
@@ -944,6 +947,15 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'CapabilityChanged':
if (event.data?.capability?.kwant_id) emitMission({ type: 'capability_changed', data: { capability: event.data.capability } });
break;
+ // Truth Ledger (C2): the board's Facts reload; the stream is already this space's.
+ case 'fact_changed':
+ case 'FactChanged':
+ if (event.data?.fact?.id) emitMission({ type: 'fact_changed', data: { fact: event.data.fact } });
+ break;
+ case 'fact_dispute':
+ case 'FactDispute':
+ if (event.data?.dispute?.id) emitMission({ type: 'fact_dispute', data: { dispute: event.data.dispute } });
+ break;
case 'routine_run':
case 'RoutineRun':
emitContinuity({ type: 'routine_run', data: event.data });
diff --git a/frontend/src/components/FactsLedger.tsx b/frontend/src/components/FactsLedger.tsx
new file mode 100644
index 00000000..f4ced315
--- /dev/null
+++ b/frontend/src/components/FactsLedger.tsx
@@ -0,0 +1,600 @@
+// Truth Ledger on the board (Phase C2): disputes first, as Needs you (keep one fact or mark them as
+// not a conflict), then the facts bots read, labelled when unconfirmed or disputed, each with where it
+// came from and which tasks rely on it. Renders nothing unless the ledger is `on`: with it off or in
+// shadow (or on a server without it) the board looks as before. Live through `fact_changed` and
+// `fact_dispute`.
+
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import { AlertTriangle, BookOpenCheck, Check, ChevronDown, Loader2, Scale } from 'lucide-react';
+import { MissionError, ago, factsApi, newIdempotencyKey, onMission } from '../missions';
+import {
+ Dispute,
+ Fact,
+ FactDetail,
+ FactFilter,
+ LedgerSetting,
+ causeText,
+ citationText,
+ disputeConflictText,
+ disputeOutcome,
+ factConflictText,
+ factLabel,
+ filterFacts,
+ scopeText,
+ sortFacts,
+ sourceText,
+} from '../truthLedger';
+
+export type LedgerApi = Pick<typeof factsApi, 'list' | 'disputes' | 'get' | 'resolve' | 'dismiss' | 'accept' | 'reject'>;
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400';
+const btn = `inline-flex items-center justify-center gap-1 px-3 min-h-[40px] sm:min-h-[32px] rounded-lg text-xs font-medium disabled:opacity-50 ${focusRing}`;
+const TONE = {
+ amber: 'border-amber-500/40 bg-amber-500/10 text-amber-200',
+ rose: 'border-rose-500/40 bg-rose-500/10 text-rose-200',
+ zinc: 'border-zinc-700 bg-zinc-800 text-zinc-400',
+};
+
+export const FactBadge: React.FC<{ status: string }> = ({ status }) => {
+ const l = factLabel(status);
+ if (!l) return null;
+ return (
+ <span className={`inline-flex shrink-0 items-center rounded-full border px-1.5 py-px text-[10px] font-medium ${TONE[l.tone]}`} data-fact-label={status}>
+ {l.text}
+ </span>
+ );
+};
+
+const errText = (e: unknown, fallback: string) => (e instanceof Error && e.message ? e.message : fallback);
+
+/** One open (or just decided) dispute: both facts side by side, keep one, or not a conflict. */
+export const DisputeCard: React.FC<{
+ dispute: Dispute;
+ names: Record<string, string>;
+ teams?: Record<string, string>;
+ now?: number;
+ busy?: boolean;
+ error?: string | null;
+ onKeep: (d: Dispute, winner: Fact) => void;
+ onDismiss: (d: Dispute) => void;
+}> = ({ dispute: d, names, teams = {}, now = Date.now(), busy = false, error = null, onKeep, onDismiss }) => {
+ const id = useId();
+ const sides = d.facts ?? [];
+ const open = d.status === 'open';
+ return (
+ <li
+ aria-labelledby={`${id}-t`}
+ className={`rounded-xl border px-3 py-2.5 space-y-2 ${open ? 'border-amber-500/30 bg-amber-500/5' : 'border-zinc-800 bg-zinc-900/40'}`}
+ data-dispute={d.id}
+ data-status={d.status}
+ >
+ <div className="flex items-start gap-2">
+ <Scale size={16} className={`mt-0.5 shrink-0 ${open ? 'text-amber-300' : 'text-zinc-500'}`} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p id={`${id}-t`} className="text-xs font-medium text-zinc-100">
+ Two facts disagree
+ </p>
+ <p className="text-[11px] text-zinc-400">
+ {causeText(d.cause)} <span className="text-zinc-600">· {ago(d.created_at, now)}</span>
+ </p>
+ </div>
+ </div>
+ <div className="grid gap-2 sm:grid-cols-2">
+ {[0, 1].map((i) => {
+ const f = sides[i];
+ const won = !open && d.winner && f?.id === d.winner;
+ return (
+ <div key={i} className={`rounded-lg border px-2.5 py-2 space-y-1.5 ${won ? 'border-emerald-500/40 bg-emerald-500/5' : 'border-zinc-800 bg-zinc-950/50'}`} data-side={i === 0 ? 'a' : 'b'}>
+ {f ? (
+ <>
+ <p className="text-xs text-zinc-100 break-words">
+ <span className="sr-only">{i === 0 ? 'First fact: ' : 'Second fact: '}</span>“{f.statement}”
+ </p>
+ <p className="text-[11px] text-zinc-500 break-words">
+ {scopeText(f, names, teams)} · {sourceText(f, names)} · {ago(f.created_at, now)}
+ </p>
+ {open && (
+ <button
+ type="button"
+ disabled={busy}
+ onClick={() => onKeep(d, f)}
+ aria-label={`Keep “${f.statement}” and replace the other`}
+ className={`${btn} w-full sm:w-auto border border-emerald-500/40 text-emerald-200 hover:bg-emerald-500/10`}
+ data-keep={f.id}
+ >
+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={12} aria-hidden="true" />}
+ Keep this one
+ </button>
+ )}
+ </>
+ ) : (
+ <p className="text-[11px] text-zinc-500">This fact is gone.</p>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ {error && (
+ <p role="alert" className="flex items-start gap-1.5 text-[11px] text-rose-300" data-dispute-error>
+ <AlertTriangle size={12} className="mt-px shrink-0" aria-hidden="true" /> <span>{error}</span>
+ </p>
+ )}
+ {open ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" disabled={busy} onClick={() => onDismiss(d)} className={`${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700`} data-dismiss>
+ Not a conflict
+ </button>
+ <span className="text-[10px] text-zinc-500">Until you choose, bots see both, labelled disputed.</span>
+ </div>
+ ) : (
+ <p className={`text-[11px] ${d.status === 'resolved' ? 'text-emerald-300' : 'text-zinc-400'}`} data-outcome={d.status}>
+ {disputeOutcome(d, sides)}
+ </p>
+ )}
+ </li>
+ );
+};
+
+/** A fact's details, loaded when opened: which tasks rely on it, its evidence and history; confirm or reject if unconfirmed. */
+const FactDetails: React.FC<{
+ fact: Fact;
+ api: LedgerApi;
+ taskTitles: Record<string, string>;
+ onOpenTask?: (id: string) => void;
+ now: number;
+ version: number;
+ onChanged: () => void;
+}> = ({ fact, api, taskTitles, onOpenTask, now, version, onChanged }) => {
+ const [detail, setDetail] = useState<FactDetail | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [note, setNote] = useState<string | null>(null);
+ const keys = useRef<Record<string, string>>({});
+ const load = useCallback(() => {
+ let live = true;
+ // A refresh keeps any message (a 409 explains itself); Try again clears it first.
+ api.get(fact.id).then(
+ (d) => live && setDetail(d),
+ (e) => live && setError(errText(e, 'Couldn’t load this fact.')),
+ );
+ return () => {
+ live = false;
+ };
+ }, [api, fact.id]);
+ useEffect(load, [load, version]);
+
+ const decide = async (accept: boolean) => {
+ const k = accept ? 'accept' : 'reject';
+ const key = (keys.current[k] ??= newIdempotencyKey());
+ setBusy(true);
+ setError(null);
+ try {
+ setDetail(await (accept ? api.accept : api.reject)(fact.id, key));
+ setNote(accept ? 'Confirmed: bots now read it without the label.' : 'Rejected: bots no longer read it.');
+ onChanged();
+ } catch (e) {
+ setError(e instanceof MissionError && e.status === 409 ? factConflictText(e) : errText(e, 'Couldn’t save that. Try again.'));
+ if (e instanceof MissionError && e.status === 409) {
+ load();
+ onChanged();
+ }
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (!detail && !error)
+ return (
+ <p className="flex items-center gap-1.5 text-[11px] text-zinc-400">
+ <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading…
+ </p>
+ );
+ const f = detail?.fact ?? fact;
+ const tasks = (detail?.citations ?? []).filter((c) => c.cited_by_kind === 'task');
+ return (
+ <div className="space-y-1.5 text-[11px]" data-fact-detail={fact.id}>
+ {detail && (
+ <>
+ <p className="text-zinc-300" data-citations={tasks.length}>
+ {citationText(detail.citations)}
+ </p>
+ {tasks.length > 0 && (
+ <ul className="space-y-0.5" aria-label="Tasks that rely on it">
+ {tasks.slice(0, 8).map((c) => {
+ const title = taskTitles[c.cited_by_id] ?? 'A task';
+ return (
+ <li key={c.cited_by_id}>
+ {onOpenTask ? (
+ <button type="button" onClick={() => onOpenTask(c.cited_by_id)} className={`text-left text-sky-300 hover:underline rounded break-words ${focusRing}`}>
+ {title}
+ </button>
+ ) : (
+ <span className="text-zinc-400">{title}</span>
+ )}
+ <span className="text-zinc-600"> · since {ago(c.created_at, now)}</span>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ {detail.evidence.length > 0 && (
+ <p className="text-zinc-400">
+ Backed by {detail.evidence.length} piece{detail.evidence.length === 1 ? '' : 's'} of evidence
+ {detail.evidence.some((e) => e.check_id) ? ', including a check' : ''}.
+ </p>
+ )}
+ {f.valid_until && (
+ <p className="text-zinc-500">
+ {Date.parse(f.valid_until) > now ? `Bots stop reading it on ${new Date(f.valid_until).toLocaleDateString()}.` : `Bots stopped reading it ${ago(f.valid_until, now)}.`}
+ </p>
+ )}
+ </>
+ )}
+ {f.status === 'proposed' && (
+ <div className="flex flex-wrap items-center gap-2 pt-0.5" role="group" aria-label={`Unconfirmed: ${f.statement}`}>
+ <button type="button" disabled={busy} onClick={() => void decide(true)} className={`${btn} bg-emerald-600/90 text-white hover:bg-emerald-500`} data-confirm-fact>
+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={12} aria-hidden="true" />} Confirm
+ </button>
+ <button type="button" disabled={busy} onClick={() => void decide(false)} className={`${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700`} data-reject-fact>
+ Reject
+ </button>
+ </div>
+ )}
+ <p aria-live="polite" className="text-emerald-300 min-h-0">
+ {note}
+ </p>
+ {error && (
+ <p role="alert" className="flex flex-wrap items-center gap-2 text-rose-300">
+ <AlertTriangle size={12} aria-hidden="true" /> {error}
+ {!detail && (
+ <button
+ type="button"
+ onClick={() => {
+ setError(null);
+ load();
+ }}
+ className={`underline hover:text-rose-200 rounded ${focusRing}`}
+ >
+ Try again
+ </button>
+ )}
+ </p>
+ )}
+ </div>
+ );
+};
+
+const FactRow: React.FC<{
+ fact: Fact;
+ names: Record<string, string>;
+ teams: Record<string, string>;
+ taskTitles: Record<string, string>;
+ onOpenTask?: (id: string) => void;
+ api: LedgerApi;
+ now: number;
+ version: number;
+ onChanged: () => void;
+}> = ({ fact: f, names, teams, taskTitles, onOpenTask, api, now, version, onChanged }) => {
+ const [open, setOpen] = useState(false);
+ const id = useId();
+ return (
+ <li className="px-2.5 py-2 space-y-1.5" data-fact={f.id} data-status={f.status}>
+ <div className="flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <p className={`text-xs break-words ${f.status === 'superseded' ? 'text-zinc-500 line-through' : 'text-zinc-100'}`}>
+ {f.statement} <FactBadge status={f.status} />
+ </p>
+ <p className="text-[11px] text-zinc-500 break-words">
+ {scopeText(f, names, teams)} · {sourceText(f, names)} · {ago(f.created_at, now)}
+ </p>
+ </div>
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={`${id}-d`}
+ onClick={() => setOpen((v) => !v)}
+ className={`shrink-0 inline-flex items-center gap-0.5 px-2 min-h-[40px] sm:min-h-[28px] rounded text-[11px] text-sky-300 hover:text-sky-200 ${focusRing}`}
+ data-fact-toggle
+ >
+ {open ? 'Less' : 'Details'}
+ <span className="sr-only"> about “{f.statement}”</span>
+ <ChevronDown size={12} className={open ? 'rotate-180' : ''} aria-hidden="true" />
+ </button>
+ </div>
+ {open && (
+ <div id={`${id}-d`} className="rounded-lg bg-zinc-950/60 px-2.5 py-2">
+ <FactDetails fact={f} api={api} taskTitles={taskTitles} onOpenTask={onOpenTask} now={now} version={version} onChanged={onChanged} />
+ </div>
+ )}
+ </li>
+ );
+};
+
+const FILTERS: Array<{ id: FactFilter; label: string }> = [
+ { id: 'all', label: 'In force' },
+ { id: 'proposed', label: 'Unconfirmed' },
+ { id: 'disputed', label: 'Disputed' },
+];
+
+/**
+ * The board's Facts section. Loads its own state; tests pass `initial` (the setting, facts and open
+ * disputes as loaded) and the API.
+ */
+export const FactsLedger: React.FC<{
+ names: Record<string, string>;
+ teams?: Record<string, string>;
+ taskTitles?: Record<string, string>;
+ onOpenTask?: (id: string) => void;
+ now?: number;
+ initial?: { setting: LedgerSetting; facts: Fact[]; disputes: Dispute[] };
+ /** Open the facts list from the start (screenshots, a notification tap). */
+ defaultOpen?: boolean;
+ api?: LedgerApi;
+}> = ({ names, teams = {}, taskTitles = {}, onOpenTask, now = Date.now(), initial, defaultOpen = false, api = factsApi }) => {
+ const headId = useId();
+ const listId = useId();
+ const [setting, setSetting] = useState<LedgerSetting | null>(initial?.setting ?? null);
+ const [facts, setFacts] = useState<Fact[]>(initial?.facts ?? []);
+ const [disputes, setDisputes] = useState<Dispute[]>(initial?.disputes ?? []);
+ const [decided, setDecided] = useState<Dispute[]>([]);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [reloading, setReloading] = useState(false);
+ const [showList, setShowList] = useState(defaultOpen);
+ const [filter, setFilter] = useState<FactFilter>('all');
+ const [version, setVersion] = useState(0);
+ const [busyId, setBusyId] = useState<string | null>(null);
+ const [errors, setErrors] = useState<Record<string, string>>({});
+ const keys = useRef<Record<string, string>>({});
+ const alive = useRef(true);
+ useEffect(
+ () => () => {
+ alive.current = false;
+ },
+ [],
+ );
+
+ const reload = useCallback(() => {
+ setReloading(true);
+ Promise.all([api.list(), api.disputes('open')]).then(
+ ([l, d]) => {
+ if (!alive.current) return;
+ setSetting(l.setting);
+ setFacts(l.facts);
+ setDisputes(d.disputes);
+ setLoadError(null);
+ setReloading(false);
+ setVersion((v) => v + 1);
+ },
+ (e) => {
+ if (!alive.current) return;
+ setReloading(false);
+ // Before the first answer an error (an older server's 404) just means: show nothing.
+ setLoadError(errText(e, 'Couldn’t load the facts.'));
+ },
+ );
+ }, [api]);
+
+ useEffect(() => {
+ if (!initial) reload();
+ }, [initial, reload]);
+
+ // Live: a burst of changes (a dispute moves both facts and their tasks) reads once.
+ useEffect(() => {
+ let t: ReturnType<typeof setTimeout> | null = null;
+ const soon = () => {
+ if (t) clearTimeout(t);
+ t = setTimeout(reload, 250);
+ };
+ const offA = onMission('fact_changed', soon);
+ const offB = onMission('fact_dispute', soon);
+ return () => {
+ offA();
+ offB();
+ if (t) clearTimeout(t);
+ };
+ }, [reload]);
+
+ const decide = async (d: Dispute, what: 'resolve' | 'dismiss', winner?: Fact) => {
+ if (busyId) return;
+ const k = `${what}:${d.id}:${winner?.id ?? ''}`;
+ const key = (keys.current[k] ??= newIdempotencyKey());
+ setBusyId(d.id);
+ setErrors(({ [d.id]: _gone, ...rest }) => rest);
+ try {
+ const after = what === 'resolve' && winner ? await api.resolve(d.id, winner.id, key) : await api.dismiss(d.id, key);
+ setDecided((cur) => [{ ...after, facts: after.facts ?? d.facts }, ...cur.filter((x) => x.id !== d.id)]);
+ setDisputes((cur) => cur.filter((x) => x.id !== d.id));
+ reload();
+ } catch (e) {
+ if (e instanceof MissionError && e.status === 409) {
+ setErrors((x) => ({ ...x, [d.id]: disputeConflictText(e) }));
+ // Show what holds now: the settled dispute with its outcome, from the full list.
+ api.disputes('all').then(
+ (r) => {
+ if (!alive.current) return;
+ const nowD = r.disputes.find((x) => x.id === d.id);
+ if (nowD && nowD.status !== 'open') {
+ setDecided((cur) => [nowD, ...cur.filter((x) => x.id !== d.id)]);
+ setDisputes((cur) => cur.filter((x) => x.id !== d.id));
+ }
+ },
+ () => {},
+ );
+ reload();
+ } else {
+ // Another press retries with the same key: a lost answer replays rather than repeats.
+ setErrors((x) => ({ ...x, [d.id]: errText(e, 'Couldn’t save that. Try again.') }));
+ }
+ } finally {
+ setBusyId(null);
+ }
+ };
+
+ // Off, shadow, an older server, or still loading the first time: the board looks as before.
+ if (setting !== 'on') return null;
+
+ // One decided here stays shown with its outcome, even if a reload raced the decision.
+ const decidedIds = new Set(decided.map((d) => d.id));
+ const openDisputes = disputes.filter((d) => !decidedIds.has(d.id)).sort((a, b) => a.created_at.localeCompare(b.created_at));
+ const shownDisputes = [...openDisputes, ...decided];
+ const inForce = facts.filter((f) => f.status !== 'superseded');
+ const unconfirmed = facts.filter((f) => f.status === 'proposed').length;
+ const disputed = facts.filter((f) => f.status === 'disputed').length;
+ const listed = sortFacts(filterFacts(facts, filter));
+
+ return (
+ <section aria-labelledby={headId} className="space-y-2 rounded-xl border border-zinc-800 bg-zinc-900/40 p-3" data-facts-ledger>
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 id={headId} className="flex items-center gap-1.5 text-xs font-medium text-zinc-200">
+ <BookOpenCheck size={14} className="text-sky-300" aria-hidden="true" /> Facts
+ </h3>
+ <p className="text-[11px] text-zinc-500" data-fact-counts>
+ {inForce.length === 0 ? 'None saved yet' : `${inForce.length} in force`}
+ {unconfirmed > 0 && <span className="text-amber-300"> · {unconfirmed} unconfirmed</span>}
+ {disputed > 0 && <span className="text-rose-300"> · {disputed} disputed</span>}
+ </p>
+ {reloading && <Loader2 size={11} className="animate-spin motion-reduce:animate-none text-zinc-500" aria-label="Updating" />}
+ <button
+ type="button"
+ aria-expanded={showList}
+ aria-controls={listId}
+ onClick={() => setShowList((v) => !v)}
+ className={`ml-auto inline-flex items-center gap-0.5 px-2 min-h-[40px] sm:min-h-[28px] rounded text-[11px] text-sky-300 hover:text-sky-200 ${focusRing}`}
+ data-facts-toggle
+ >
+ {showList ? 'Hide facts' : 'Show facts'}
+ <ChevronDown size={12} className={showList ? 'rotate-180' : ''} aria-hidden="true" />
+ </button>
+ </div>
+
+ {loadError && (
+ <p role="alert" className="flex flex-wrap items-center gap-2 text-[11px] text-rose-300" data-facts-error>
+ <AlertTriangle size={12} aria-hidden="true" /> {loadError}
+ <button type="button" onClick={reload} className={`underline hover:text-rose-200 rounded ${focusRing}`}>
+ Try again
+ </button>
+ </p>
+ )}
+
+ {shownDisputes.length > 0 && (
+ <div className="space-y-2" data-disputes={openDisputes.length}>
+ <h4 className="text-xs font-medium text-amber-200">
+ Needs you: {openDisputes.length === 0 ? 'disputes' : openDisputes.length === 1 ? 'one dispute' : `${openDisputes.length} disputes`} to settle
+ </h4>
+ <ul className="space-y-2">
+ {shownDisputes.map((d) => (
+ <DisputeCard
+ key={d.id}
+ dispute={d}
+ names={names}
+ teams={teams}
+ now={now}
+ busy={busyId === d.id}
+ error={errors[d.id] ?? null}
+ onKeep={(x, w) => void decide(x, 'resolve', w)}
+ onDismiss={(x) => void decide(x, 'dismiss')}
+ />
+ ))}
+ </ul>
+ {openDisputes.length === 0 && (
+ <p className="text-[11px] text-zinc-500">
+ All settled.{' '}
+ <button type="button" onClick={() => setDecided([])} className={`underline hover:text-zinc-300 rounded ${focusRing}`}>
+ Hide
+ </button>
+ </p>
+ )}
+ </div>
+ )}
+
+ {showList && (
+ <div id={listId} className="space-y-2">
+ <div role="group" aria-label="Show" className="flex flex-wrap gap-1.5">
+ {FILTERS.map((x) => (
+ <button
+ key={x.id}
+ type="button"
+ aria-pressed={filter === x.id}
+ onClick={() => setFilter(x.id)}
+ className={`px-2.5 min-h-[36px] sm:min-h-[28px] rounded-full border text-[11px] ${focusRing} ${filter === x.id ? 'border-sky-500/60 bg-sky-500/15 text-sky-100' : 'border-zinc-700 text-zinc-400 hover:text-zinc-200'}`}
+ data-filter={x.id}
+ >
+ {x.label}
+ </button>
+ ))}
+ </div>
+ {listed.length === 0 ? (
+ <p className="text-[11px] text-zinc-500" data-facts-empty>
+ {filter === 'all'
+ ? 'No facts yet. When a bot saves a note or you write a shared fact, it shows here.'
+ : filter === 'proposed'
+ ? 'Nothing unconfirmed.'
+ : 'Nothing disputed.'}
+ </p>
+ ) : (
+ <ul className="divide-y divide-zinc-800 rounded-lg border border-zinc-800" aria-label="Facts">
+ {listed.slice(0, 100).map((f) => (
+ <FactRow key={f.id} fact={f} names={names} teams={teams} taskTitles={taskTitles} onOpenTask={onOpenTask} api={api} now={now} version={version} onChanged={reload} />
+ ))}
+ </ul>
+ )}
+ {listed.length > 100 && <p className="text-[11px] text-zinc-500">Showing the first 100 of {listed.length}.</p>}
+ <p className="text-[10px] text-zinc-600">Bots read the facts in force; unconfirmed and disputed ones come with that label.</p>
+ </div>
+ )}
+ </section>
+ );
+};
+
+/** A task's needs-you about a fact: a fact it relied on changed (stop relying on it), or is disputed (settle it under Facts). */
+export const FactNeedsYouAction: React.FC<{
+ taskId: string;
+ item: { kind: string; id: string; fact_id?: string };
+ api?: Pick<LedgerApi, never> & { uncite: (id: string, taskId: string) => Promise<{ ok: boolean }> };
+}> = ({ taskId, item, api = factsApi }) => {
+ const [busy, setBusy] = useState(false);
+ const [done, setDone] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ if (item.kind === 'rests_on_disputed_fact')
+ return (
+ <span className="text-[11px] text-amber-200/80" data-settle-under-facts>
+ Settle it under Facts on the board.
+ </span>
+ );
+ if (item.kind !== 'fact_changed') return null;
+ if (done)
+ return (
+ <span role="status" className="text-[11px] text-emerald-300" data-uncited>
+ Done: this task no longer relies on it.
+ </span>
+ );
+ return (
+ <span className="inline-flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ disabled={busy}
+ onClick={async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ await api.uncite(item.fact_id ?? item.id, taskId);
+ setDone(true);
+ } catch (e) {
+ setError(errText(e, 'Couldn’t save that. Try again.'));
+ } finally {
+ setBusy(false);
+ }
+ }}
+ className="px-2 py-1 rounded border border-amber-500/40 hover:bg-amber-500/10 min-h-[32px] disabled:opacity-50"
+ data-uncite
+ >
+ {busy ? 'Saving…' : 'Stop relying on it'}
+ </button>
+ {error && (
+ <span role="alert" className="text-[11px] text-rose-300">
+ {error}
+ </span>
+ )}
+ </span>
+ );
+};
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index fb33d4a9..e5f2f9f3 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -35,6 +35,8 @@ import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
import { ModernAvatar } from './ModernAvatar';
import { PerformancePanel } from './PerformancePanel';
import { TierRequests } from './TierProposals';
+import { FactNeedsYouAction, FactsLedger } from './FactsLedger';
+import { isFactNeedsYou } from '../truthLedger';
import { RisksSection } from './RisksSection';
import { AuditWaiting, Risk, RiskResolution, TaskRisks, auditCardPlace, auditLive, auditWaiting, openRiskCounts, riskBadgeText, riskResolvedText } from '../auditor';
import { awayApi } from '../away';
@@ -2180,20 +2182,26 @@ export const TaskDetailBody: React.FC<{
<li key={n.id} className="flex flex-wrap items-center gap-2 px-3 py-2 rounded-lg border border-amber-500/30 bg-amber-500/10 text-xs text-amber-100">
<span className="flex-1 min-w-[10rem] break-words">
<span className="font-medium">
- {n.kind === 'approval'
- ? 'Approval'
- : n.kind === 'human_step'
- ? 'Step in the browser'
- : n.kind === 'check_approval'
- ? 'Check to allow'
- : n.kind === ENGINE_CANT_SANDBOX
- ? 'Engine can’t be sandboxed'
- : 'Question'}
+ {n.kind === 'fact_changed'
+ ? 'A fact changed'
+ : n.kind === 'rests_on_disputed_fact'
+ ? 'Rests on a disputed fact'
+ : n.kind === 'approval'
+ ? 'Approval'
+ : n.kind === 'human_step'
+ ? 'Step in the browser'
+ : n.kind === 'check_approval'
+ ? 'Check to allow'
+ : n.kind === ENGINE_CANT_SANDBOX
+ ? 'Engine can’t be sandboxed'
+ : 'Question'}
:{' '}
</span>
{n.kind === ENGINE_CANT_SANDBOX ? <span data-engine-cant-sandbox>{engineCantSandboxText(owner ?? null)}</span> : n.text}
</span>
- {n.kind === 'check_approval' ? (
+ {isFactNeedsYou(n.kind) ? (
+ <FactNeedsYouAction taskId={t.id} item={n} />
+ ) : n.kind === 'check_approval' ? (
(() => {
const c = detail.checks.find((x) => x.id === n.id);
return c && c.status === 'needs_approval' ? (
@@ -2549,6 +2557,14 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
const drafts = mission ? [] : visibleMissions.filter((m) => m.status === 'draft');
const inMission = (tasks ?? []).filter((t) => t.state !== 'cancelled' && (!missionId || t.mission_id === missionId));
const shown = filterByTeams(inMission, teamFilter, teams);
+ const taskTitles = useMemo(() => Object.fromEntries((tasks ?? []).map((t) => [t.id, t.title])), [tasks]);
+ const openTaskById = useCallback(
+ (id: string) => {
+ const t = (tasks ?? []).find((x) => x.id === id);
+ if (t) onOpenTask(t);
+ },
+ [tasks, onOpenTask],
+ );
const empty = tasks !== null && inMission.length === 0 && !mission && drafts.length === 0;
const teamOf = teamOfBots(teams);
const liveShown = live ? (teamFilter.length ? live.filter((b) => teamFilter.includes(b.teamId)) : live) : null;
@@ -2628,6 +2644,7 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
{liveShown && <LiveStrip bots={liveShown} teams={teams} workingCards={workingCards} now={now} onOpen={onOpenLive} />}
<InsightsStrip insights={insights} needsYou={needsYouCount(tasks)} />
+ <FactsLedger names={names} taskTitles={taskTitles} onOpenTask={openTaskById} now={now} />
<TierRequests names={names} now={now} />
diff --git a/frontend/src/continuity.ts b/frontend/src/continuity.ts
index 81372135..09099b98 100644
--- a/frontend/src/continuity.ts
+++ b/frontend/src/continuity.ts
@@ -180,6 +180,7 @@ export const TOAST_KINDS: NotifyKind[] = [
'human_step',
'automation_suggested',
'tier_proposed',
+ 'fact_disputed',
];
export interface NotifyEvent {
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 58129485..b1cef367 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -8,6 +8,7 @@ import { PersonCancelledError, personFetch } from './auth';
import { relativeTime } from './away';
import { Capabilities, CapabilityChange, CapabilityChangedEvent, ENGINE_CANT_SANDBOX, ProposalDecision, ProposalStatus, Scorecard, TaskTier, Tier, TierProposal } from './flightSchool';
import type { Risk, RiskResolution, TaskRisks } from './auditor';
+import { Dispute, DisputeStatus, Fact, FactChangedEvent, FactDetail, FactDisputeEvent, FactStatus, ledgerSetting } from './truthLedger';
export type TaskState = 'backlog' | 'ready' | 'working' | 'needs_you' | 'review' | 'verified' | 'blocked' | 'failed' | 'cancelled';
export type MissionStatus = 'draft' | 'active' | 'done' | 'cancelled';
@@ -51,10 +52,27 @@ export interface NeedsYouItem {
* fix_needed: a failure AutoFix never retries (id = the failure's id). workflow_change: a proposed change
* (id = the change's id); approve or reject it under /api/workflow-changes.
* engine_cant_sandbox: Flight School blocked the task because its bot is below Act on an engine kwant
- * can't hold to a tier (id = the task's id). */
- kind: 'question' | 'approval' | 'human_step' | 'check_approval' | 'may_be_invalid' | 'autofix_suggested' | 'fix_needed' | 'workflow_change' | 'engine_cant_sandbox';
+ * can't hold to a tier (id = the task's id).
+ * fact_changed: an open task cites a fact that is now disputed or was replaced (cleared with
+ * `POST /api/facts/:id/uncite`). rests_on_disputed_fact: a verified task's fact is disputed. */
+ kind:
+ | 'question'
+ | 'approval'
+ | 'human_step'
+ | 'check_approval'
+ | 'may_be_invalid'
+ | 'autofix_suggested'
+ | 'fix_needed'
+ | 'workflow_change'
+ | 'engine_cant_sandbox'
+ | 'fact_changed'
+ | 'rests_on_disputed_fact';
id: string;
text: string;
+ /** fact_changed, rests_on_disputed_fact: the fact (id = fact_id), its status now and what replaced it. */
+ fact_id?: string;
+ status?: string;
+ superseded_by?: string | null;
/** question, approval, human_step: the chat the card is in (the owner's hand-off thread, a
* channel or a direct chat), which may not be the chat the task came from. */
chat?: { channel_id: string | null; kwant_id: string | null; thread_id: string | null };
@@ -1483,7 +1501,9 @@ export type MissionEvent =
| { type: 'task_updated'; data: { task: Task } }
| { type: 'mission_updated'; data: { mission: Mission } }
/** Flight School C4: a bot asked for a tier, or a proposal was granted, declined or went stale. */
- | { type: 'capability_changed'; data: { capability: CapabilityChangedEvent } };
+ | { type: 'capability_changed'; data: { capability: CapabilityChangedEvent } }
+ | { type: 'fact_changed'; data: { fact: FactChangedEvent } }
+ | { type: 'fact_dispute'; data: { dispute: FactDisputeEvent } };
const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;
@@ -1542,7 +1562,7 @@ const sentence = (s: string) => {
export function errorFrom(status: number, answer: unknown): MissionError {
const a = answer && typeof answer === 'object' ? (answer as Record<string, unknown>) : {};
const err = typeof a.error === 'string' && a.error.trim() ? sentence(a.error) : null;
- // A 409 without a `code` may name the state it found instead (Flight School proposals).
+ // A 409 without a `code` may name the state it found instead (a Flight School proposal, or a dispute or fact already decided).
const code = typeof a.code === 'string' && a.code ? a.code : status === 409 && typeof a.status === 'string' && a.status ? a.status : null;
if (status === 403) return new MissionError('Only you can change tasks on the board.', 403);
if (status === 404 && !err) return new MissionError('This server doesn’t have the Mission board yet. Update the app and try again.', 404);
@@ -1661,6 +1681,28 @@ export const capabilitiesApi = {
call<ProposalDecision>(`/api/capabilities/proposals/${enc(id)}/decline`, 'POST', note ? { note } : {}, { 'Idempotency-Key': key }),
};
+/** The Truth Ledger (C2, person only; writes 409 unless the ledger is `on`). */
+export const factsApi = {
+ /** `setting` tells whether to show anything: only `on` does. */
+ list: (status?: FactStatus) =>
+ call<{ setting?: string; facts?: Fact[] }>(`/api/facts${status ? `?status=${enc(status)}` : ''}`).then((r) => ({
+ setting: ledgerSetting(r?.setting),
+ facts: Array.isArray(r?.facts) ? r.facts : [],
+ })),
+ disputes: (status: DisputeStatus | 'all' = 'open') =>
+ call<{ setting?: string; disputes?: Dispute[] }>(`/api/facts/disputes?status=${enc(status)}`).then((r) => ({
+ setting: ledgerSetting(r?.setting),
+ disputes: Array.isArray(r?.disputes) ? r.disputes : [],
+ })),
+ get: (id: string) => call<FactDetail>(`/api/facts/${enc(id)}`),
+ resolve: (id: string, winner: string, key: string) => call<Dispute>(`/api/facts/disputes/${enc(id)}/resolve`, 'POST', { winner }, { 'Idempotency-Key': key }),
+ dismiss: (id: string, key: string) => call<Dispute>(`/api/facts/disputes/${enc(id)}/dismiss`, 'POST', {}, { 'Idempotency-Key': key }),
+ accept: (id: string, key: string) => call<FactDetail>(`/api/facts/${enc(id)}/accept`, 'POST', {}, { 'Idempotency-Key': key }),
+ reject: (id: string, key: string) => call<FactDetail>(`/api/facts/${enc(id)}/reject`, 'POST', {}, { 'Idempotency-Key': key }),
+ uncite: (id: string, taskId: string) => call<{ ok: boolean }>(`/api/facts/${enc(id)}/uncite`, 'POST', { task_id: taskId }),
+};
+export type FactsApi = typeof factsApi;
+
/** Where a task came from in the app: a channel, a bot's thread, or a bot's direct chat. */
/** Where to answer a Needs-you card: the chat the card is in, else the chat the task came from. */
export function answerChat(t: Pick<Task, 'channel_id' | 'direct_kwant_id' | 'thread_id'>, n: Pick<NeedsYouItem, 'chat'>): ChatPlace | null {
diff --git a/frontend/src/truthLedger.ts b/frontend/src/truthLedger.ts
new file mode 100644
index 00000000..c9b599f8
--- /dev/null
+++ b/frontend/src/truthLedger.ts
@@ -0,0 +1,210 @@
+// Truth Ledger, Phase C2 (docs/mission-control.md, contract §2): the facts bots and the person saved,
+// labelled when unconfirmed or disputed, the disputes the person settles, and which tasks rely on a
+// fact. Shown only with the ledger `on`: off and shadow leave the app as it was.
+
+import type { MissionError } from './missions';
+
+export type LedgerSetting = 'off' | 'shadow' | 'on';
+export type FactStatus = 'proposed' | 'accepted' | 'superseded' | 'disputed';
+export type FactScope = 'bot' | 'team' | 'space';
+export type DisputeStatus = 'open' | 'resolved' | 'dismissed';
+export type DisputeCause = 'same_subject' | 'numbers_differ' | 'negation' | 'person' | 'bot';
+
+export interface Fact {
+ id: string;
+ space_id: string;
+ scope: FactScope | string;
+ scope_id: string;
+ statement: string;
+ subject: string | null;
+ source_kind: 'person' | 'bot' | 'import' | 'check' | 'task' | string;
+ source_ref: string | null;
+ author_kwant_id: string | null;
+ trust: 'person' | 'bot' | 'outside' | string;
+ status: FactStatus | string;
+ superseded_by: string | null;
+ valid_from: string;
+ valid_until: string | null;
+ memory_id: string | null;
+ pinned: boolean;
+ decided_by: string | null;
+ decided_at: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface Dispute {
+ id: string;
+ space_id?: string;
+ fact_a: string;
+ fact_b: string;
+ cause: DisputeCause | string;
+ status: DisputeStatus | string;
+ winner: string | null;
+ resolved_by: string | null;
+ created_at: string;
+ resolved_at: string | null;
+ /** Both facts, A then B; a side can be null if it was deleted. */
+ facts?: Array<Fact | null>;
+}
+
+export interface FactEvent {
+ id: number;
+ kind: string;
+ actor: string;
+ detail: string | null;
+ created_at: string;
+}
+export interface FactEvidence {
+ fact_id: string;
+ evidence_id: string | null;
+ check_id: string | null;
+ message_id: string | null;
+ added_by: string;
+ added_at: string;
+}
+export interface Citation {
+ fact_id: string;
+ cited_by_kind: 'task' | 'fact' | string;
+ cited_by_id: string;
+ created_at: string;
+}
+export interface FactDetail {
+ fact: Fact;
+ events: FactEvent[];
+ evidence: FactEvidence[];
+ citations: Citation[];
+ disputes: Dispute[];
+}
+
+/** The SSE payloads: a fact or dispute changed (the board reloads what it shows). */
+export interface FactChangedEvent {
+ id: string;
+ status?: string;
+ space_id?: string;
+ scope?: string;
+ scope_id?: string;
+ kwant_id?: string | null;
+}
+export interface FactDisputeEvent {
+ id: string;
+ status?: string;
+ space_id?: string;
+ fact_a?: string;
+ fact_b?: string;
+ cause?: string;
+ winner?: string | null;
+}
+
+export const ledgerSetting = (v: unknown): LedgerSetting => (v === 'on' || v === 'shadow' ? v : 'off');
+
+
+/** The label a fact carries in lists and prompts; none for one that simply holds. */
+export function factLabel(status: string): { text: string; tone: 'amber' | 'rose' | 'zinc' } | null {
+ switch (status) {
+ case 'proposed':
+ return { text: 'Unconfirmed', tone: 'amber' };
+ case 'disputed':
+ return { text: 'Disputed', tone: 'rose' };
+ case 'superseded':
+ return { text: 'Replaced', tone: 'zinc' };
+ default:
+ return null;
+ }
+}
+
+/** In force: what bots read (accepted, proposed with its label, disputed with its label). */
+export const factInForce = (f: Pick<Fact, 'status'>) => f.status !== 'superseded';
+
+/** Whose fact it is: "Sandy’s note", "Team Design", "Everyone in this space". */
+export function scopeText(f: Pick<Fact, 'scope' | 'scope_id'>, names: Record<string, string> = {}, teams: Record<string, string> = {}): string {
+ if (f.scope === 'bot') return `${names[f.scope_id] ?? 'A bot'}’s note`;
+ if (f.scope === 'team') return teams[f.scope_id] ? `Team ${teams[f.scope_id]}` : 'A team';
+ return 'Everyone in this space';
+}
+
+/** Where it came from, in a few words. */
+export function sourceText(f: Pick<Fact, 'source_kind' | 'trust' | 'author_kwant_id'>, names: Record<string, string> = {}): string {
+ const by = f.author_kwant_id ? names[f.author_kwant_id] ?? 'a bot' : null;
+ switch (f.source_kind) {
+ case 'person':
+ return 'You wrote it';
+ case 'import':
+ return 'Imported';
+ case 'check':
+ return 'From a passing check';
+ case 'task':
+ return by ? `From ${by}’s task` : 'From a task';
+ default:
+ return f.trust === 'outside' ? `${by ? `${by}, ` : ''}from something it read outside` : by ? `${by} saved it` : 'A bot saved it';
+ }
+}
+
+/** Why kwant thinks two facts disagree. */
+export function causeText(cause: string): string {
+ switch (cause) {
+ case 'same_subject':
+ return 'Both are about the same thing and say different things.';
+ case 'numbers_differ':
+ return 'They say nearly the same thing with different numbers.';
+ case 'negation':
+ return 'One says the opposite of the other.';
+ case 'person':
+ return 'You marked them as conflicting.';
+ case 'bot':
+ return 'A bot found they conflict.';
+ default:
+ return 'They can’t both hold.';
+ }
+}
+
+/** A dispute's outcome line once it's no longer open. */
+export function disputeOutcome(d: Pick<Dispute, 'status' | 'winner' | 'fact_a' | 'resolved_by'>, sides: Array<Fact | null | undefined>): string {
+ if (d.status === 'dismissed') return 'Not a conflict: both stand, and this pair won’t be raised again.';
+ if (d.status === 'resolved') {
+ const w = sides.find((f) => f?.id === d.winner);
+ const by = d.resolved_by && d.resolved_by !== 'person' ? ' (settled by a passing check)' : '';
+ return w ? `Settled${by}: “${w.statement}” stands; the other is replaced.` : `Settled${by}.`;
+ }
+ return 'Waiting for you.';
+}
+
+/** A 409 on resolve or dismiss: someone else (or a check) got there first, or the ledger was switched off. */
+export function disputeConflictText(e: MissionError): string {
+ switch (e.code) {
+ case 'resolved':
+ return 'Someone got there first: this one is already settled.';
+ case 'dismissed':
+ return 'Someone got there first: it’s already marked as not a conflict.';
+ default:
+ return /isn.t on/i.test(e.message) ? 'The Truth Ledger was switched off, so facts can’t be changed right now.' : e.message;
+ }
+}
+
+/** A 409 on accept/reject of an unconfirmed fact. */
+export function factConflictText(e: MissionError): string {
+ if (e.code === 'accepted') return 'Someone got there first: it’s already confirmed.';
+ if (e.code === 'superseded') return 'Someone got there first: it’s already replaced.';
+ if (e.code === 'disputed') return 'It’s disputed now: settle the dispute instead.';
+ return /isn.t on|is off/i.test(e.message) ? 'The Truth Ledger was switched off, so facts can’t be changed right now.' : e.message;
+}
+
+/** Open disputes oldest first; the facts list with disputed, then unconfirmed, then the rest (newest first). */
+export function sortFacts(list: Fact[]): Fact[] {
+ const rank = (s: string) => (s === 'disputed' ? 0 : s === 'proposed' ? 1 : s === 'superseded' ? 3 : 2);
+ return [...list].sort((a, b) => rank(a.status) - rank(b.status) || b.created_at.localeCompare(a.created_at));
+}
+
+export type FactFilter = 'all' | 'proposed' | 'disputed';
+export const filterFacts = (list: Fact[], f: FactFilter) => (f === 'all' ? list.filter(factInForce) : list.filter((x) => x.status === f));
+
+/** "Relied on by 2 tasks" (citations by tasks only; a fact citing a fact is internal). */
+export function citationText(cs: Citation[]): string {
+ const n = cs.filter((c) => c.cited_by_kind === 'task').length;
+ return n === 0 ? 'No task relies on it yet.' : `${n} ${n === 1 ? 'task relies' : 'tasks rely'} on it.`;
+}
+
+/** Needs-you kinds on tasks with the ledger on. */
+export const FACT_NEEDS_YOU = ['fact_changed', 'rests_on_disputed_fact'] as const;
+export type FactNeedsYouKind = (typeof FACT_NEEDS_YOU)[number];
+export const isFactNeedsYou = (k: string): k is FactNeedsYouKind => (FACT_NEEDS_YOU as readonly string[]).includes(k);
diff --git a/frontend/tests/truthLedger.test.mjs b/frontend/tests/truthLedger.test.mjs
new file mode 100644
index 00000000..ad217feb
--- /dev/null
+++ b/frontend/tests/truthLedger.test.mjs
@@ -0,0 +1,300 @@
+// Truth Ledger, Phase C2 (docs/mission-control.md, contract §2): the board's Facts section shows the
+// facts bots read, labelled unconfirmed or disputed, open disputes as Needs you (keep one, or not a
+// conflict), and which tasks rely on a fact. A decision another tab made first (409) says so; changes
+// arrive live. With the ledger off or in shadow, or on an older server, nothing new shows.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/s1', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const b = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { FactsLedger, FactNeedsYouAction } from './src/components/FactsLedger';
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { FactsLedger, FactNeedsYouAction } from './src/components/FactsLedger';
+ export * from './src/truthLedger';
+ export { MissionError, errorFrom, emitMission } from './src/missions';
+ export { TOAST_KINDS } from './src/continuity';
+ export const ledgerHtml = (p) => renderToStaticMarkup(React.createElement(FactsLedger, p));
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const settle = async () => {
+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const NOW = Date.parse('2026-11-01T12:00:00Z');
+const names = { k_sandy: 'Sandy', k_cody: 'Cody' };
+
+const fact = (over = {}) => ({
+ id: 'f1', space_id: 's1', scope: 'space', scope_id: 's1', statement: 'Launch day is 12 November.', subject: 'launch day',
+ source_kind: 'bot', source_ref: null, author_kwant_id: 'k_sandy', trust: 'bot', status: 'accepted', superseded_by: null,
+ valid_from: '2026-10-30T12:00:00Z', valid_until: null, memory_id: null, pinned: false, decided_by: null, decided_at: null,
+ created_at: '2026-10-30T12:00:00Z', updated_at: '2026-10-30T12:00:00Z', ...over,
+});
+const A = fact({ id: 'fa', statement: 'Launch day is 12 November.', status: 'disputed' });
+const B = fact({ id: 'fb', statement: 'Launch day is 19 November.', status: 'disputed', author_kwant_id: 'k_cody', scope: 'bot', scope_id: 'k_cody', created_at: '2026-10-31T12:00:00Z' });
+const dispute = (over = {}) => ({
+ id: 'd1', fact_a: 'fa', fact_b: 'fb', cause: 'numbers_differ', status: 'open', winner: null, resolved_by: null,
+ created_at: '2026-11-01T11:00:00Z', resolved_at: null, facts: [A, B], ...over,
+});
+const P = fact({ id: 'fp', statement: 'The newsletter goes out on Fridays.', status: 'proposed', created_at: '2026-11-01T10:00:00Z' });
+const OLD = fact({ id: 'fo', statement: 'Prices start at $9.', status: 'superseded' });
+const facts = [fact(), A, B, P, OLD];
+const initial = (over = {}) => ({ setting: 'on', facts, disputes: [dispute()], ...over });
+
+function fakeApi(over = {}) {
+ const calls = [];
+ return {
+ calls,
+ list: async () => (calls.push(['list']), { setting: 'on', facts }),
+ disputes: async (s) => (calls.push(['disputes', s]), { setting: 'on', disputes: s === 'open' ? [dispute()] : [dispute({ status: 'resolved', winner: 'fb', resolved_by: 'person' })] }),
+ get: async (id) => (calls.push(['get', id]), {
+ fact: facts.find((f) => f.id === id) ?? fact({ id }),
+ events: [], evidence: [{ fact_id: id, evidence_id: 'e1', check_id: 'c1', message_id: null, added_by: 'check', added_at: '2026-10-30T12:00:00Z' }],
+ citations: [{ fact_id: id, cited_by_kind: 'task', cited_by_id: 't1', created_at: '2026-10-31T12:00:00Z' }, { fact_id: id, cited_by_kind: 'fact', cited_by_id: 'fx', created_at: '2026-10-31T12:00:00Z' }],
+ disputes: [],
+ }),
+ resolve: async (id, winner, key) => (calls.push(['resolve', id, winner, key]), dispute({ status: 'resolved', winner, resolved_by: 'person' })),
+ dismiss: async (id, key) => (calls.push(['dismiss', id, key]), dispute({ status: 'dismissed' })),
+ accept: async (id, key) => (calls.push(['accept', id, key]), { fact: { ...P, status: 'accepted' }, events: [], evidence: [], citations: [], disputes: [] }),
+ reject: async (id, key) => (calls.push(['reject', id, key]), { fact: { ...P, status: 'superseded' }, events: [], evidence: [], citations: [], disputes: [] }),
+ uncite: async (id, taskId) => (calls.push(['uncite', id, taskId]), { ok: true }),
+ ...over,
+ };
+}
+
+async function mount(Component, props) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = b.createRoot(host);
+ root.render(b.React.createElement(Component, props));
+ await settle();
+ return {
+ host,
+ text: () => host.textContent.replace(/\s+/g, ' '),
+ click: async (sel) => {
+ const el = host.querySelector(sel);
+ assert.ok(el, `no ${sel}`);
+ el.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ },
+ done: () => {
+ root.unmount();
+ host.remove();
+ },
+ };
+}
+
+test('with the ledger off or in shadow, or on an older server, the board shows nothing new', async () => {
+ assert.equal(b.ledgerHtml({ names, initial: initial({ setting: 'off' }), api: fakeApi() }), '');
+ assert.equal(b.ledgerHtml({ names, initial: initial({ setting: 'shadow' }), api: fakeApi() }), '');
+ assert.equal(b.ledgerSetting('anything'), 'off');
+ // An older server answers 404: still nothing, not an error.
+ const gone = new b.MissionError('Not found', 404);
+ const m = await mount(b.FactsLedger, { names, api: fakeApi({ list: async () => Promise.reject(gone), disputes: async () => Promise.reject(gone) }) });
+ assert.equal(m.host.innerHTML, '');
+ m.done();
+ // Off from the server on load: nothing either.
+ const off = await mount(b.FactsLedger, { names, api: fakeApi({ list: async () => ({ setting: 'off', facts: [] }), disputes: async () => ({ setting: 'off', disputes: [] }) }) });
+ assert.equal(off.host.innerHTML, '');
+ off.done();
+});
+
+test('labels: unconfirmed in amber, disputed in rose, replaced in grey, none for a fact that holds', () => {
+ assert.deepEqual(b.factLabel('proposed'), { text: 'Unconfirmed', tone: 'amber' });
+ assert.deepEqual(b.factLabel('disputed'), { text: 'Disputed', tone: 'rose' });
+ assert.deepEqual(b.factLabel('superseded'), { text: 'Replaced', tone: 'zinc' });
+ assert.equal(b.factLabel('accepted'), null);
+ assert.equal(b.scopeText({ scope: 'bot', scope_id: 'k_cody' }, names), 'Cody’s note');
+ assert.equal(b.scopeText({ scope: 'team', scope_id: 'tm' }, names, { tm: 'Design' }), 'Team Design');
+ assert.equal(b.scopeText({ scope: 'space', scope_id: 's1' }), 'Everyone in this space');
+ assert.equal(b.sourceText({ source_kind: 'person', trust: 'person', author_kwant_id: null }), 'You wrote it');
+ assert.equal(b.sourceText({ source_kind: 'bot', trust: 'outside', author_kwant_id: 'k_sandy' }, names), 'Sandy, from something it read outside');
+ assert.equal(b.citationText([]), 'No task relies on it yet.');
+});
+
+test('an open dispute is Needs you: both facts side by side, why, keep one, or not a conflict', () => {
+ const html = b.ledgerHtml({ names, now: NOW, initial: initial(), api: fakeApi() });
+ const t = text(html);
+ assert.match(t, /Facts 4 in force · 1 unconfirmed · 2 disputed/);
+ assert.match(t, /Needs you: one dispute to settle/);
+ assert.match(t, /Two facts disagree They say nearly the same thing with different numbers\./);
+ assert.match(t, /First fact: “Launch day is 12 November\.” Everyone in this space · Sandy saved it/);
+ assert.match(t, /Second fact: “Launch day is 19 November\.” Cody’s note · Cody saved it/);
+ assert.equal((html.match(/data-keep=/g) ?? []).length, 2);
+ assert.match(html, /aria-label="Keep “Launch day is 12 November\.” and replace the other"/);
+ assert.match(t, /Not a conflict/);
+ assert.match(t, /Until you choose, bots see both, labelled disputed\./);
+ // Named for screen readers by its title; the section by its heading.
+ assert.match(html, /<li aria-labelledby="[^"]+"[^>]*data-dispute="d1" data-status="open"/);
+ assert.match(html, /<section aria-labelledby="[^"]+"[^>]*data-facts-ledger/);
+ // The facts list is behind a disclosure.
+ assert.match(html, /aria-expanded="false"[^>]*data-facts-toggle/);
+ assert.doesNotMatch(html, /data-fact="/);
+});
+
+test('the facts list: disputed, then unconfirmed, labelled; replaced ones only by filter', async () => {
+ const html = b.ledgerHtml({ names, now: NOW, initial: initial({ disputes: [] }), api: fakeApi(), defaultOpen: true });
+ const order = [...html.matchAll(/data-fact="([^"]+)"/g)].map((x) => x[1]);
+ assert.deepEqual(order, ['fb', 'fa', 'fp', 'f1']);
+ assert.match(html, /data-fact="fp" data-status="proposed".*?data-fact-label="proposed"[^>]*>Unconfirmed/);
+ assert.match(html, /data-fact="fa" data-status="disputed".*?data-fact-label="disputed"[^>]*>Disputed/);
+ assert.doesNotMatch(html, /Prices start at/);
+ assert.match(html, /aria-pressed="true"[^>]*data-filter="all"/);
+ assert.doesNotMatch(text(html), /Needs you/);
+
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial({ disputes: [] }), api: fakeApi(), defaultOpen: true });
+ await m.click('[data-filter="proposed"]');
+ assert.deepEqual([...m.host.querySelectorAll('[data-fact]')].map((x) => x.dataset.fact), ['fp']);
+ await m.click('[data-filter="disputed"]');
+ assert.deepEqual([...m.host.querySelectorAll('[data-fact]')].map((x) => x.dataset.fact), ['fb', 'fa']);
+ m.done();
+
+ // An empty ledger says so.
+ const empty = text(b.ledgerHtml({ names, initial: initial({ facts: [], disputes: [] }), api: fakeApi(), defaultOpen: true }));
+ assert.match(empty, /Facts None saved yet/);
+ assert.match(empty, /No facts yet\. When a bot saves a note or you write a shared fact, it shows here\./);
+});
+
+test('details show which tasks rely on a fact, its evidence, and open the task', async () => {
+ const api = fakeApi();
+ const opened = [];
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial({ disputes: [] }), api, defaultOpen: true, taskTitles: { t1: 'Write the launch post' }, onOpenTask: (id) => opened.push(id) });
+ const toggle = m.host.querySelector('[data-fact="f1"] [data-fact-toggle]');
+ assert.equal(toggle.getAttribute('aria-expanded'), 'false');
+ toggle.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ assert.equal(toggle.getAttribute('aria-expanded'), 'true');
+ assert.deepEqual(api.calls.at(-1), ['get', 'f1']);
+ const d = m.host.querySelector('[data-fact-detail="f1"]').textContent;
+ // A fact citing a fact is internal: one task, not two.
+ assert.match(d, /1 task relies on it\./);
+ assert.match(d, /Write the launch post/);
+ assert.match(d, /Backed by 1 piece of evidence, including a check\./);
+ m.host.querySelector('[data-fact-detail="f1"] ul button').dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ assert.deepEqual(opened, ['t1']);
+ m.done();
+});
+
+test('keeping one fact resolves the dispute once, then shows the outcome', async () => {
+ const api = fakeApi();
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial(), api });
+ await m.click('[data-keep="fb"]');
+ const r = api.calls.find((c) => c[0] === 'resolve');
+ assert.equal(r[1], 'd1');
+ assert.equal(r[2], 'fb');
+ assert.ok(r[3], 'sends an idempotency key');
+ assert.match(m.text(), /Settled: “Launch day is 19 November\.” stands; the other is replaced\./);
+ assert.equal(m.host.querySelector('[data-keep]'), null);
+ assert.match(m.text(), /All settled\./);
+ m.done();
+});
+
+test('not a conflict dismisses; a failed press retries with the same key', async () => {
+ let fail = true;
+ const keys = [];
+ const api = fakeApi({
+ dismiss: async (id, key) => {
+ keys.push(key);
+ if (fail) {
+ fail = false;
+ throw new b.MissionError('Network down', 0);
+ }
+ return dispute({ status: 'dismissed' });
+ },
+ });
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial(), api });
+ await m.click('[data-dismiss]');
+ assert.match(m.host.querySelector('[data-dispute-error]').textContent, /Network down/);
+ await m.click('[data-dismiss]');
+ assert.equal(keys.length, 2);
+ assert.equal(keys[0], keys[1]);
+ assert.match(m.text(), /Not a conflict: both stand, and this pair won’t be raised again\./);
+ m.done();
+});
+
+test('a dispute someone else settled first (409) says so and shows what holds now', async () => {
+ const conflict = b.errorFrom(409, { error: 'this dispute is already resolved', status: 'resolved' });
+ assert.equal(conflict.code, 'resolved');
+ assert.equal(b.disputeConflictText(conflict), 'Someone got there first: this one is already settled.');
+ assert.equal(b.disputeConflictText(new b.MissionError('the Truth Ledger isn’t on', 409)), 'The Truth Ledger was switched off, so facts can’t be changed right now.');
+ const api = fakeApi({ resolve: async () => Promise.reject(conflict) });
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial(), api });
+ await m.click('[data-keep="fa"]');
+ assert.equal(m.host.querySelector('[role="alert"]').textContent.trim(), 'Someone got there first: this one is already settled.');
+ assert.ok(api.calls.some((c) => c[0] === 'disputes' && c[1] === 'all'));
+ assert.match(m.text(), /Settled: “Launch day is 19 November\.” stands/);
+ m.done();
+});
+
+test('an unconfirmed fact can be confirmed or rejected; a 409 explains', async () => {
+ const api = fakeApi();
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial({ disputes: [] }), api, defaultOpen: true });
+ await m.click('[data-fact="fp"] [data-fact-toggle]');
+ assert.match(m.host.querySelector('[data-fact="fp"]').innerHTML, /role="group" aria-label="Unconfirmed: The newsletter goes out on Fridays\."/);
+ await m.click('[data-confirm-fact]');
+ const a = api.calls.find((c) => c[0] === 'accept');
+ assert.equal(a[1], 'fp');
+ assert.ok(a[2]);
+ assert.match(m.text(), /Confirmed: bots now read it without the label\./);
+ m.done();
+
+ assert.equal(b.factConflictText(b.errorFrom(409, { error: 'this fact is already accepted', status: 'accepted' })), 'Someone got there first: it’s already confirmed.');
+ const m2 = await mount(b.FactsLedger, {
+ names, now: NOW, initial: initial({ disputes: [] }), defaultOpen: true,
+ api: fakeApi({ reject: async () => Promise.reject(b.errorFrom(409, { error: 'this fact is already disputed', status: 'disputed' })) }),
+ });
+ await m2.click('[data-fact="fp"] [data-fact-toggle]');
+ await m2.click('[data-reject-fact]');
+ assert.match(m2.host.querySelector('[role="alert"]').textContent, /It’s disputed now: settle the dispute instead\./);
+ m2.done();
+});
+
+test('live: fact_changed and fact_dispute reload once per burst', async () => {
+ const api = fakeApi();
+ const m = await mount(b.FactsLedger, { names, now: NOW, initial: initial(), api });
+ const before = api.calls.filter((c) => c[0] === 'list').length;
+ b.emitMission({ type: 'fact_changed', data: { id: 'fa', status: 'superseded' } });
+ b.emitMission({ type: 'fact_dispute', data: { id: 'd1', status: 'resolved' } });
+ b.emitMission({ type: 'fact_changed', data: { id: 'fb', status: 'accepted' } });
+ await new Promise((r) => setTimeout(r, 350));
+ await settle();
+ assert.equal(api.calls.filter((c) => c[0] === 'list').length - before, 1);
+ m.done();
+});
+
+test('a task whose fact changed can stop relying on it; a disputed one points to Facts', async () => {
+ const api = fakeApi();
+ const m = await mount(b.FactNeedsYouAction, { taskId: 't1', item: { kind: 'fact_changed', id: 'n1', fact_id: 'fa' }, api });
+ await m.click('[data-uncite]');
+ assert.deepEqual(api.calls.at(-1), ['uncite', 'fa', 't1']);
+ assert.match(m.text(), /Done: this task no longer relies on it\./);
+ m.done();
+ const d = await mount(b.FactNeedsYouAction, { taskId: 't1', item: { kind: 'rests_on_disputed_fact', id: 'n2', fact_id: 'fa' }, api });
+ assert.match(d.text(), /Settle it under Facts on the board\./);
+ d.done();
+});
+
+test('wiring: the board shows Facts under the week strip, tasks label fact needs-you, a dispute notification opens the board', () => {
+ const board = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');
+ // Measures (Insights) may sit between the week strip and Facts.
+ assert.match(board, /<InsightsStrip [^>]*\/>\s*(?:<MeasuresPanel [^>]*\/>\s*)?<FactsLedger /);
+ assert.match(board, /'A fact changed'/);
+ assert.match(board, /'Rests on a disputed fact'/);
+ assert.match(board, /isFactNeedsYou\(n\.kind\) \? \(\s*<FactNeedsYouAction /);
+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ assert.match(app, /case 'fact_changed':/);
+ assert.match(app, /case 'fact_dispute':/);
+ assert.match(app, /n\.kind === 'fact_disputed'\) openBoardForTier\(\)/);
+ assert.ok(b.TOAST_KINDS.includes('fact_disputed'));
+});