Open-source SEO, GEO, and marketing skills for AI agents.
feat(goals): add grouped metric dashboards (#97)
Yuting Zhong18a0252f1eb1
diff --git a/notfair/src/app/(app)/[project]/goals/page.tsx b/notfair/src/app/(app)/[project]/goals/page.tsxindex 48b5c54c..99c0a521 100644--- a/notfair/src/app/(app)/[project]/goals/page.tsx+++ b/notfair/src/app/(app)/[project]/goals/page.tsx@@ -7,6 +7,14 @@ import { getPinnedGoalIds, listGoals } from "@/server/db/goals";import { projectHref } from "@/lib/project-href";import { goalLabel } from "@/lib/goal-label";import { GoalsBoard, type BoardGoal } from "@/components/goals-board";+import {+ listGoalGroupMemberships,+ listGoalGroups,+ listGoalsInGroup,+} from "@/server/db/goal-groups";+import { countGoalGroupHealth } from "@/lib/goal-group-health";+import { GoalGroupsOverview, type GoalGroupOverviewRow } from "@/components/goal-groups-overview";+import { GoalGroupEditor, type GoalGroupEditorGoal } from "@/components/goal-group-editor";export const dynamic = "force-dynamic";@@ -28,10 +36,16 @@ export default async function AllGoalsPage({const agents = await listProjectAgents(slug);const agentById = new Map(agents.map((a) => [a.agent_id, a]));const pinnedIds = getPinnedGoalIds(slug);+ const projectGoals = listGoals(slug);+ const groups = listGoalGroups(slug);+ const membershipByGoal = new Map(+ listGoalGroupMemberships(slug).map((membership) => [membership.goal_id, membership.group_id]),+ );+ const groupById = new Map(groups.map((group) => [group.id, group.name]));// Plain-JSON card props for the client board. Goals whose agent sidecar// is missing (half-deleted workspace) have no page to link to — skip.- const goals = listGoals(slug).flatMap<BoardGoal>((g) => {+ const goals = projectGoals.flatMap<BoardGoal>((g) => {const agent = agentById.get(g.agent_id);if (!agent) return [];return [@@ -56,6 +70,31 @@ export default async function AllGoalsPage({];});+ const groupRows: GoalGroupOverviewRow[] = groups.map((group) => {+ const members = listGoalsInGroup(group.id);+ const counts = countGoalGroupHealth(members);+ return {+ id: group.id,+ href: projectHref(slug, `/groups/${group.id}`),+ name: group.name,+ description: group.description,+ goal_count: members.length,+ healthy_count: counts.healthy,+ attention_count: counts.attention,+ waiting_count: counts.waiting + counts.paused,+ };+ });+ const editorGoals: GoalGroupEditorGoal[] = projectGoals.map((goal) => {+ const groupId = membershipByGoal.get(goal.id) ?? null;+ return {+ id: goal.id,+ label: goalLabel(goal),+ status: goal.status,+ current_group_id: groupId,+ current_group_name: groupId ? groupById.get(groupId) ?? null : null,+ };+ });+// Anchored to the viewport region (like the goal screen) so the column// strip scrolls inside the page instead of stretching SidebarInset — a// flex item with no min-width — and dragging the whole body sideways.@@ -69,12 +108,23 @@ export default async function AllGoalsPage({filter by status, click through for the full story.</p></div>- <Link href={projectHref(slug, "")} className="ns-btn ns-btn-primary shrink-0">- <Plus className="size-3.5" />- New goal- </Link>+ <div className="ns-page-actions">+ <GoalGroupEditor projectSlug={slug} goals={editorGoals} />+ <Link href={projectHref(slug, "")} className="ns-btn ns-btn-ghost shrink-0">+ <Plus className="size-3.5" />+ New goal+ </Link>+ </div></header>+ <section className="mb-7" aria-labelledby="goal-groups-heading">+ <h2 id="goal-groups-heading" className="ns-h2 mt-0">+ <span>Groups</span>+ <span className="ns-h2-meta">Dashboards for related goals</span>+ </h2>+ <GoalGroupsOverview groups={groupRows} />+ </section>+{goals.length === 0 ? (<div className="ns-card p-8 text-center"><p className="m-0 text-[13.5px] text-[hsl(var(--notfair-ink-3))]">diff --git a/notfair/src/app/(app)/[project]/groups/[group]/page.tsx b/notfair/src/app/(app)/[project]/groups/[group]/page.tsxnew file mode 100644index 00000000..2f135afc--- /dev/null+++ b/notfair/src/app/(app)/[project]/groups/[group]/page.tsx@@ -0,0 +1,116 @@+import { notFound } from "next/navigation";+import { getProject } from "@/server/db/projects";+import {+ getGoalGroup,+ listGoalGroupMemberships,+ listGoalGroups,+ listGoalsInGroup,+} from "@/server/db/goal-groups";+import { listGoals, listGoalTicks, listMetricSnapshots } from "@/server/db/goals";+import { listProjectAgents } from "@/server/agent-meta";+import { goalLabel } from "@/lib/goal-label";+import { projectHref } from "@/lib/project-href";+import { GoalGroupEditor, type GoalGroupEditorGoal } from "@/components/goal-group-editor";+import {+ GoalGroupDashboard,+ type GoalGroupActivity,+ type GoalGroupDashboardGoal,+} from "@/components/goal-group-dashboard";+import { GoalAutoRefresh } from "@/components/goal-auto-refresh";++export const dynamic = "force-dynamic";++export default async function GoalGroupPage({+ params,+}: {+ params: Promise<{ project: string; group: string }>;+}) {+ const { project: slug, group: groupId } = await params;+ const project = getProject(slug);+ const group = getGoalGroup(groupId);+ if (!project || project.archived_at || !group || group.project_slug !== slug) notFound();++ const agents = await listProjectAgents(slug);+ const agentById = new Map(agents.map((agent) => [agent.agent_id, agent]));+ const members = listGoalsInGroup(group.id);+ const dashboardGoals = members.flatMap<GoalGroupDashboardGoal>((goal) => {+ const agent = agentById.get(goal.agent_id);+ if (!agent) return [];+ return [{+ id: goal.id,+ href: projectHref(slug, `/goals/${agent.slug}`),+ label: goalLabel(goal),+ statement: goal.statement,+ status: goal.status,+ status_reason: goal.status_reason,+ metric_name: goal.metric_name,+ current_value: goal.current_value,+ target_value: goal.target_value,+ metric_direction: goal.metric_direction,+ cadence_cron: goal.cadence_cron,+ last_tick_at: goal.last_tick_at,+ next_tick_at: goal.next_tick_at,+ tick_count: goal.tick_count,+ snapshots: listMetricSnapshots(goal.id, 120).map((snapshot) => snapshot.value),+ }];+ });++ const dashboardById = new Map(dashboardGoals.map((goal) => [goal.id, goal]));+ const activity = members+ .flatMap<GoalGroupActivity>((goal) => {+ const display = dashboardById.get(goal.id);+ if (!display) return [];+ return listGoalTicks(goal.id, 8).map((tick) => ({+ id: tick.id,+ goal_id: goal.id,+ goal_href: display.href,+ goal_label: display.label,+ tick_number: tick.tick_number,+ status: tick.status,+ metric_value: tick.metric_value,+ metric_error: tick.metric_error,+ summary: tick.summary,+ started_at: tick.started_at,+ }));+ })+ .sort((a, b) => b.started_at.localeCompare(a.started_at))+ .slice(0, 20);++ const groups = listGoalGroups(slug);+ const groupById = new Map(groups.map((item) => [item.id, item.name]));+ const membershipByGoal = new Map(+ listGoalGroupMemberships(slug).map((membership) => [membership.goal_id, membership.group_id]),+ );+ const editorGoals: GoalGroupEditorGoal[] = listGoals(slug).map((goal) => {+ const currentGroupId = membershipByGoal.get(goal.id) ?? null;+ return {+ id: goal.id,+ label: goalLabel(goal),+ status: goal.status,+ current_group_id: currentGroupId,+ current_group_name: currentGroupId ? groupById.get(currentGroupId) ?? null : null,+ };+ });++ return (+ <>+ {dashboardGoals.some((goal) => goal.status === "active") && (+ <GoalAutoRefresh intervalMs={60_000} />+ )}+ <GoalGroupDashboard+ name={group.name}+ description={group.description}+ allGoalsHref={projectHref(slug, "/goals")}+ goals={dashboardGoals}+ activity={activity}+ actions={+ <GoalGroupEditor+ projectSlug={slug}+ goals={editorGoals}+ group={{ id: group.id, name: group.name, description: group.description }}+ />+ }+ />+ </>+ );+}diff --git a/notfair/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsxindex 9579a009..2941e86f 100644--- a/notfair/src/components/app-sidebar.tsx+++ b/notfair/src/components/app-sidebar.tsx@@ -1,4 +1,5 @@import Link from "next/link";+import { Fragment } from "react";import {Sidebar,SidebarContent,@@ -13,7 +14,7 @@ import {SidebarTrigger,} from "@/components/ui/sidebar";import { SidebarBrand } from "@/components/sidebar-brand";-import { BookOpen, LayoutGrid, Plug, Plus, Settings, type LucideIcon } from "lucide-react";+import { BookOpen, FolderKanban, LayoutGrid, Plug, Plus, Settings, type LucideIcon } from "lucide-react";import { listProjects } from "@/server/db/projects";import { getActiveProject } from "@/server/active-project";import { listProjectAgents } from "@/server/agent-meta";@@ -32,6 +33,7 @@ import { ProjectSwitcher } from "./project-switcher";import { HarnessFooter } from "./harness-footer";import { SidebarVersion } from "./sidebar-version";import { ThemeToggle } from "./theme-toggle";+import { listGoalGroupMemberships, listGoalGroups } from "@/server/db/goal-groups";type NavItem = {href: string;@@ -68,6 +70,10 @@ export async function AppSidebar() {...liveGoals.filter((g) => !pinnedIds.has(g.id)),];const totalGoals = active ? listGoals(active.slug).length : 0;+ const goalGroups = active ? listGoalGroups(active.slug) : [];+ const memberships = active ? listGoalGroupMemberships(active.slug) : [];+ const groupIdByGoal = new Map(memberships.map((membership) => [membership.goal_id, membership.group_id]));+ const ungroupedRailGoals = railGoals.filter((goal) => !groupIdByGoal.has(goal.id));const agentBySlug = new Map(agentEntries.map((a) => [a.agent_id, a]));// Best-effort fetch of harness usage. For Codex this hits the// chatgpt.com wham/usage endpoint (cached 60s in-process); for@@ -114,7 +120,7 @@ export async function AppSidebar() {</Link></SidebarMenuButton></SidebarMenuItem>- {railGoals.map((goal) => {+ {ungroupedRailGoals.map((goal) => {const agent = agentBySlug.get(goal.agent_id);if (!agent) return null;const color = colorForAgentSlug(agent.slug);@@ -150,6 +156,54 @@ export async function AppSidebar() {</SidebarGroup>)}+ {active && goalGroups.length > 0 && (+ <SidebarGroup>+ <SidebarGroupLabel>Groups</SidebarGroupLabel>+ <SidebarGroupContent>+ <SidebarMenu>+ {goalGroups.map((group) => {+ const groupGoals = railGoals.filter((goal) => groupIdByGoal.get(goal.id) === group.id);+ const totalMembers = memberships.filter((membership) => membership.group_id === group.id).length;+ return (+ <Fragment key={group.id}>+ <SidebarMenuItem>+ <SidebarMenuButton asChild>+ <Link href={projectHref(active.slug, `/groups/${group.id}`)}>+ <FolderKanban />+ <span className="truncate">{group.name}</span>+ <span className="ml-auto text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">+ {totalMembers}+ </span>+ </Link>+ </SidebarMenuButton>+ </SidebarMenuItem>+ {groupGoals.map((goal) => {+ const agent = agentBySlug.get(goal.agent_id);+ if (!agent) return null;+ const color = colorForAgentSlug(agent.slug);+ return (+ <SidebarGoalItem+ key={goal.id}+ href={projectHref(active.slug, `/goals/${agent.slug}`)}+ homeHref={projectHref(active.slug, "")}+ goalId={goal.id}+ label={goalLabel(goal)}+ status={goal.status as "intake" | "proposed" | "active" | "paused"}+ pinned={pinnedIds.has(goal.id)}+ dotClass={GOAL_DOT[goal.status] ?? "ns-dot-mute"}+ labelClass={color.label}+ nested+ />+ );+ })}+ </Fragment>+ );+ })}+ </SidebarMenu>+ </SidebarGroupContent>+ </SidebarGroup>+ )}+{active && (<SidebarGroup><SidebarGroupLabel>Workspace</SidebarGroupLabel>diff --git a/notfair/src/components/goal-group-dashboard.test.tsx b/notfair/src/components/goal-group-dashboard.test.tsxnew file mode 100644index 00000000..3fb00eaa--- /dev/null+++ b/notfair/src/components/goal-group-dashboard.test.tsx@@ -0,0 +1,73 @@+// @vitest-environment jsdom+import { describe, expect, it } from "vitest";+import { render, screen, within } from "@testing-library/react";+import { GoalGroupDashboard, type GoalGroupDashboardGoal } from "./goal-group-dashboard";++function goal(overrides: Partial<GoalGroupDashboardGoal>): GoalGroupDashboardGoal {+ return {+ id: "g1",+ href: "/project/goals/goal-1",+ label: "Google Ads errors <2%",+ statement: "Keep errors low",+ status: "active",+ status_reason: null,+ metric_name: "Authenticated tool-call error rate",+ current_value: 1.77,+ target_value: 2,+ metric_direction: "decrease",+ cadence_cron: "0 * * * *",+ last_tick_at: "2026-07-17T20:00:00.000Z",+ next_tick_at: "2026-07-17T22:00:00.000Z",+ tick_count: 5,+ snapshots: [2.4, 1.9, 1.77],+ ...overrides,+ };+}++describe("GoalGroupDashboard", () => {+ it("shows every member metric with its own target and health", () => {+ render(+ <GoalGroupDashboard+ name="Ads MCP reliability"+ description="Keep ads connections healthy."+ allGoalsHref="/project/goals"+ goals={[+ goal({ id: "google" }),+ goal({+ id: "meta",+ href: "/project/goals/goal-2",+ label: "Meta MCP errors <5%",+ current_value: 29.75,+ target_value: 5,+ snapshots: [8, 12, 29.75],+ }),+ ]}+ activity={[]}+ />,+ );++ expect(screen.getByText("1 healthy")).toBeTruthy();+ expect(screen.getByText("1 needs attention")).toBeTruthy();+ const google = screen.getByRole("link", { name: /Google Ads errors/ });+ const meta = screen.getByRole("link", { name: /Meta MCP errors/ });+ expect(within(google).getByText("1.77")).toBeTruthy();+ expect(within(google).getByText("≤ 2")).toBeTruthy();+ expect(within(meta).getByText("29.75")).toBeTruthy();+ expect(within(meta).getByText("≤ 5")).toBeTruthy();+ });++ it("provides an actionable empty state", () => {+ render(+ <GoalGroupDashboard+ name="Empty"+ description=""+ allGoalsHref="/project/goals"+ goals={[]}+ activity={[]}+ actions={<button>Manage group</button>}+ />,+ );+ expect(screen.getByText("This group is ready for goals.")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Manage group" })).toBeTruthy();+ });+});diff --git a/notfair/src/components/goal-group-dashboard.tsx b/notfair/src/components/goal-group-dashboard.tsxnew file mode 100644index 00000000..c034bf2a--- /dev/null+++ b/notfair/src/components/goal-group-dashboard.tsx@@ -0,0 +1,271 @@+import Link from "next/link";+import { Activity, ArrowLeft, Clock3 } from "lucide-react";+import { GoalSparkline } from "@/components/goal-sparkline";+import { formatMetric } from "@/lib/format-metric";+import { goalGroupHealth, countGoalGroupHealth } from "@/lib/goal-group-health";+import { cadenceLabel } from "@/lib/goal-cadence";+import { timeAgo, timeUntil } from "@/lib/time-ago";+import { cn } from "@/lib/utils";+import { type GoalStatus, type GoalTickStatus, type MetricDirection } from "@/server/db/goals";+import { type ReactNode } from "react";++export type GoalGroupDashboardGoal = {+ id: string;+ href: string;+ label: string;+ statement: string;+ status: GoalStatus;+ status_reason: string | null;+ metric_name: string | null;+ current_value: number | null;+ target_value: number | null;+ metric_direction: MetricDirection | null;+ cadence_cron: string;+ last_tick_at: string | null;+ next_tick_at: string | null;+ tick_count: number;+ snapshots: number[];+};++export type GoalGroupActivity = {+ id: string;+ goal_id: string;+ goal_href: string;+ goal_label: string;+ tick_number: number;+ status: GoalTickStatus;+ metric_value: number | null;+ metric_error: string | null;+ summary: string | null;+ started_at: string;+};++const HEALTH_COPY = {+ healthy: { label: "healthy", dot: "ns-dot-live", text: "text-[hsl(var(--notfair-accent))]" },+ attention: { label: "needs attention", dot: "ns-dot-err", text: "text-[hsl(var(--destructive))]" },+ waiting: { label: "waiting for data", dot: "ns-dot-warn", text: "text-[hsl(var(--notfair-warn))]" },+ paused: { label: "paused", dot: "ns-dot-mute", text: "text-[hsl(var(--notfair-ink-4))]" },+ closed: { label: "closed", dot: "ns-dot-mute", text: "text-[hsl(var(--notfair-ink-4))]" },+} as const;++function latestIso(values: Array<string | null>): string | null {+ return values.filter((value): value is string => Boolean(value)).sort().at(-1) ?? null;+}++function earliestIso(values: Array<string | null>): string | null {+ return values.filter((value): value is string => Boolean(value)).sort().at(0) ?? null;+}++function plainSummary(value: string): string {+ return value+ .replace(/\*\*([^*]+)\*\*/g, "$1")+ .replace(/`([^`]+)`/g, "$1")+ .replace(/\s+/g, " ")+ .trim();+}++export function GoalGroupDashboard({+ name,+ description,+ allGoalsHref,+ goals,+ activity,+ actions,+}: {+ name: string;+ description: string;+ allGoalsHref: string;+ goals: GoalGroupDashboardGoal[];+ activity: GoalGroupActivity[];+ actions?: ReactNode;+}) {+ const counts = countGoalGroupHealth(goals);+ const latestCheck = latestIso(goals.map((goal) => goal.last_tick_at));+ const nextCheck = earliestIso(goals.map((goal) => goal.next_tick_at));++ return (+ <div className="ns-app-wide">+ <Link+ href={allGoalsHref}+ className="mb-5 inline-flex items-center gap-1.5 text-[12.5px] text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink-2))]"+ >+ <ArrowLeft className="size-3.5" />+ All goals+ </Link>+ <header className="ns-page-head">+ <div className="ns-page-head-stack">+ <div className="mb-2 flex flex-wrap items-center gap-2">+ <span className="ns-tag-mono">goal group</span>+ <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">+ {goals.length} goal{goals.length === 1 ? "" : "s"}+ </span>+ </div>+ <h1 className="ns-page-title">{name}</h1>+ <p className="ns-page-sub">{description || "A shared dashboard for related goals."}</p>+ </div>+ <div className="ns-page-actions">{actions}</div>+ </header>++ {goals.length === 0 ? (+ <div className="ns-empty">+ <p className="ns-empty-title">This group is ready for goals.</p>+ <p className="ns-empty-sub">+ Use Manage group to add existing goals. Their schedules and history stay unchanged.+ </p>+ </div>+ ) : (+ <>+ <section+ aria-label="Group health summary"+ className="mb-7 flex flex-wrap items-center gap-x-5 gap-y-2 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)] px-4 py-3 text-[12px]"+ >+ {counts.healthy > 0 && (+ <span className="flex items-center gap-1.5 text-[hsl(var(--notfair-accent))]">+ <span className="ns-dot ns-dot-live" aria-hidden />+ {counts.healthy} healthy+ </span>+ )}+ {counts.attention > 0 && (+ <span className="flex items-center gap-1.5 text-[hsl(var(--destructive))]">+ <span className="ns-dot ns-dot-err" aria-hidden />+ {counts.attention} need{counts.attention === 1 ? "s" : ""} attention+ </span>+ )}+ {counts.waiting > 0 && <span className="text-[hsl(var(--notfair-ink-4))]">{counts.waiting} waiting for data</span>}+ {counts.paused > 0 && <span className="text-[hsl(var(--notfair-ink-4))]">{counts.paused} paused</span>}+ <span className="ml-auto flex items-center gap-1.5 font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">+ <Clock3 className="size-3" />+ {latestCheck ? `last check ${timeAgo(latestCheck)}` : "no checks yet"}+ {nextCheck ? ` · next ${timeUntil(nextCheck)}` : ""}+ </span>+ </section>++ <section aria-labelledby="group-metrics-heading">+ <h2 id="group-metrics-heading" className="ns-h2">+ <span>Metrics</span>+ <span className="ns-h2-meta">Each goal keeps its own threshold</span>+ </h2>+ <ol className="ns-group">+ {goals.map((goal) => {+ const health = goalGroupHealth(goal);+ const healthCopy = HEALTH_COPY[health];+ const comparator = goal.metric_direction === "decrease" ? "≤" : "≥";+ return (+ <li key={goal.id}>+ <Link+ href={goal.href}+ className="grid min-h-[116px] grid-cols-1 items-center gap-4 px-4 py-4 transition-colors hover:bg-[hsl(var(--notfair-hover))] sm:grid-cols-[minmax(0,1.25fr)_150px_180px_auto]"+ >+ <span className="min-w-0">+ <span className="mb-1 flex items-center gap-2">+ <span className={cn("ns-dot", healthCopy.dot)} aria-hidden />+ <span className="truncate text-[13.5px] font-medium">{goal.label}</span>+ </span>+ <span className="block truncate text-[11.5px] text-[hsl(var(--notfair-ink-4))]">+ {goal.metric_name ?? "Metric is still being defined"}+ </span>+ <span className="mt-2 block font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">+ {cadenceLabel(goal.cadence_cron)} · {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"}+ </span>+ </span>++ <span>+ <span className="block font-mono text-[10px] uppercase tracking-[0.06em] text-[hsl(var(--notfair-ink-4))]">+ current / target+ </span>+ <span className="mt-1 block text-[20px] font-semibold tabular-nums tracking-[-0.02em]">+ {formatMetric(goal.current_value)}+ <span className="ml-1.5 text-[12px] font-normal text-[hsl(var(--notfair-ink-4))]">+ {goal.target_value === null ? "no target" : `${comparator} ${formatMetric(goal.target_value)}`}+ </span>+ </span>+ </span>++ <span className="hidden sm:block" aria-label={`${goal.label} metric history`}>+ {goal.snapshots.length >= 2 ? (+ <GoalSparkline+ values={goal.snapshots}+ target={goal.target_value}+ direction={goal.metric_direction}+ width={180}+ height={44}+ />+ ) : (+ <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">+ History appears after 2 readings+ </span>+ )}+ </span>++ <span className={cn("justify-self-start whitespace-nowrap text-[11.5px] sm:justify-self-end", healthCopy.text)}>+ {healthCopy.label} <span className="ml-1 text-[hsl(var(--notfair-ink-4))]">›</span>+ </span>+ </Link>+ </li>+ );+ })}+ </ol>+ </section>++ <section aria-labelledby="group-activity-heading">+ <h2 id="group-activity-heading" className="ns-h2">+ <span>Recent checks</span>+ <span className="ns-h2-meta">Across this group</span>+ </h2>+ {activity.length === 0 ? (+ <div className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.45)] px-4 py-5 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">+ No checks yet. Activity appears here when a member goal runs its heartbeat.+ </div>+ ) : (+ <ol className="ns-group">+ {activity.map((item) => {+ const failed = item.status === "failed" || Boolean(item.metric_error);+ const running = item.status === "running";+ return (+ <li key={item.id}>+ <Link href={item.goal_href} className="ns-row-button">+ <span className="ns-glyph" aria-hidden>+ <Activity className="size-4" />+ </span>+ <span className="ns-row-body min-w-0">+ <span className="ns-row-title-row">+ <span className="ns-row-title">{item.goal_label}</span>+ <span className="ns-tag-mono">check {item.tick_number}</span>+ </span>+ <span className="ns-row-desc block truncate">+ {plainSummary(item.metric_error || item.summary || (running ? "Check is running…" : "Metric recorded"))}+ </span>+ </span>+ <span className="ml-auto flex shrink-0 items-center gap-3 text-[11px]">+ {item.metric_value !== null && (+ <span className="font-mono tabular-nums text-[hsl(var(--notfair-ink-3))]">+ {formatMetric(item.metric_value)}+ </span>+ )}+ <span+ className={cn(+ "flex items-center gap-1.5",+ failed+ ? "text-[hsl(var(--destructive))]"+ : running+ ? "text-[hsl(var(--notfair-warn))]"+ : "text-[hsl(var(--notfair-accent))]",+ )}+ >+ <span className={cn("ns-dot", failed ? "ns-dot-err" : running ? "ns-dot-warn" : "ns-dot-live")} aria-hidden />+ {running ? "running" : failed ? "failed" : "done"}+ </span>+ <span className="font-mono text-[hsl(var(--notfair-ink-4))]">{timeAgo(item.started_at)}</span>+ </span>+ </Link>+ </li>+ );+ })}+ </ol>+ )}+ </section>+ </>+ )}+ </div>+ );+}diff --git a/notfair/src/components/goal-group-editor.tsx b/notfair/src/components/goal-group-editor.tsxnew file mode 100644index 00000000..07ee2701--- /dev/null+++ b/notfair/src/components/goal-group-editor.tsx@@ -0,0 +1,239 @@+"use client";++import { useState, useTransition } from "react";+import { useRouter } from "next/navigation";+import { FolderPlus, Settings2, Trash2 } from "lucide-react";+import { toast } from "sonner";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import {+ createGoalGroupAction,+ deleteGoalGroupAction,+ saveGoalGroupAction,+} from "@/server/actions/goal-groups";+import { projectHref } from "@/lib/project-href";++export type GoalGroupEditorGoal = {+ id: string;+ label: string;+ status: string;+ current_group_id: string | null;+ current_group_name: string | null;+};++export function GoalGroupEditor({+ projectSlug,+ goals,+ group,+}: {+ projectSlug: string;+ goals: GoalGroupEditorGoal[];+ group?: { id: string; name: string; description: string };+}) {+ const router = useRouter();+ const editing = Boolean(group);+ const initialSelected = goals+ .filter((goal) => goal.current_group_id === group?.id)+ .map((goal) => goal.id);+ const [open, setOpen] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const [name, setName] = useState(group?.name ?? "");+ const [description, setDescription] = useState(group?.description ?? "");+ const [selected, setSelected] = useState<Set<string>>(() => new Set(initialSelected));+ const [pending, startTransition] = useTransition();++ function reset() {+ setName(group?.name ?? "");+ setDescription(group?.description ?? "");+ setSelected(new Set(initialSelected));+ setConfirmDelete(false);+ }++ function toggle(goalId: string) {+ setSelected((current) => {+ const next = new Set(current);+ if (next.has(goalId)) next.delete(goalId);+ else next.add(goalId);+ return next;+ });+ }++ function submit() {+ startTransition(async () => {+ const result = group+ ? await saveGoalGroupAction({+ group_id: group.id,+ name,+ description,+ goal_ids: [...selected],+ })+ : await createGoalGroupAction({+ project_slug: projectSlug,+ name,+ description,+ goal_ids: [...selected],+ });+ if (!result.ok || !result.group_id) {+ toast.error(result.error ?? "Could not save the group.");+ return;+ }+ toast.success(group ? "Group updated." : "Group created.");+ setOpen(false);+ router.push(projectHref(projectSlug, `/groups/${result.group_id}`));+ router.refresh();+ });+ }++ function remove() {+ if (!group) return;+ startTransition(async () => {+ const result = await deleteGoalGroupAction(group.id);+ if (!result.ok) {+ toast.error(result.error ?? "Could not delete the group.");+ return;+ }+ toast.success("Group deleted. Its goals are now ungrouped.");+ setOpen(false);+ router.push(projectHref(projectSlug, "/goals"));+ router.refresh();+ });+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (next) reset();+ }}+ >+ <DialogTrigger asChild>+ <button type="button" className={editing ? "ns-btn ns-btn-ghost" : "ns-btn ns-btn-primary"}>+ {editing ? <Settings2 className="size-3.5" /> : <FolderPlus className="size-3.5" />}+ {editing ? "Manage group" : "New group"}+ </button>+ </DialogTrigger>+ <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>{editing ? "Manage goal group" : "Create a goal group"}</DialogTitle>+ <DialogDescription>+ A group is one dashboard for related goals. Moving a goal here removes it from+ its previous group, but never changes its heartbeat or history.+ </DialogDescription>+ </DialogHeader>++ <form+ onSubmit={(event) => {+ event.preventDefault();+ submit();+ }}+ className="space-y-5"+ >+ <div className="space-y-2">+ <label htmlFor="goal-group-name" className="text-[12.5px] font-medium">+ Name+ </label>+ <Input+ id="goal-group-name"+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder="Ads MCP reliability"+ maxLength={80}+ autoFocus+ />+ </div>+ <div className="space-y-2">+ <label htmlFor="goal-group-description" className="text-[12.5px] font-medium">+ Description <span className="font-normal text-[hsl(var(--notfair-ink-4))]">optional</span>+ </label>+ <textarea+ id="goal-group-description"+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ placeholder="Keep every paid-ads MCP connection reliable."+ maxLength={240}+ rows={3}+ className="w-full resize-none rounded-md border border-transparent bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"+ />+ </div>++ <fieldset>+ <legend className="mb-2 text-[12.5px] font-medium">+ Goals <span className="font-normal tabular-nums text-[hsl(var(--notfair-ink-4))]">{selected.size} selected</span>+ </legend>+ {goals.length === 0 ? (+ <p className="m-0 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.55)] p-4 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">+ No goals yet. You can create the empty group now and add goals later.+ </p>+ ) : (+ <div className="flex max-h-72 flex-col gap-2 overflow-y-auto pr-1">+ {goals.map((goal) => {+ const moving =+ selected.has(goal.id) &&+ goal.current_group_id !== null &&+ goal.current_group_id !== group?.id;+ return (+ <label+ key={goal.id}+ className="flex cursor-pointer items-start gap-3 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.55)] px-3 py-2.5 transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"+ >+ <input+ type="checkbox"+ checked={selected.has(goal.id)}+ onChange={() => toggle(goal.id)}+ className="mt-0.5 size-4 accent-[hsl(var(--notfair-ink))]"+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[13px] font-medium">{goal.label}</span>+ <span className="block text-[11px] text-[hsl(var(--notfair-ink-4))]">+ {moving ? `Moves from ${goal.current_group_name}` : goal.status}+ </span>+ </span>+ </label>+ );+ })}+ </div>+ )}+ </fieldset>++ <DialogFooter className="items-center sm:justify-between">+ {editing ? (+ confirmDelete ? (+ <div className="flex items-center gap-2">+ <span className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">Goals will become ungrouped.</span>+ <Button type="button" size="sm" variant="destructive" onClick={remove} disabled={pending}>+ Delete group+ </Button>+ </div>+ ) : (+ <Button type="button" size="sm" variant="ghost" onClick={() => setConfirmDelete(true)} disabled={pending}>+ <Trash2 className="size-3.5" />+ Delete+ </Button>+ )+ ) : (+ <span />+ )}+ <div className="flex gap-2">+ <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={pending}>+ Cancel+ </Button>+ <Button type="submit" disabled={pending || !name.trim()}>+ {pending ? "Saving…" : editing ? "Save group" : "Create group"}+ </Button>+ </div>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/notfair/src/components/goal-groups-overview.tsx b/notfair/src/components/goal-groups-overview.tsxnew file mode 100644index 00000000..56c12f70--- /dev/null+++ b/notfair/src/components/goal-groups-overview.tsx@@ -0,0 +1,57 @@+import Link from "next/link";+import { FolderKanban } from "lucide-react";++export type GoalGroupOverviewRow = {+ id: string;+ href: string;+ name: string;+ description: string;+ goal_count: number;+ healthy_count: number;+ attention_count: number;+ waiting_count: number;+};++export function GoalGroupsOverview({ groups }: { groups: GoalGroupOverviewRow[] }) {+ if (groups.length === 0) {+ return (+ <div className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.45)] px-4 py-5 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">+ Group related goals to see their metrics and recent checks together.+ </div>+ );+ }+ return (+ <ol className="ns-group">+ {groups.map((group) => (+ <li key={group.id}>+ <Link href={group.href} className="ns-row-button">+ <span className="ns-glyph" aria-hidden>+ <FolderKanban className="size-4" />+ </span>+ <span className="ns-row-body min-w-0">+ <span className="ns-row-title-row">+ <span className="ns-row-title">{group.name}</span>+ <span className="ns-tag-mono">{group.goal_count} goal{group.goal_count === 1 ? "" : "s"}</span>+ </span>+ <span className="ns-row-desc block truncate">+ {group.description || "A shared dashboard for related goals."}+ </span>+ </span>+ <span className="ml-auto flex shrink-0 items-center gap-3 text-[11.5px]">+ {group.healthy_count > 0 && (+ <span className="text-[hsl(var(--notfair-accent))]">{group.healthy_count} healthy</span>+ )}+ {group.attention_count > 0 && (+ <span className="text-[hsl(var(--destructive))]">{group.attention_count} attention</span>+ )}+ {group.waiting_count > 0 && (+ <span className="text-[hsl(var(--notfair-ink-4))]">{group.waiting_count} waiting</span>+ )}+ <span className="chev" aria-hidden>›</span>+ </span>+ </Link>+ </li>+ ))}+ </ol>+ );+}diff --git a/notfair/src/components/sidebar-goal-item.tsx b/notfair/src/components/sidebar-goal-item.tsxindex 22e69289..198c752d 100644--- a/notfair/src/components/sidebar-goal-item.tsx+++ b/notfair/src/components/sidebar-goal-item.tsx@@ -60,6 +60,7 @@ export function SidebarGoalItem({pinned,dotClass,labelClass,+ nested = false,}: {href: string;/** Project home — where the user lands after deleting the open goal. */@@ -70,6 +71,7 @@ export function SidebarGoalItem({pinned: boolean;dotClass: string;labelClass: string;+ nested?: boolean;}) {const router = useRouter();const pathname = usePathname();@@ -112,7 +114,7 @@ export function SidebarGoalItem({return (<SidebarMenuItem>- <SidebarMenuButton asChild>+ <SidebarMenuButton asChild className={nested ? "pl-7" : undefined}><Link href={href}><span className={cn("ns-dot", dotClass)} aria-hidden /><span className={cn("truncate", labelClass)}>{label}</span>diff --git a/notfair/src/components/ui/sidebar.tsx b/notfair/src/components/ui/sidebar.tsxindex 96af4d44..fa62a478 100644--- a/notfair/src/components/ui/sidebar.tsx+++ b/notfair/src/components/ui/sidebar.tsx@@ -309,7 +309,7 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {<maindata-slot="sidebar-inset"className={cn(- "relative flex w-full flex-1 flex-col bg-background",+ "relative flex min-w-0 w-full flex-1 flex-col bg-background","md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",className)}diff --git a/notfair/src/lib/goal-cadence.ts b/notfair/src/lib/goal-cadence.tsindex c93ddee7..ce02d338 100644--- a/notfair/src/lib/goal-cadence.ts+++ b/notfair/src/lib/goal-cadence.ts@@ -6,6 +6,7 @@export type CadenceOption = { value: string; label: string; hint: string };export const CADENCE_OPTIONS: CadenceOption[] = [+ { value: "0 * * * *", label: "Hourly", hint: "every hour" },{ value: "0 16 * * *", label: "Daily", hint: "every day, 9am PT" },{ value: "0 16 * * 1-5", label: "Weekdays", hint: "Mon–Fri, 9am PT" },{ value: "0 */6 * * *", label: "4× daily", hint: "every 6 hours" },diff --git a/notfair/src/lib/goal-group-health.test.ts b/notfair/src/lib/goal-group-health.test.tsnew file mode 100644index 00000000..b4dd39a6--- /dev/null+++ b/notfair/src/lib/goal-group-health.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vitest";+import { countGoalGroupHealth, goalGroupHealth } from "./goal-group-health";++const active = {+ status: "active" as const,+ target_value: 2,+ metric_direction: "decrease" as const,+};++describe("goalGroupHealth", () => {+ it("evaluates every goal against its own direction and threshold", () => {+ expect(goalGroupHealth({ ...active, current_value: 1.77 })).toBe("healthy");+ expect(goalGroupHealth({ ...active, current_value: 29.75, target_value: 5 })).toBe("attention");+ expect(+ goalGroupHealth({+ status: "active",+ current_value: 120,+ target_value: 100,+ metric_direction: "increase",+ }),+ ).toBe("healthy");+ });++ it("does not invent health when data is missing", () => {+ expect(goalGroupHealth({ ...active, current_value: null })).toBe("waiting");+ });++ it("counts health without averaging unrelated metrics", () => {+ expect(+ countGoalGroupHealth([+ { ...active, current_value: 1.77 },+ { ...active, current_value: 29.75, target_value: 5 },+ ]),+ ).toMatchObject({ healthy: 1, attention: 1 });+ });+});diff --git a/notfair/src/lib/goal-group-health.ts b/notfair/src/lib/goal-group-health.tsnew file mode 100644index 00000000..e33cb74b--- /dev/null+++ b/notfair/src/lib/goal-group-health.ts@@ -0,0 +1,39 @@+import { type GoalStatus, type MetricDirection } from "@/server/db/goals";++export type GoalGroupHealth =+ | "healthy"+ | "attention"+ | "waiting"+ | "paused"+ | "closed";++export type GoalHealthInput = {+ status: GoalStatus;+ current_value: number | null;+ target_value: number | null;+ metric_direction: MetricDirection | null;+};++export function goalGroupHealth(goal: GoalHealthInput): GoalGroupHealth {+ if (goal.status === "achieved") return "healthy";+ if (goal.status === "failed") return "attention";+ if (goal.status === "killed") return "closed";+ if (goal.status === "paused") return "paused";+ if (goal.status !== "active") return "waiting";+ if (goal.current_value === null || goal.target_value === null) return "waiting";+ const met =+ goal.metric_direction === "decrease"+ ? goal.current_value <= goal.target_value+ : goal.current_value >= goal.target_value;+ return met ? "healthy" : "attention";+}++export function countGoalGroupHealth(goals: GoalHealthInput[]) {+ return goals.reduce(+ (counts, goal) => {+ counts[goalGroupHealth(goal)] += 1;+ return counts;+ },+ { healthy: 0, attention: 0, waiting: 0, paused: 0, closed: 0 },+ );+}diff --git a/notfair/src/server/actions/goal-groups.ts b/notfair/src/server/actions/goal-groups.tsnew file mode 100644index 00000000..40511732--- /dev/null+++ b/notfair/src/server/actions/goal-groups.ts@@ -0,0 +1,87 @@+"use server";++import { revalidatePath } from "next/cache";+import {+ createGoalGroup,+ deleteGoalGroup,+ getGoalGroup,+ saveGoalGroup,+} from "@/server/db/goal-groups";+import { getProject } from "@/server/db/projects";++export type GoalGroupActionResult = {+ ok: boolean;+ error?: string;+ group_id?: string;+};++function cleanFields(name: string, description?: string):+ | { name: string; description: string }+ | { error: string } {+ const cleanName = name.trim();+ const cleanDescription = description?.trim() ?? "";+ if (!cleanName) return { error: "Group name can't be empty." };+ if (cleanName.length > 80) return { error: "Group name must be 80 characters or fewer." };+ if (cleanDescription.length > 240) {+ return { error: "Description must be 240 characters or fewer." };+ }+ return { name: cleanName, description: cleanDescription };+}++function messageForError(error: unknown): string {+ if (error instanceof Error && error.message.includes("UNIQUE constraint failed")) {+ return "A group with that name already exists in this project.";+ }+ return error instanceof Error ? error.message : String(error);+}++export async function createGoalGroupAction(input: {+ project_slug: string;+ name: string;+ description?: string;+ goal_ids?: string[];+}): Promise<GoalGroupActionResult> {+ if (!getProject(input.project_slug)) return { ok: false, error: "Project not found." };+ const fields = cleanFields(input.name, input.description);+ if ("error" in fields) return { ok: false, error: fields.error };+ try {+ const group = createGoalGroup({+ project_slug: input.project_slug,+ ...fields,+ goal_ids: input.goal_ids ?? [],+ });+ revalidatePath("/", "layout");+ return { ok: true, group_id: group.id };+ } catch (error) {+ return { ok: false, error: messageForError(error) };+ }+}++export async function saveGoalGroupAction(input: {+ group_id: string;+ name: string;+ description?: string;+ goal_ids: string[];+}): Promise<GoalGroupActionResult> {+ if (!getGoalGroup(input.group_id)) return { ok: false, error: "Goal group not found." };+ const fields = cleanFields(input.name, input.description);+ if ("error" in fields) return { ok: false, error: fields.error };+ try {+ const group = saveGoalGroup({+ id: input.group_id,+ ...fields,+ goal_ids: input.goal_ids,+ });+ if (!group) return { ok: false, error: "Goal group not found." };+ revalidatePath("/", "layout");+ return { ok: true, group_id: group.id };+ } catch (error) {+ return { ok: false, error: messageForError(error) };+ }+}++export async function deleteGoalGroupAction(groupId: string): Promise<GoalGroupActionResult> {+ if (!deleteGoalGroup(groupId)) return { ok: false, error: "Goal group not found." };+ revalidatePath("/", "layout");+ return { ok: true };+}diff --git a/notfair/src/server/db/goal-groups.test.ts b/notfair/src/server/db/goal-groups.test.tsnew file mode 100644index 00000000..694e7dec--- /dev/null+++ b/notfair/src/server/db/goal-groups.test.ts@@ -0,0 +1,100 @@+import { beforeAll, describe, expect, it, vi } from "vitest";++vi.hoisted(() => {+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");+ const { tmpdir } = require("node:os") as typeof import("node:os");+ const { join } = require("node:path") as typeof import("node:path");+ process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-goal-groups-"));+});++import { getDb } from "./db";+import { createGoal, getGoal } from "./goals";+import {+ createGoalGroup,+ deleteGoalGroup,+ getGoalGroup,+ listGoalGroupMemberships,+ listGoalsInGroup,+ saveGoalGroup,+ setGoalGroupMembership,+} from "./goal-groups";++const PROJECT = "group-project";++beforeAll(() => {+ const db = getDb();+ const insert = db.prepare(+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'codex-local')",+ );+ insert.run("gp1", PROJECT, "Group project", new Date().toISOString());+ insert.run("gp2", "other-project", "Other project", new Date().toISOString());+});++describe("goal groups", () => {+ it("creates a group containing many goals", () => {+ const google = createGoal({ project_slug: PROJECT, agent_id: "google", statement: "Google errors" });+ const meta = createGoal({ project_slug: PROJECT, agent_id: "meta", statement: "Meta errors" });+ const group = createGoalGroup({+ project_slug: PROJECT,+ name: "Ads MCP reliability",+ description: "Keep every ads connection healthy.",+ goal_ids: [google.id, meta.id],+ });++ expect(listGoalsInGroup(group.id).map((goal) => goal.id)).toEqual([google.id, meta.id]);+ expect(listGoalGroupMemberships(PROJECT)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ goal_id: google.id, group_id: group.id }),+ expect.objectContaining({ goal_id: meta.id, group_id: group.id }),+ ]),+ );+ });++ it("moves a goal atomically when it joins another group", () => {+ const goal = createGoal({ project_slug: PROJECT, agent_id: "move-me", statement: "Move" });+ const first = createGoalGroup({ project_slug: PROJECT, name: "First", goal_ids: [goal.id] });+ const second = createGoalGroup({ project_slug: PROJECT, name: "Second" });++ setGoalGroupMembership(goal.id, second.id);+ expect(listGoalsInGroup(first.id)).toHaveLength(0);+ expect(listGoalsInGroup(second.id).map((item) => item.id)).toEqual([goal.id]);+ });++ it("saves metadata and replaces members in one transaction", () => {+ const one = createGoal({ project_slug: PROJECT, agent_id: "save-one", statement: "One" });+ const two = createGoal({ project_slug: PROJECT, agent_id: "save-two", statement: "Two" });+ const group = createGoalGroup({ project_slug: PROJECT, name: "Before", goal_ids: [one.id] });++ const saved = saveGoalGroup({+ id: group.id,+ name: "After",+ description: "Updated",+ goal_ids: [two.id],+ });+ expect(saved).toMatchObject({ name: "After", description: "Updated" });+ expect(listGoalsInGroup(group.id).map((goal) => goal.id)).toEqual([two.id]);+ });++ it("rejects cross-project membership", () => {+ const other = createGoal({+ project_slug: "other-project",+ agent_id: "other-goal",+ statement: "Other",+ });+ expect(() =>+ createGoalGroup({ project_slug: PROJECT, name: "Invalid", goal_ids: [other.id] }),+ ).toThrow(/same project/);+ expect(getDb().prepare("SELECT COUNT(*) AS n FROM goal_groups WHERE name = 'Invalid'").get())+ .toEqual({ n: 0 });+ });++ it("deleting a group ungroups goals without deleting them", () => {+ const goal = createGoal({ project_slug: PROJECT, agent_id: "survivor", statement: "Stay" });+ const group = createGoalGroup({ project_slug: PROJECT, name: "Temporary", goal_ids: [goal.id] });++ expect(deleteGoalGroup(group.id)).toBe(true);+ expect(getGoalGroup(group.id)).toBeNull();+ expect(getGoal(goal.id)).not.toBeNull();+ expect(listGoalGroupMemberships(PROJECT).some((member) => member.goal_id === goal.id)).toBe(false);+ });+});diff --git a/notfair/src/server/db/goal-groups.ts b/notfair/src/server/db/goal-groups.tsnew file mode 100644index 00000000..cfaa59cc--- /dev/null+++ b/notfair/src/server/db/goal-groups.ts@@ -0,0 +1,167 @@+import { randomUUID } from "node:crypto";+import { getDb } from "./db";+import { type Goal } from "./goals";++export type GoalGroup = {+ id: string;+ project_slug: string;+ name: string;+ description: string;+ sort_order: number;+ created_at: string;+ updated_at: string;+};++export type GoalGroupMembership = {+ goal_id: string;+ group_id: string;+ created_at: string;+};++function now(): string {+ return new Date().toISOString();+}++function uniqueGoalIds(goalIds: string[]): string[] {+ return [...new Set(goalIds)];+}++function assertGoalsBelongToProject(projectSlug: string, goalIds: string[]): void {+ const ids = uniqueGoalIds(goalIds);+ if (ids.length === 0) return;+ const placeholders = ids.map(() => "?").join(",");+ const row = getDb()+ .prepare(+ `SELECT COUNT(*) AS count FROM goals+ WHERE project_slug = ? AND id IN (${placeholders})`,+ )+ .get(projectSlug, ...ids) as { count: number };+ if (row.count !== ids.length) {+ throw new Error("Every grouped goal must belong to the same project as the group.");+ }+}++function replaceMembers(group: GoalGroup, goalIds: string[]): void {+ const db = getDb();+ const ids = uniqueGoalIds(goalIds);+ assertGoalsBelongToProject(group.project_slug, ids);+ db.prepare("DELETE FROM goal_group_memberships WHERE group_id = ?").run(group.id);+ const insert = db.prepare(+ `INSERT INTO goal_group_memberships (goal_id, group_id, created_at)+ VALUES (?, ?, ?)+ ON CONFLICT(goal_id) DO UPDATE SET group_id = excluded.group_id, created_at = excluded.created_at`,+ );+ const ts = now();+ for (const goalId of ids) insert.run(goalId, group.id, ts);+}++export function createGoalGroup(input: {+ project_slug: string;+ name: string;+ description?: string;+ goal_ids?: string[];+}): GoalGroup {+ const db = getDb();+ const id = randomUUID();+ const ts = now();+ const run = db.transaction(() => {+ const sort = db+ .prepare(+ "SELECT COALESCE(MAX(sort_order), -1) + 1 AS next FROM goal_groups WHERE project_slug = ?",+ )+ .get(input.project_slug) as { next: number };+ db.prepare(+ `INSERT INTO goal_groups+ (id, project_slug, name, description, sort_order, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)`,+ ).run(+ id,+ input.project_slug,+ input.name,+ input.description ?? "",+ sort.next,+ ts,+ ts,+ );+ const group = getGoalGroup(id)!;+ replaceMembers(group, input.goal_ids ?? []);+ return group;+ });+ return run();+}++export function getGoalGroup(id: string): GoalGroup | null {+ const row = getDb().prepare("SELECT * FROM goal_groups WHERE id = ?").get(id);+ return (row as GoalGroup) ?? null;+}++export function listGoalGroups(projectSlug: string): GoalGroup[] {+ return getDb()+ .prepare(+ `SELECT * FROM goal_groups WHERE project_slug = ?+ ORDER BY sort_order ASC, created_at ASC, rowid ASC`,+ )+ .all(projectSlug) as GoalGroup[];+}++export function listGoalGroupMemberships(projectSlug: string): GoalGroupMembership[] {+ return getDb()+ .prepare(+ `SELECT m.* FROM goal_group_memberships m+ JOIN goal_groups gg ON gg.id = m.group_id+ WHERE gg.project_slug = ?+ ORDER BY m.created_at ASC`,+ )+ .all(projectSlug) as GoalGroupMembership[];+}++export function listGoalsInGroup(groupId: string): Goal[] {+ return getDb()+ .prepare(+ `SELECT g.* FROM goals g+ JOIN goal_group_memberships m ON m.goal_id = g.id+ WHERE m.group_id = ?+ ORDER BY g.created_at ASC, g.rowid ASC`,+ )+ .all(groupId) as Goal[];+}++export function saveGoalGroup(input: {+ id: string;+ name: string;+ description?: string;+ goal_ids: string[];+}): GoalGroup | null {+ const db = getDb();+ const run = db.transaction(() => {+ const current = getGoalGroup(input.id);+ if (!current) return null;+ db.prepare(+ "UPDATE goal_groups SET name = ?, description = ?, updated_at = ? WHERE id = ?",+ ).run(input.name, input.description ?? "", now(), input.id);+ const updated = getGoalGroup(input.id)!;+ replaceMembers(updated, input.goal_ids);+ return updated;+ });+ return run();+}++export function setGoalGroupMembership(goalId: string, groupId: string | null): void {+ const db = getDb();+ if (groupId === null) {+ db.prepare("DELETE FROM goal_group_memberships WHERE goal_id = ?").run(goalId);+ return;+ }+ const group = getGoalGroup(groupId);+ if (!group) throw new Error("Goal group not found.");+ assertGoalsBelongToProject(group.project_slug, [goalId]);+ db.prepare(+ `INSERT INTO goal_group_memberships (goal_id, group_id, created_at)+ VALUES (?, ?, ?)+ ON CONFLICT(goal_id) DO UPDATE SET group_id = excluded.group_id, created_at = excluded.created_at`,+ ).run(goalId, groupId, now());+}++export function deleteGoalGroup(id: string): boolean {+ return getDb().prepare("DELETE FROM goal_groups WHERE id = ?").run(id).changes > 0;+}diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.tsindex e1b9e230..08126a5b 100644--- a/notfair/src/server/db/schema.ts+++ b/notfair/src/server/db/schema.ts@@ -115,6 +115,31 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_goals_one_live_per_agentON goals(agent_id)WHERE status IN ('intake','proposed','active','paused');+-- Goal groups are dashboard/navigation containers. Membership is kept in a+-- separate table so existing CREATE-IF-NOT-EXISTS databases gain grouping+-- without altering the goals table. goal_id is the primary key, enforcing+-- the product rule that one goal belongs to at most one group.+CREATE TABLE IF NOT EXISTS goal_groups (+ id TEXT PRIMARY KEY,+ project_slug TEXT NOT NULL REFERENCES projects(slug) ON DELETE CASCADE,+ name TEXT NOT NULL COLLATE NOCASE,+ description TEXT NOT NULL DEFAULT '',+ sort_order INTEGER NOT NULL DEFAULT 0,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ UNIQUE(project_slug, name)+);+CREATE INDEX IF NOT EXISTS idx_goal_groups_project+ ON goal_groups(project_slug, sort_order, created_at);++CREATE TABLE IF NOT EXISTS goal_group_memberships (+ goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,+ group_id TEXT NOT NULL REFERENCES goal_groups(id) ON DELETE CASCADE,+ created_at TEXT NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_goal_group_memberships_group+ ON goal_group_memberships(group_id, created_at);+CREATE TABLE IF NOT EXISTS goal_actions (id TEXT PRIMARY KEY,goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,diff --git a/notfair/src/server/goals/metric.test.ts b/notfair/src/server/goals/metric.test.tsindex 49b58095..743e3ca0 100644--- a/notfair/src/server/goals/metric.test.ts+++ b/notfair/src/server/goals/metric.test.ts@@ -37,10 +37,18 @@ describe("parseMetricValue", () => {expect(parseMetricValue({ ok: true, result: { value: 9 } })).toBe(9);});+ it("accepts a one-column MCP table with one numeric row", () => {+ expect(parseMetricValue("value\n1.2097")).toBe(1.2097);+ expect(parseMetricValue("value\r\n1.2097")).toBe(1.2097);+ });+it("rejects ambiguous payloads", () => {expect(parseMetricValue("")).toBeNull();expect(parseMetricValue([1, 2])).toBeNull();expect(parseMetricValue({ rows: 4 })).toBeNull();+ expect(parseMetricValue("value\n1\n2")).toBeNull();+ expect(parseMetricValue("1\n2")).toBeNull();+ expect(parseMetricValue("not-a-metric\n1")).toBeNull();});});diff --git a/notfair/src/server/goals/metric.ts b/notfair/src/server/goals/metric.tsindex 44219eea..90e359a9 100644--- a/notfair/src/server/goals/metric.ts+++ b/notfair/src/server/goals/metric.ts@@ -115,7 +115,22 @@ export function parseMetricValue(payload: unknown, depth = 0): number | null {const trimmed = payload.trim();if (trimmed === "") return null;const n = Number(trimmed);- return Number.isFinite(n) ? n : null;+ if (Number.isFinite(n)) return n;++ // CLI-style MCPs may render a one-cell query as a two-line table:+ // value+ // 1.2097+ // Accept exactly one header plus one numeric data row. Anything wider+ // or taller remains ambiguous and must be rejected.+ const lines = trimmed+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ if (lines.length === 2 && lines[0]?.toLowerCase() === "value") {+ const tableValue = Number(lines[1]);+ if (Number.isFinite(tableValue)) return tableValue;+ }+ return null;}if (Array.isArray(payload)) {return payload.length === 1 ? parseMetricValue(payload[0], depth + 1) : null;