Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(goals): sidebar rail rework + all-goals board with pin/rename/delete

Yuting Zhong0abf70697053
diff --git a/notfair/src/app/(app)/[project]/goals/page.tsx b/notfair/src/app/(app)/[project]/goals/page.tsx
new file mode 100644
index 00000000..48b5c54c
--- /dev/null
+++ b/notfair/src/app/(app)/[project]/goals/page.tsx
@@ -0,0 +1,97 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { Plus } from "lucide-react";
+import { getProject } from "@/server/db/projects";
+import { listProjectAgents } from "@/server/agent-meta";
+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";
+
+export const dynamic = "force-dynamic";
+
+/**
+ * The All-goals board: every goal in the workspace across its whole
+ * lifecycle, one column per state. The sidebar rail only carries live
+ * goals — this page is where closed goals (achieved, failed, or closed by
+ * hand) remain browsable.
+ */
+export default async function AllGoalsPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
+
+ const agents = await listProjectAgents(slug);
+ const agentById = new Map(agents.map((a) => [a.agent_id, a]));
+ const pinnedIds = getPinnedGoalIds(slug);
+
+ // 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 agent = agentById.get(g.agent_id);
+ if (!agent) return [];
+ return [
+ {
+ id: g.id,
+ href: projectHref(slug, `/goals/${agent.slug}`),
+ label: goalLabel(g),
+ statement: g.statement,
+ status: g.status,
+ status_reason: g.status_reason,
+ metric_name: g.metric_name,
+ baseline_value: g.baseline_value,
+ current_value: g.current_value,
+ target_value: g.target_value,
+ metric_direction: g.metric_direction,
+ mode: g.mode,
+ tick_count: g.tick_count,
+ pinned: pinnedIds.has(g.id),
+ created_at: g.created_at,
+ updated_at: g.updated_at,
+ },
+ ];
+ });
+
+ // 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.
+ return (
+ <div className="absolute inset-0 flex flex-col overflow-y-auto px-7 pt-8 pb-4">
+ <header className="ns-page-head shrink-0">
+ <div className="ns-page-head-stack">
+ <h1 className="ns-page-title">All goals</h1>
+ <p className="ns-page-sub">
+ Every goal in {project.display_name}, across its whole life —
+ 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>
+ </header>
+
+ {goals.length === 0 ? (
+ <div className="ns-card p-8 text-center">
+ <p className="m-0 text-[13.5px] text-[hsl(var(--notfair-ink-3))]">
+ No goals yet. State an ambition and NotFair will figure out how to
+ measure and chase it.
+ </p>
+ <Link
+ href={projectHref(slug, "")}
+ className="ns-btn ns-btn-primary mt-4 inline-flex"
+ >
+ <Plus className="size-3.5" />
+ Create your first goal
+ </Link>
+ </div>
+ ) : (
+ <GoalsBoard goals={goals} />
+ )}
+ </div>
+ );
+}
diff --git a/notfair/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsx
index 4d5d79b2..9579a009 100644
--- a/notfair/src/components/app-sidebar.tsx
+++ b/notfair/src/components/app-sidebar.tsx
@@ -13,15 +13,20 @@ import {
SidebarTrigger,
} from "@/components/ui/sidebar";
import { SidebarBrand } from "@/components/sidebar-brand";
-import { BookOpen, Plug, Settings, Target, type LucideIcon } from "lucide-react";
+import { BookOpen, 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";
-import { getGoalForAgent, getLatestGoalForAgent, type GoalStatus } from "@/server/db/goals";
+import {
+ getPinnedGoalIds,
+ listGoals,
+ listLiveGoals,
+ type GoalStatus,
+} from "@/server/db/goals";
import { colorForAgentSlug } from "@/lib/agent-colors";
+import { SidebarGoalItem } from "@/components/sidebar-goal-item";
import { readHarnessUsage } from "@/server/harness-usage";
import { projectHref } from "@/lib/project-href";
-import { cn } from "@/lib/utils";
import { goalLabel } from "@/lib/goal-label";
import { ProjectSwitcher } from "./project-switcher";
import { HarnessFooter } from "./harness-footer";
@@ -40,21 +45,30 @@ const NAV: NavItem[] = [
{ href: "/settings", label: "Settings", icon: Settings },
];
-/** Compact status dot per goal state — the sidebar's only status signal. */
-const GOAL_DOT: Record<GoalStatus, string> = {
+/** Compact status dot per live goal state — the rail's only status signal.
+ * Closed goals never render here; their outcomes live on the board. */
+const GOAL_DOT: Partial<Record<GoalStatus, string>> = {
intake: "ns-dot-warn",
proposed: "ns-dot-warn",
active: "ns-dot-live",
paused: "ns-dot-mute",
- achieved: "ns-dot-on",
- failed: "ns-dot-err",
- killed: "ns-dot-mute",
};
export async function AppSidebar() {
const projects = listProjects();
const active = await getActiveProject();
const agentEntries = active ? await listProjectAgents(active.slug) : [];
+ // The rail shows only non-closed goals — an achieved/failed/closed goal
+ // moves to the All-goals board instead of lingering in daily nav.
+ // Pinned goals float to the top; the rest keep creation order.
+ const liveGoals = active ? listLiveGoals(active.slug) : [];
+ const pinnedIds = active ? getPinnedGoalIds(active.slug) : new Set<string>();
+ const railGoals = [
+ ...liveGoals.filter((g) => pinnedIds.has(g.id)),
+ ...liveGoals.filter((g) => !pinnedIds.has(g.id)),
+ ];
+ const totalGoals = active ? listGoals(active.slug).length : 0;
+ 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
// Claude Code it just reads the local stats-cache. Either failure
@@ -92,33 +106,45 @@ export async function AppSidebar() {
<SidebarGroupLabel>Goals</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
- {agentEntries.map((a) => {
- const goal = getGoalForAgent(a.agent_id) ?? getLatestGoalForAgent(a.agent_id);
- const color = colorForAgentSlug(a.slug);
- return (
- <SidebarMenuItem key={a.agent_id}>
- <SidebarMenuButton asChild>
- <Link href={projectHref(active.slug, `/goals/${a.slug}`)}>
- <span
- className={cn("ns-dot", goal ? GOAL_DOT[goal.status] : "ns-dot-mute")}
- aria-hidden
- />
- <span className={cn("truncate", color.label)}>
- {goal ? goalLabel(goal) : a.name}
- </span>
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- );
- })}
<SidebarMenuItem>
<SidebarMenuButton asChild>
<Link href={projectHref(active.slug, "")}>
- <Target />
+ <Plus />
<span>New goal…</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
+ {railGoals.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}
+ />
+ );
+ })}
+ {totalGoals > 0 && (
+ <SidebarMenuItem>
+ <SidebarMenuButton asChild>
+ <Link href={projectHref(active.slug, "/goals")}>
+ <LayoutGrid />
+ <span>All goals</span>
+ <span className="ml-auto text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {totalGoals}
+ </span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ )}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
diff --git a/notfair/src/components/goals-board.test.tsx b/notfair/src/components/goals-board.test.tsx
new file mode 100644
index 00000000..649008b7
--- /dev/null
+++ b/notfair/src/components/goals-board.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { GoalsBoard, type BoardGoal } from "./goals-board";
+
+function goal(overrides: Partial<BoardGoal>): BoardGoal {
+ return {
+ id: "g1",
+ href: "/proj/goals/goal-1",
+ label: "Goal one",
+ statement: "Do the thing",
+ status: "active",
+ status_reason: null,
+ metric_name: "Clicks",
+ baseline_value: 0,
+ current_value: 5,
+ target_value: 10,
+ metric_direction: "increase",
+ mode: "achieve",
+ tick_count: 3,
+ pinned: false,
+ created_at: "2026-07-01T00:00:00.000Z",
+ updated_at: "2026-07-10T00:00:00.000Z",
+ ...overrides,
+ };
+}
+
+describe("GoalsBoard", () => {
+ it("groups goals into lifecycle columns", () => {
+ render(
+ <GoalsBoard
+ goals={[
+ goal({ id: "a", label: "Running goal", status: "active" }),
+ goal({ id: "b", label: "Won goal", status: "achieved", status_reason: "target hit" }),
+ goal({ id: "c", label: "Draft goal", status: "intake" }),
+ ]}
+ />,
+ );
+ expect(
+ within(screen.getByRole("region", { name: "Running" })).getByText("Running goal"),
+ ).toBeTruthy();
+ const achieved = screen.getByRole("region", { name: "Achieved" });
+ expect(within(achieved).getByText("Won goal")).toBeTruthy();
+ expect(within(achieved).getByText("target hit")).toBeTruthy();
+ expect(
+ within(screen.getByRole("region", { name: "Setting up" })).getByText("Draft goal"),
+ ).toBeTruthy();
+ });
+
+ it("toggling a status chip hides and restores its column", () => {
+ render(<GoalsBoard goals={[goal({ status: "active" })]} />);
+ const chip = screen.getByRole("button", { name: /Running/ });
+ expect(screen.getByRole("region", { name: "Running" })).toBeTruthy();
+
+ fireEvent.click(chip);
+ expect(screen.queryByRole("region", { name: "Running" })).toBeNull();
+
+ fireEvent.click(chip);
+ expect(screen.getByRole("region", { name: "Running" })).toBeTruthy();
+ });
+
+ it("sorts pinned goals to the top of their column", () => {
+ render(
+ <GoalsBoard
+ goals={[
+ goal({ id: "old", label: "Older unpinned", created_at: "2026-07-02T00:00:00.000Z" }),
+ goal({
+ id: "new",
+ label: "Newest unpinned",
+ created_at: "2026-07-05T00:00:00.000Z",
+ }),
+ goal({
+ id: "pinned",
+ label: "Pinned goal",
+ pinned: true,
+ created_at: "2026-07-01T00:00:00.000Z",
+ }),
+ ]}
+ />,
+ );
+ const cards = within(screen.getByRole("region", { name: "Running" })).getAllByRole("link");
+ expect(cards[0]!.textContent).toContain("Pinned goal");
+ expect(cards[1]!.textContent).toContain("Newest unpinned");
+ });
+});
diff --git a/notfair/src/components/goals-board.tsx b/notfair/src/components/goals-board.tsx
new file mode 100644
index 00000000..f21fa7b8
--- /dev/null
+++ b/notfair/src/components/goals-board.tsx
@@ -0,0 +1,240 @@
+"use client";
+
+import Link from "next/link";
+import { useState } from "react";
+import { Pin } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { formatMetric } from "@/lib/format-metric";
+import { timeAgo } from "@/lib/time-ago";
+
+// Local copy of the status union — this component is client-side and takes
+// plain JSON props; importing from the server db module would be noise.
+type GoalStatus =
+ | "intake"
+ | "proposed"
+ | "active"
+ | "paused"
+ | "achieved"
+ | "failed"
+ | "killed";
+
+export type BoardGoal = {
+ id: string;
+ href: string;
+ label: string;
+ statement: string;
+ status: GoalStatus;
+ status_reason: string | null;
+ metric_name: string | null;
+ baseline_value: number | null;
+ current_value: number | null;
+ target_value: number | null;
+ metric_direction: "increase" | "decrease" | null;
+ mode: "achieve" | "maintain";
+ tick_count: number;
+ pinned: boolean;
+ created_at: string;
+ updated_at: string;
+};
+
+type GroupKey = "setup" | "running" | "paused" | "achieved" | "failed" | "closed";
+
+/**
+ * Board columns. Intake and proposed share a column — both are "the goal
+ * isn't running yet"; the card chip tells them apart (and flags the one
+ * that's waiting on the user's START). The three terminal states each get
+ * their own column so an achieved goal reads as a win, not just "gone".
+ */
+const GROUPS: Array<{
+ key: GroupKey;
+ title: string;
+ statuses: GoalStatus[];
+ dot: string;
+}> = [
+ { key: "setup", title: "Setting up", statuses: ["intake", "proposed"], dot: "ns-dot-warn" },
+ { key: "running", title: "Running", statuses: ["active"], dot: "ns-dot-live" },
+ { key: "paused", title: "Paused", statuses: ["paused"], dot: "ns-dot-mute" },
+ { key: "achieved", title: "Achieved", statuses: ["achieved"], dot: "ns-dot-on" },
+ { key: "failed", title: "Failed", statuses: ["failed"], dot: "ns-dot-err" },
+ { key: "closed", title: "Closed", statuses: ["killed"], dot: "ns-dot-mute" },
+];
+
+const TERMINAL: GoalStatus[] = ["achieved", "failed", "killed"];
+
+/**
+ * Jira-style board of every goal in the project, one column per lifecycle
+ * group, with toggleable status filters. Read-only: cards link to the goal
+ * screen where the real controls live.
+ */
+export function GoalsBoard({ goals }: { goals: BoardGoal[] }) {
+ const [visible, setVisible] = useState<Set<GroupKey>>(
+ () => new Set(GROUPS.map((g) => g.key)),
+ );
+
+ function toggle(key: GroupKey) {
+ setVisible((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }
+
+ const columns = GROUPS.map((group) => {
+ const items = goals
+ .filter((g) => group.statuses.includes(g.status))
+ .sort((a, b) => {
+ if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;
+ // Closed columns: most recently closed first. Live columns: newest first.
+ const key = TERMINAL.includes(a.status) ? "updated_at" : "created_at";
+ return b[key].localeCompare(a[key]);
+ });
+ return { ...group, items };
+ });
+
+ const shown = columns.filter((c) => visible.has(c.key));
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-4">
+ <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label="Filter goals by status">
+ {columns.map((c) => (
+ <button
+ key={c.key}
+ type="button"
+ onClick={() => toggle(c.key)}
+ aria-pressed={visible.has(c.key)}
+ className={cn(
+ "flex items-center gap-1.5 rounded-full px-3 py-1 text-[12.5px] font-medium transition-colors",
+ visible.has(c.key)
+ ? "bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-accent))] shadow-[var(--notfair-shadow-sm)]"
+ : "bg-[hsl(var(--notfair-surface-2)/0.6)] text-[hsl(var(--notfair-ink-3))] hover:bg-[hsl(var(--notfair-surface-2))]",
+ )}
+ >
+ <span className={cn("ns-dot", c.dot)} aria-hidden />
+ {c.title}
+ <span className="tabular-nums opacity-70">{c.items.length}</span>
+ </button>
+ ))}
+ </div>
+
+ {shown.length === 0 ? (
+ <p className="m-0 py-10 text-center text-[13px] text-[hsl(var(--notfair-ink-4))]">
+ Every status is filtered out — turn one back on above.
+ </p>
+ ) : (
+ <div className="flex min-h-0 flex-1 items-start gap-3 overflow-x-auto pb-4">
+ {shown.map((c) => (
+ <section
+ key={c.key}
+ aria-label={c.title}
+ className="flex max-h-full w-[280px] shrink-0 flex-col rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)]"
+ >
+ <header className="flex items-center gap-2 px-3 pt-3 pb-2">
+ <span className={cn("ns-dot", c.dot)} aria-hidden />
+ <h2 className="m-0 text-[11px] font-semibold uppercase tracking-[0.08em] text-[hsl(var(--notfair-ink-3))]">
+ {c.title}
+ </h2>
+ <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {c.items.length}
+ </span>
+ </header>
+ <div className="flex min-h-0 flex-col gap-2 overflow-y-auto px-2 pb-2">
+ {c.items.length === 0 ? (
+ <p className="m-0 px-1.5 py-6 text-center text-[12px] text-[hsl(var(--notfair-ink-4))]">
+ No goals here
+ </p>
+ ) : (
+ c.items.map((g) => <GoalCard key={g.id} goal={g} />)
+ )}
+ </div>
+ </section>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** Direction-agnostic progress toward target, 0..1, or null when unknowable. */
+function progressFraction(g: BoardGoal): number | null {
+ if (
+ g.baseline_value === null ||
+ g.current_value === null ||
+ g.target_value === null ||
+ g.target_value === g.baseline_value
+ ) {
+ return null;
+ }
+ const f = (g.current_value - g.baseline_value) / (g.target_value - g.baseline_value);
+ return Math.min(1, Math.max(0, f));
+}
+
+function GoalCard({ goal }: { goal: BoardGoal }) {
+ const closed = TERMINAL.includes(goal.status);
+ const progress =
+ goal.status === "active" || goal.status === "paused" ? progressFraction(goal) : null;
+
+ return (
+ <Link
+ href={goal.href}
+ className="ns-card block p-3 no-underline transition-shadow hover:shadow-[var(--notfair-shadow)]"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <span className="min-w-0 flex-1 text-[13px] leading-snug font-semibold text-foreground">
+ {goal.label}
+ </span>
+ {goal.pinned && (
+ <Pin
+ aria-label="Pinned"
+ className="mt-0.5 size-3 shrink-0 text-[hsl(var(--notfair-ink-4))]"
+ />
+ )}
+ </div>
+
+ {goal.status === "proposed" && (
+ <span className="ns-tag-accent mt-1.5 inline-block">ready to start</span>
+ )}
+ {goal.status === "intake" && (
+ <span className="ns-tag mt-1.5 inline-block">defining metric</span>
+ )}
+
+ <p className="m-0 mt-1.5 line-clamp-2 text-[12px] leading-snug text-[hsl(var(--notfair-ink-3))]">
+ {goal.statement}
+ </p>
+
+ {goal.metric_name && goal.target_value !== null && (
+ <p className="m-0 mt-2 text-[11.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ <span className="text-[hsl(var(--notfair-ink-3))]">{goal.metric_name}</span>{" "}
+ {formatMetric(goal.current_value)} / {formatMetric(goal.target_value)}
+ {goal.mode === "maintain" ? " (hold)" : ""}
+ </p>
+ )}
+
+ {progress !== null && (
+ <div
+ className="mt-1.5 h-[3px] w-full overflow-hidden rounded-full bg-[hsl(var(--notfair-ink-4)/0.12)]"
+ role="progressbar"
+ aria-valuenow={Math.round(progress * 100)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ >
+ <div
+ className="h-full rounded-full bg-[hsl(var(--notfair-accent))]"
+ style={{ width: `${Math.round(progress * 100)}%` }}
+ />
+ </div>
+ )}
+
+ {closed && goal.status_reason && (
+ <p className="m-0 mt-1.5 line-clamp-2 text-[11.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">
+ {goal.status_reason}
+ </p>
+ )}
+
+ <p className="m-0 mt-2 text-[11px] text-[hsl(var(--notfair-ink-4))]">
+ {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"} ·{" "}
+ {closed ? `closed ${timeAgo(goal.updated_at)}` : `updated ${timeAgo(goal.updated_at)}`}
+ </p>
+ </Link>
+ );
+}
diff --git a/notfair/src/components/sidebar-goal-item.tsx b/notfair/src/components/sidebar-goal-item.tsx
new file mode 100644
index 00000000..22e69289
--- /dev/null
+++ b/notfair/src/components/sidebar-goal-item.tsx
@@ -0,0 +1,258 @@
+"use client";
+
+import Link from "next/link";
+import { usePathname, useRouter } from "next/navigation";
+import { useState, useTransition } from "react";
+import { toast } from "sonner";
+import {
+ MoreVertical,
+ Pause,
+ Pencil,
+ Pin,
+ PinOff,
+ Play,
+ Trash2,
+} from "lucide-react";
+import {
+ SidebarMenuAction,
+ SidebarMenuButton,
+ SidebarMenuItem,
+} from "@/components/ui/sidebar";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ deleteGoalAction,
+ pauseGoalAction,
+ renameGoalAction,
+ resumeGoalAction,
+ setGoalPinnedAction,
+} from "@/server/actions/goals";
+import { cn } from "@/lib/utils";
+
+type LiveStatus = "intake" | "proposed" | "active" | "paused";
+
+/**
+ * One goal row in the sidebar rail: link to the goal screen plus a ⋮ menu
+ * (pin, rename, pause/resume, delete). Server sidebar computes the display
+ * bits (dot/label classes); this component owns the interactions.
+ */
+export function SidebarGoalItem({
+ href,
+ homeHref,
+ goalId,
+ label,
+ status,
+ pinned,
+ dotClass,
+ labelClass,
+}: {
+ href: string;
+ /** Project home — where the user lands after deleting the open goal. */
+ homeHref: string;
+ goalId: string;
+ label: string;
+ status: LiveStatus;
+ pinned: boolean;
+ dotClass: string;
+ labelClass: string;
+}) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const [pending, startTransition] = useTransition();
+ const [renameOpen, setRenameOpen] = useState(false);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const [draft, setDraft] = useState(label);
+
+ function run(
+ fn: () => Promise<{ ok: boolean; error?: string }>,
+ successMsg?: string,
+ after?: () => void,
+ ) {
+ startTransition(async () => {
+ const r = await fn();
+ if (!r.ok) {
+ toast.error(r.error ?? "Action failed.");
+ return;
+ }
+ if (successMsg) toast.success(successMsg);
+ after?.();
+ router.refresh();
+ });
+ }
+
+ function onDelete() {
+ run(
+ () => deleteGoalAction(goalId),
+ "Goal deleted.",
+ () => {
+ setDeleteOpen(false);
+ // If the user is anywhere inside the deleted goal's screen, that
+ // route is now a 404 — send them home.
+ if (pathname === href || pathname?.startsWith(`${href}/`)) {
+ router.push(homeHref);
+ }
+ },
+ );
+ }
+
+ return (
+ <SidebarMenuItem>
+ <SidebarMenuButton asChild>
+ <Link href={href}>
+ <span className={cn("ns-dot", dotClass)} aria-hidden />
+ <span className={cn("truncate", labelClass)}>{label}</span>
+ {pinned && (
+ <Pin
+ aria-label="Pinned"
+ className="ml-auto !size-3 shrink-0 text-[hsl(var(--notfair-ink-4))]"
+ />
+ )}
+ </Link>
+ </SidebarMenuButton>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <SidebarMenuAction showOnHover aria-label={`Goal actions: ${label}`}>
+ <MoreVertical />
+ </SidebarMenuAction>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="right" align="start" className="min-w-44">
+ <DropdownMenuItem
+ disabled={pending}
+ onSelect={() =>
+ run(
+ () => setGoalPinnedAction(goalId, !pinned),
+ pinned ? "Unpinned." : "Pinned to top.",
+ )
+ }
+ >
+ {pinned ? <PinOff /> : <Pin />}
+ {pinned ? "Unpin" : "Pin to top"}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={pending}
+ onSelect={() => {
+ setDraft(label);
+ setRenameOpen(true);
+ }}
+ >
+ <Pencil />
+ Rename…
+ </DropdownMenuItem>
+ {status === "active" && (
+ <DropdownMenuItem
+ disabled={pending}
+ onSelect={() => run(() => pauseGoalAction(goalId), "Goal paused.")}
+ >
+ <Pause />
+ Pause
+ </DropdownMenuItem>
+ )}
+ {status === "paused" && (
+ <DropdownMenuItem
+ disabled={pending}
+ onSelect={() =>
+ run(() => resumeGoalAction(goalId), "Goal resumed — heartbeat restarted.")
+ }
+ >
+ <Play />
+ Resume
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ disabled={pending}
+ onSelect={() => setDeleteOpen(true)}
+ >
+ <Trash2 />
+ Delete…
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <Dialog open={renameOpen} onOpenChange={setRenameOpen}>
+ <DialogContent className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Rename goal</DialogTitle>
+ <DialogDescription>
+ Changes the display name everywhere — the ambition itself stays
+ as you stated it.
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ run(
+ () => renameGoalAction(goalId, draft),
+ "Goal renamed.",
+ () => setRenameOpen(false),
+ );
+ }}
+ >
+ <Input
+ value={draft}
+ onChange={(e) => setDraft(e.target.value)}
+ autoFocus
+ aria-label="Goal name"
+ />
+ <DialogFooter className="mt-4">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setRenameOpen(false)}
+ disabled={pending}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={pending || !draft.trim()}>
+ Rename
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+
+ <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>
+ <DialogContent className="max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Delete “{label}”?</DialogTitle>
+ <DialogDescription>
+ Permanently removes the goal, its agent, its chat history, and
+ every check. There is no recovery — if you just want the loop to
+ stop, close the goal from its page instead.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => setDeleteOpen(false)}
+ disabled={pending}
+ >
+ Cancel
+ </Button>
+ <Button variant="destructive" onClick={onDelete} disabled={pending}>
+ <Trash2 className="size-3.5" />
+ Delete forever
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </SidebarMenuItem>
+ );
+}
diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.ts
index 8a824986..8343f172 100644
--- a/notfair/src/server/actions/goals.ts
+++ b/notfair/src/server/actions/goals.ts
@@ -3,11 +3,15 @@
import { revalidatePath } from "next/cache";
import {
createGoal,
+ deleteGoalsForAgent,
getGoal,
getGoalForAgent,
+ renameGoal,
+ setGoalPinned,
setGoalStatus,
startGoalLoop,
} from "@/server/db/goals";
+import { cascadeDeleteAgentArtifacts } from "@/server/agents/cascade-delete";
import { getProject } from "@/server/db/projects";
import {
goalAgentIdFor,
@@ -156,6 +160,44 @@ export async function killGoalAction(
return { ok: true };
}
+/** Rename the goal's display label (the sidebar/board handle). */
+export async function renameGoalAction(
+ goal_id: string,
+ label: string,
+): Promise<GoalActionResult> {
+ const trimmed = label.trim();
+ if (!trimmed) return { ok: false, error: "Name can't be empty." };
+ const goal = renameGoal(goal_id, trimmed);
+ if (!goal) return { ok: false, error: "Goal not found." };
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/** Pin/unpin the goal to the top of the sidebar rail. */
+export async function setGoalPinnedAction(
+ goal_id: string,
+ pinned: boolean,
+): Promise<GoalActionResult> {
+ if (!getGoal(goal_id)) return { ok: false, error: "Goal not found." };
+ setGoalPinned(goal_id, pinned);
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/**
+ * Delete the goal AND its agent — workspace dir, chat history, MCP
+ * registrations, every goal row. Unlike closing (killGoalAction), nothing
+ * survives; this is the "it never happened" path.
+ */
+export async function deleteGoalAction(goal_id: string): Promise<GoalActionResult> {
+ const goal = getGoal(goal_id);
+ if (!goal) return { ok: false, error: "Goal not found." };
+ await cascadeDeleteAgentArtifacts(goal.project_slug, goal.agent_id);
+ deleteGoalsForAgent(goal.agent_id);
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
/**
* Manual "Run tick now". Fire-and-forget for the turn itself, but the
* check row is claimed synchronously inside runGoalTick's pre-await
diff --git a/notfair/src/server/agents/cascade-delete.ts b/notfair/src/server/agents/cascade-delete.ts
index 04f11561..7db9635f 100644
--- a/notfair/src/server/agents/cascade-delete.ts
+++ b/notfair/src/server/agents/cascade-delete.ts
@@ -80,6 +80,52 @@ export async function getProjectDeletionSummary(
};
}
+/**
+ * Hard-delete ONE agent's artifacts: unregister its MCP servers from the
+ * harness config, drop its workspace dir, and delete its sessions
+ * (transcripts cascade). Goal rows are the caller's job
+ * (`deleteGoalsForAgent`) — this module owns the filesystem/harness side.
+ */
+export async function cascadeDeleteAgentArtifacts(
+ project_slug: string,
+ agent_id: string,
+): Promise<void> {
+ const project = getProject(project_slug);
+ const adapter = project ? requireAdapter(project.harness_adapter) : null;
+
+ if (adapter) {
+ const { GOALS_MCP_KEY, BROWSER_MCP_KEY } = await import(
+ "@/server/mcp-server/registration"
+ );
+ const serverNames = [
+ ...getMcpCatalog(project_slug).map((spec) => spec.key),
+ GOALS_MCP_KEY,
+ BROWSER_MCP_KEY,
+ ];
+ for (const serverName of serverNames) {
+ try {
+ await adapter.unregisterMcp({
+ serverName,
+ projectSlug: project_slug,
+ agentId: agent_id,
+ });
+ } catch {
+ // best-effort
+ }
+ }
+ }
+
+ try {
+ await rm(workspaceDirFor(agent_id), { recursive: true, force: true });
+ } catch (err) {
+ console.error(`[delete] failed to rm workspace ${agent_id}:`, err);
+ }
+
+ getDb()
+ .prepare("DELETE FROM sessions WHERE project_slug = ? AND agent_id = ?")
+ .run(project_slug, agent_id);
+}
+
/**
* Hard-delete every artifact tied to a project that lives outside the
* `projects` row's own FK cascade: agent workspace dirs, sessions +
diff --git a/notfair/src/server/db/goals.test.ts b/notfair/src/server/db/goals.test.ts
new file mode 100644
index 00000000..bdb978a3
--- /dev/null
+++ b/notfair/src/server/db/goals.test.ts
@@ -0,0 +1,87 @@
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+// Real better-sqlite3 against a tmpdir DB, per repo test conventions.
+// MUST be hoisted: static imports evaluate before module-level statements,
+// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment
+// here would silently point the suite at the developer's live ~/.notfair.
+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-goals-"));
+});
+
+import { getDb } from "./db";
+import {
+ createGoal,
+ deleteGoalsForAgent,
+ getGoal,
+ getPinnedGoalIds,
+ recordMetricSnapshot,
+ renameGoal,
+ setGoalPinned,
+} from "./goals";
+
+const SLUG = "proj";
+
+beforeAll(() => {
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",
+ )
+ .run(SLUG, new Date().toISOString());
+});
+
+describe("renameGoal", () => {
+ it("updates short_label and returns the goal", () => {
+ const goal = createGoal({ project_slug: SLUG, agent_id: "a-rename", statement: "ship" });
+ const renamed = renameGoal(goal.id, "Ship it → 100%");
+ expect(renamed?.short_label).toBe("Ship it → 100%");
+ });
+
+ it("returns null for an unknown goal", () => {
+ expect(renameGoal("nope", "x")).toBeNull();
+ });
+});
+
+describe("goal pins", () => {
+ it("pin/unpin round-trips and is idempotent", () => {
+ const goal = createGoal({ project_slug: SLUG, agent_id: "a-pin", statement: "pin me" });
+ setGoalPinned(goal.id, true);
+ setGoalPinned(goal.id, true); // no throw on double-pin
+ expect(getPinnedGoalIds(SLUG).has(goal.id)).toBe(true);
+ setGoalPinned(goal.id, false);
+ expect(getPinnedGoalIds(SLUG).has(goal.id)).toBe(false);
+ });
+
+ it("scopes pinned ids to the project", () => {
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p2', 'other', 'Other', ?, 'codex-local')",
+ )
+ .run(new Date().toISOString());
+ const goal = createGoal({ project_slug: "other", agent_id: "a-other", statement: "x" });
+ setGoalPinned(goal.id, true);
+ expect(getPinnedGoalIds(SLUG).has(goal.id)).toBe(false);
+ expect(getPinnedGoalIds("other").has(goal.id)).toBe(true);
+ });
+});
+
+describe("deleteGoalsForAgent", () => {
+ it("deletes the goal rows and cascades child tables", () => {
+ const goal = createGoal({ project_slug: SLUG, agent_id: "a-del", statement: "delete me" });
+ recordMetricSnapshot(goal.id, 42, "intake");
+ setGoalPinned(goal.id, true);
+
+ expect(deleteGoalsForAgent("a-del")).toBe(1);
+ expect(getGoal(goal.id)).toBeNull();
+ const snaps = getDb()
+ .prepare("SELECT COUNT(*) AS n FROM goal_metric_snapshots WHERE goal_id = ?")
+ .get(goal.id) as { n: number };
+ expect(snaps.n).toBe(0);
+ const pins = getDb()
+ .prepare("SELECT COUNT(*) AS n FROM goal_pins WHERE goal_id = ?")
+ .get(goal.id) as { n: number };
+ expect(pins.n).toBe(0);
+ });
+});
diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.ts
index 2334b7ce..c737e740 100644
--- a/notfair/src/server/db/goals.ts
+++ b/notfair/src/server/db/goals.ts
@@ -414,6 +414,52 @@ export function amendGoal(id: string, input: AmendGoalInput): Goal | null {
return getGoal(id);
}
+/**
+ * Rename the goal's display label. Works in any status — a closed goal's
+ * label is still the user's handle for it in history views.
+ */
+export function renameGoal(id: string, short_label: string): Goal | null {
+ const r = getDb()
+ .prepare("UPDATE goals SET short_label = ?, updated_at = ? WHERE id = ?")
+ .run(short_label, now(), id);
+ if (r.changes === 0) return null;
+ return getGoal(id);
+}
+
+/**
+ * Hard-delete an agent's goal rows. FK cascades take actions, snapshots,
+ * learnings, ticks, PRs, and pins with them. Agent = goal, so callers pair
+ * this with the agent's workspace/session cascade.
+ */
+export function deleteGoalsForAgent(agent_id: string): number {
+ return getDb().prepare("DELETE FROM goals WHERE agent_id = ?").run(agent_id).changes;
+}
+
+// ── pins ─────────────────────────────────────────────────────────────────
+
+export function setGoalPinned(id: string, pinned: boolean): void {
+ const db = getDb();
+ if (pinned) {
+ db.prepare(
+ "INSERT OR IGNORE INTO goal_pins (goal_id, created_at) VALUES (?, ?)",
+ ).run(id, now());
+ } else {
+ db.prepare("DELETE FROM goal_pins WHERE goal_id = ?").run(id);
+ }
+}
+
+/** Pinned goal ids for a project (sidebar sorts these first). */
+export function getPinnedGoalIds(project_slug: string): Set<string> {
+ const rows = getDb()
+ .prepare(
+ `SELECT p.goal_id FROM goal_pins p
+ JOIN goals g ON g.id = p.goal_id
+ WHERE g.project_slug = ?`,
+ )
+ .all(project_slug) as Array<{ goal_id: string }>;
+ return new Set(rows.map((r) => r.goal_id));
+}
+
/** Total incremental spend the agent has logged (non-abandoned actions). */
export function loggedSpendTotal(goal_id: string): number {
const row = getDb()
diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.ts
index f7b0980d..e1b9e230 100644
--- a/notfair/src/server/db/schema.ts
+++ b/notfair/src/server/db/schema.ts
@@ -177,6 +177,14 @@ CREATE TABLE IF NOT EXISTS goal_support_metric_snapshots (
CREATE INDEX IF NOT EXISTS idx_goal_support_snapshots_metric
ON goal_support_metric_snapshots(metric_id, created_at);
+-- Sidebar pins: pinned goals sort to the top of the goal rail. A separate
+-- table (not a column on goals) because schema boot is CREATE-IF-NOT-EXISTS
+-- only: existing databases never gain columns.
+CREATE TABLE IF NOT EXISTS goal_pins (
+ goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,
+ created_at TEXT NOT NULL
+);
+
CREATE TABLE IF NOT EXISTS goal_learnings (
id TEXT PRIMARY KEY,
goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,