Skip to content

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

feat: celebrate completed goals and fix Codex launch

Yuting Zhong93c7eebd3e91
diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.md
index b9b76edf..e469b24d 100644
--- a/notfair/CHANGELOG.md
+++ b/notfair/CHANGELOG.md
@@ -1,5 +1,11 @@
# NotFair
+## 0.9.17 — 2026-07-22
+
+**Completed goals now get the celebration they deserve.** Achievements stay visible in the sidebar with a sparkling **Completed** badge until you open the congratulations experience, where you can set a more ambitious next milestone or archive the goal without losing its chat, checks, metrics, or evidence.
+
+**Background NotFair servers can reliably launch Codex.** Codex discovery no longer depends entirely on an interactive shell’s `PATH`; chat execution, health checks, login, and usage status now find standard installations and the executable bundled with the ChatGPT desktop app while still honoring `NOTFAIR_CODEX_BIN`.
+
## 0.9.16 — 2026-07-22
**NotFair now starts with the Node.js runtime that matches its installed native database module.** Global installs no longer land on a server-error page when the shell and npm installation use different Node.js versions.
diff --git a/notfair/package.json b/notfair/package.json
index cb25b70b..631794c1 100644
--- a/notfair/package.json
+++ b/notfair/package.json
@@ -1,6 +1,6 @@
{
"name": "notfair",
- "version": "0.9.16",
+ "version": "0.9.17",
"description": "Goal-driven, loop-powered marketing agents that crush your business goals 24/7 — on your own machine. Say 'cut CAC to $30' and a dedicated agent turns it into a server-verified metric, then moves the number check after check while you sleep. Rides your existing Claude Code or Codex login.",
"license": "MIT",
"bin": {
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
index 9e54681b..cff3e0f6 100644
--- a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
@@ -1,10 +1,12 @@
import Link from "next/link";
import { notFound } from "next/navigation";
+import { Sparkles } from "lucide-react";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import {
getGoalForAgent,
getLatestGoalForAgent,
+ isGoalArchived,
listGoalActions,
listOpenGoalActions,
listUserActionRequests,
@@ -54,6 +56,7 @@ import { type MoveRow } from "@/components/goal-moves";
import { GoalPrsDialog, type PrRow } from "@/components/goal-prs-dialog";
import { maybeSyncGoalPrs } from "@/server/goals/pr-sync";
import { buildCheckSquares, currentStreak } from "@/lib/goal-streak";
+import { GoalCompletionDialog } from "@/components/goal-completion-dialog";
export const dynamic = "force-dynamic";
@@ -128,6 +131,8 @@ export default async function GoalPage({
}));
const live = goal.status === "intake" || goal.status === "proposed" || goal.status === "active" || goal.status === "paused";
+ const achievementArchived =
+ goal.status === "achieved" ? isGoalArchived(goal.id) : false;
const learnings = listGoalLearnings(goal.id, 100);
// Header dialogs: the moves journal (every open action, whatever its
@@ -220,6 +225,28 @@ export default async function GoalPage({
status={goal.status as "intake" | "proposed" | "active" | "paused"}
/>
)}
+ {goal.status === "achieved" && !achievementArchived && (
+ <GoalCompletionDialog
+ goalId={goal.id}
+ label={goalLabel(goal)}
+ metricName={goal.metric_name}
+ currentValue={goal.current_value}
+ targetValue={goal.target_value}
+ metricDirection={goal.metric_direction}
+ completionReason={goal.status_reason}
+ completedAt={goal.updated_at}
+ trigger={
+ <button
+ type="button"
+ className="ns-chip ns-completed-badge bg-[hsl(var(--notfair-accent-soft))] font-medium text-[hsl(var(--notfair-accent))] shadow-[inset_0_0_0_1px_hsl(var(--notfair-accent-border))] hover:text-[hsl(var(--notfair-accent))]"
+ aria-label="Celebrate this completed goal"
+ >
+ <Sparkles aria-hidden />
+ Celebrate
+ </button>
+ }
+ />
+ )}
</div>
</header>
diff --git a/notfair/src/app/globals.css b/notfair/src/app/globals.css
index 7267c09e..057e77d5 100644
--- a/notfair/src/app/globals.css
+++ b/notfair/src/app/globals.css
@@ -220,6 +220,36 @@
50% { box-shadow: 0 0 0 4px transparent; }
}
+@keyframes ns-celebration-pop {
+ 0% { transform: scale(0.5) rotate(-10deg); opacity: 0; }
+ 62% { transform: scale(1.12) rotate(3deg); opacity: 1; }
+ 100% { transform: scale(1) rotate(0); opacity: 1; }
+}
+
+@keyframes ns-celebration-ring {
+ 0% { transform: scale(0.7); opacity: 0; }
+ 42% { opacity: 0.7; }
+ 100% { transform: scale(1.3); opacity: 0; }
+}
+
+@keyframes ns-confetti-burst {
+ 0% {
+ opacity: 0;
+ transform: translate(-50%, -50%) rotate(var(--angle)) translateY(0) scale(0.35);
+ }
+ 18% { opacity: 1; }
+ 100% {
+ opacity: 0;
+ transform: translate(-50%, -50%) rotate(var(--angle)) translateY(var(--distance)) scale(1);
+ }
+}
+
+@keyframes ns-completed-badge-arrive {
+ 0% { transform: translateY(2px) scale(0.78); opacity: 0; }
+ 58% { transform: translateY(-1px) scale(1.07); opacity: 1; }
+ 100% { transform: translateY(0) scale(1); opacity: 1; }
+}
+
@theme inline {
--animate-aurora-sweep: aurora-sweep 2.6s linear infinite;
--animate-shimmer-bar: shimmer-bar 1.8s ease-in-out infinite;
@@ -227,6 +257,112 @@
--animate-phase-glow: phase-glow 2s ease-in-out infinite;
}
+@layer components {
+.ns-completed-badge {
+ animation: ns-completed-badge-arrive 0.7s cubic-bezier(.22, .9, .25, 1.15) both;
+}
+
+.ns-celebration-stage {
+ position: relative;
+ min-height: 256px;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 32px 16px 14px;
+ background:
+ radial-gradient(circle at 50% 35%, hsl(var(--notfair-accent-soft)) 0, transparent 43%),
+ linear-gradient(180deg, hsl(var(--card)), hsl(var(--card)));
+}
+
+.ns-celebration-halo {
+ position: absolute;
+ top: 29px;
+ left: 50%;
+ width: 124px;
+ height: 124px;
+ margin-left: -62px;
+ border: 1px solid hsl(var(--notfair-accent-border));
+ border-radius: 999px;
+ animation: ns-celebration-ring 1.15s ease-out 0.15s both;
+}
+
+.ns-celebration-medal {
+ position: relative;
+ z-index: 2;
+ display: grid;
+ place-items: center;
+ width: 76px;
+ height: 76px;
+ margin-bottom: 18px;
+ border-radius: 23px;
+ color: white;
+ background: linear-gradient(145deg, #55b875, #328f55);
+ box-shadow:
+ 0 16px 38px -14px rgba(63, 158, 96, 0.72),
+ inset 0 1px 0 rgba(255, 255, 255, 0.32);
+ animation: ns-celebration-pop 0.65s cubic-bezier(.22, .9, .25, 1.2) both;
+}
+
+.ns-celebration-medal > svg {
+ width: 34px;
+ height: 34px;
+ stroke-width: 1.8;
+}
+
+.ns-celebration-medal > span {
+ position: absolute;
+ right: -6px;
+ bottom: -5px;
+ display: grid;
+ place-items: center;
+ width: 26px;
+ height: 26px;
+ border: 3px solid hsl(var(--card));
+ border-radius: 999px;
+ color: #277b45;
+ background: white;
+}
+
+.ns-celebration-medal > span svg {
+ width: 13px;
+ height: 13px;
+ stroke-width: 3;
+}
+
+.ns-celebration-confetti {
+ position: absolute;
+ top: 71px;
+ left: 50%;
+ width: 1px;
+ height: 1px;
+}
+
+.ns-celebration-confetti > span {
+ --distance: 100px;
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 7px;
+ height: 3px;
+ border-radius: 2px;
+ background: var(--piece-color);
+ opacity: 0;
+ animation: ns-confetti-burst 0.9s cubic-bezier(.16, .75, .28, 1) var(--delay) both;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ns-completed-badge,
+ .ns-celebration-halo,
+ .ns-celebration-medal,
+ .ns-celebration-confetti > span {
+ animation: none;
+ }
+ .ns-celebration-confetti { display: none; }
+}
+}
+
:root {
--sidebar: hsl(var(--notfair-sidebar));
--sidebar-foreground: hsl(var(--notfair-ink-3));
diff --git a/notfair/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsx
index 7f832ad2..f455805e 100644
--- a/notfair/src/components/app-sidebar.tsx
+++ b/notfair/src/components/app-sidebar.tsx
@@ -22,7 +22,7 @@ import {
countUserActionRequests,
getPinnedGoalIds,
listGoals,
- listLiveGoals,
+ listSidebarGoals,
} from "@/server/db/goals";
import { colorForAgentSlug } from "@/lib/agent-colors";
import { SidebarGoalItem } from "@/components/sidebar-goal-item";
@@ -53,12 +53,15 @@ 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) : [];
+ // Achievements remain in the rail until the user explicitly chooses to
+ // archive or continue them. Pinned live goals float within the live set;
+ // newly completed goals stay first so the payoff cannot be missed.
+ const sidebarGoals = active ? listSidebarGoals(active.slug) : [];
const pinnedIds = active ? getPinnedGoalIds(active.slug) : new Set<string>();
+ const completedGoals = sidebarGoals.filter((goal) => goal.status === "achieved");
+ const liveGoals = sidebarGoals.filter((goal) => goal.status !== "achieved");
const railGoals = [
+ ...completedGoals,
...liveGoals.filter((g) => pinnedIds.has(g.id)),
...liveGoals.filter((g) => !pinnedIds.has(g.id)),
];
@@ -151,13 +154,25 @@ export async function AppSidebar() {
homeHref={projectHref(active.slug, "")}
goalId={goal.id}
label={goalLabel(goal)}
- status={goal.status as "intake" | "proposed" | "active" | "paused"}
+ status={goal.status as "intake" | "proposed" | "active" | "paused" | "achieved"}
pinned={pinnedIds.has(goal.id)}
labelClass={color.label}
projectSlug={active.slug}
groups={groupTargets}
groupId={null}
needsAttention={(attentionByGoal.get(goal.id) ?? 0) > 0}
+ completion={
+ goal.status === "achieved"
+ ? {
+ metricName: goal.metric_name,
+ currentValue: goal.current_value,
+ targetValue: goal.target_value,
+ metricDirection: goal.metric_direction,
+ completionReason: goal.status_reason,
+ completedAt: goal.updated_at,
+ }
+ : undefined
+ }
/>
);
})}
@@ -169,6 +184,7 @@ export async function AppSidebar() {
groupId={group.id}
name={group.name}
href={projectHref(active.slug, `/groups/${group.id}`)}
+ completedCount={groupGoals.filter((goal) => goal.status === "achieved").length}
>
{groupGoals.map((goal) => {
const agent = agentBySlug.get(goal.agent_id);
@@ -181,13 +197,25 @@ export async function AppSidebar() {
homeHref={projectHref(active.slug, "")}
goalId={goal.id}
label={goalLabel(goal)}
- status={goal.status as "intake" | "proposed" | "active" | "paused"}
+ status={goal.status as "intake" | "proposed" | "active" | "paused" | "achieved"}
pinned={pinnedIds.has(goal.id)}
labelClass={color.label}
projectSlug={active.slug}
groups={groupTargets}
groupId={group.id}
needsAttention={(attentionByGoal.get(goal.id) ?? 0) > 0}
+ completion={
+ goal.status === "achieved"
+ ? {
+ metricName: goal.metric_name,
+ currentValue: goal.current_value,
+ targetValue: goal.target_value,
+ metricDirection: goal.metric_direction,
+ completionReason: goal.status_reason,
+ completedAt: goal.updated_at,
+ }
+ : undefined
+ }
/>
);
})}
diff --git a/notfair/src/components/goal-completion-dialog.test.tsx b/notfair/src/components/goal-completion-dialog.test.tsx
new file mode 100644
index 00000000..2eb1bdcd
--- /dev/null
+++ b/notfair/src/components/goal-completion-dialog.test.tsx
@@ -0,0 +1,98 @@
+// @vitest-environment jsdom
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { GoalCompletionDialog } from "@/components/goal-completion-dialog";
+
+const archiveGoal = vi.hoisted(() => vi.fn());
+const continueGoal = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/goals", () => ({
+ archiveCompletedGoalAction: archiveGoal,
+ continueCompletedGoalAction: continueGoal,
+}));
+
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh }),
+}));
+
+const PROPS = {
+ goalId: "goal-1",
+ label: "Qualified visits → 100",
+ metricName: "Qualified visits",
+ currentValue: 112,
+ targetValue: 100,
+ metricDirection: "increase" as const,
+ completionReason: "The verified metric reached 112.",
+ completedAt: "2026-07-22T18:00:00.000Z",
+ goalHref: "/acme/goals/goal-1",
+};
+
+function renderDialog() {
+ render(
+ <GoalCompletionDialog
+ {...PROPS}
+ trigger={<button type="button">Completed</button>}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Completed" }));
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ archiveGoal.mockResolvedValue({ ok: true });
+ continueGoal.mockResolvedValue({ ok: true });
+});
+
+describe("GoalCompletionDialog", () => {
+ it("celebrates the measured result and keeps every next step explicit", () => {
+ renderDialog();
+
+ expect(screen.getByRole("heading", { name: "You did it." })).toBeInTheDocument();
+ expect(screen.getByText("112")).toBeInTheDocument();
+ expect(screen.getByText("100")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /set a new target/i })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /archive goal/i })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: /view the full story/i })).toHaveAttribute(
+ "href",
+ "/acme/goals/goal-1",
+ );
+ });
+
+ it("continues the same goal with a validated next milestone", async () => {
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: /set a new target/i }));
+ expect(
+ screen.getByRole("heading", { name: /what’s the next milestone/i }),
+ ).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText("New target"), {
+ target: { value: "150" },
+ });
+ expect(screen.getByLabelText("Goal name")).toHaveValue(
+ "Qualified visits → 150",
+ );
+ fireEvent.change(screen.getByLabelText(/Deadline/), {
+ target: { value: "2030-12-31" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /start next milestone/i }));
+
+ await waitFor(() =>
+ expect(continueGoal).toHaveBeenCalledWith("goal-1", {
+ target_value: 150,
+ deadline: "2030-12-31",
+ label: "Qualified visits → 150",
+ }),
+ );
+ await waitFor(() => expect(refresh).toHaveBeenCalled());
+ });
+
+ it("archives the achievement without conflating archive with delete", async () => {
+ renderDialog();
+ fireEvent.click(screen.getByRole("button", { name: /archive goal/i }));
+
+ await waitFor(() => expect(archiveGoal).toHaveBeenCalledWith("goal-1"));
+ expect(continueGoal).not.toHaveBeenCalled();
+ await waitFor(() => expect(refresh).toHaveBeenCalled());
+ });
+});
diff --git a/notfair/src/components/goal-completion-dialog.tsx b/notfair/src/components/goal-completion-dialog.tsx
new file mode 100644
index 00000000..d18e13fb
--- /dev/null
+++ b/notfair/src/components/goal-completion-dialog.tsx
@@ -0,0 +1,404 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import {
+ Archive,
+ ArrowLeft,
+ ArrowRight,
+ Check,
+ ExternalLink,
+ Sparkles,
+ Trophy,
+} from "lucide-react";
+import {
+ useMemo,
+ useState,
+ useTransition,
+ type CSSProperties,
+ type ReactNode,
+} from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ archiveCompletedGoalAction,
+ continueCompletedGoalAction,
+} from "@/server/actions/goals";
+import { formatMetric } from "@/lib/format-metric";
+
+const CONFETTI = Array.from({ length: 20 }, (_, index) => ({
+ angle: index * 18 + (index % 3) * 4,
+ delay: (index % 5) * 32,
+ distance: 90 + (index % 4) * 15,
+ color: ["#4CAF6E", "#F1B94A", "#8B7CF6", "#54A7E8", "#F26D85"][
+ index % 5
+ ],
+}));
+
+export type GoalCompletionDialogProps = {
+ goalId: string;
+ label: string;
+ metricName: string | null;
+ currentValue: number | null;
+ targetValue: number | null;
+ metricDirection: "increase" | "decrease" | null;
+ completionReason: string | null;
+ completedAt: string;
+ goalHref?: string;
+ trigger: ReactNode;
+};
+
+/**
+ * The explicit handoff between "the agent hit the number" and "the user
+ * decides what happens next." Closing the dialog leaves the achievement in
+ * the sidebar, so celebration can never accidentally become dismissal.
+ */
+export function GoalCompletionDialog({
+ goalId,
+ label,
+ metricName,
+ currentValue,
+ targetValue,
+ metricDirection,
+ completionReason,
+ completedAt,
+ goalHref,
+ trigger,
+}: GoalCompletionDialogProps) {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const [step, setStep] = useState<"celebrate" | "continue">("celebrate");
+ const [target, setTarget] = useState("");
+ const [nextLabel, setNextLabel] = useState(label);
+ const [labelEdited, setLabelEdited] = useState(false);
+ const [deadline, setDeadline] = useState("");
+ const [pending, startTransition] = useTransition();
+ const completedLabel = useMemo(
+ () =>
+ new Date(completedAt).toLocaleDateString([], {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ }),
+ [completedAt],
+ );
+
+ function changeOpen(next: boolean) {
+ setOpen(next);
+ if (!next) {
+ setStep("celebrate");
+ setTarget("");
+ setNextLabel(label);
+ setLabelEdited(false);
+ setDeadline("");
+ }
+ }
+
+ function archive() {
+ startTransition(async () => {
+ const result = await archiveCompletedGoalAction(goalId);
+ if (!result.ok) {
+ toast.error(result.error ?? "Could not archive this goal.");
+ return;
+ }
+ changeOpen(false);
+ toast.success("Achievement archived — its full story is saved in All goals.");
+ router.refresh();
+ });
+ }
+
+ function continueGoal() {
+ const targetValue = Number(target);
+ if (!target.trim() || !Number.isFinite(targetValue)) {
+ toast.error("Enter a valid next target.");
+ return;
+ }
+ startTransition(async () => {
+ const result = await continueCompletedGoalAction(goalId, {
+ target_value: targetValue,
+ deadline: deadline || null,
+ label: nextLabel.trim() || null,
+ });
+ if (!result.ok) {
+ toast.error(result.error ?? "Could not start the next milestone.");
+ return;
+ }
+ changeOpen(false);
+ toast.success("Next milestone started — your goal is running again.");
+ router.refresh();
+ });
+ }
+
+ const directionWord =
+ metricDirection === "increase"
+ ? "above"
+ : metricDirection === "decrease"
+ ? "below"
+ : "beyond";
+
+ function updateTarget(value: string) {
+ setTarget(value);
+ if (labelEdited) return;
+ const numeric = Number(value);
+ if (!value.trim() || !Number.isFinite(numeric)) {
+ setNextLabel(label);
+ return;
+ }
+ const nextValue = formatMetric(numeric);
+ const oldValue = formatMetric(targetValue);
+ if (targetValue !== null && label.includes(oldValue)) {
+ setNextLabel(label.replace(oldValue, nextValue));
+ return;
+ }
+ const rawOldValue = targetValue === null ? "" : String(targetValue);
+ if (rawOldValue && label.includes(rawOldValue)) {
+ setNextLabel(label.replace(rawOldValue, nextValue));
+ return;
+ }
+ setNextLabel(`${metricName ?? label} → ${nextValue}`);
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={changeOpen}>
+ <DialogTrigger asChild>{trigger}</DialogTrigger>
+ <DialogContent
+ className="overflow-hidden p-0 sm:max-w-[540px]"
+ >
+ {step === "celebrate" ? (
+ <>
+ <div className="ns-celebration-stage">
+ <div className="ns-celebration-halo" aria-hidden />
+ <div className="ns-celebration-confetti" aria-hidden>
+ {CONFETTI.map((piece, index) => (
+ <span
+ key={index}
+ style={
+ {
+ "--angle": `${piece.angle}deg`,
+ "--delay": `${piece.delay}ms`,
+ "--distance": `-${piece.distance}px`,
+ "--piece-color": piece.color,
+ } as CSSProperties
+ }
+ />
+ ))}
+ </div>
+ <div className="ns-celebration-medal" aria-hidden>
+ <Trophy />
+ <span><Check /></span>
+ </div>
+ <div className="relative z-10 px-6 pt-2 text-center">
+ <div className="mb-2 flex items-center justify-center gap-1.5 text-[11px] font-semibold tracking-[0.14em] text-[hsl(var(--notfair-accent))] uppercase">
+ <Sparkles className="size-3.5" />
+ Goal completed
+ </div>
+ <DialogHeader className="items-center text-center sm:text-center">
+ <DialogTitle className="text-[28px] leading-[1.08] tracking-[-0.035em]">
+ You did it.
+ </DialogTitle>
+ <DialogDescription
+ className="max-w-[42ch] text-[14px] leading-relaxed"
+ >
+ <span className="font-medium text-[hsl(var(--notfair-ink-2))]">
+ {label}
+ </span>{" "}
+ crossed the finish line. Every check and smart adjustment
+ added up to this result.
+ </DialogDescription>
+ </DialogHeader>
+ </div>
+ </div>
+
+ <div className="px-6 pt-1 pb-6">
+ <div className="grid grid-cols-2 gap-2 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.62)] p-1.5">
+ <div className="rounded-[9px] bg-[hsl(var(--card))] px-4 py-3 shadow-[var(--notfair-shadow-sm)]">
+ <div className="text-[10px] font-medium tracking-[0.08em] text-[hsl(var(--notfair-ink-4))] uppercase">
+ Result
+ </div>
+ <div className="mt-1 text-[22px] leading-none font-semibold tabular-nums tracking-[-0.03em]">
+ {formatMetric(currentValue)}
+ </div>
+ <div className="mt-1 truncate text-[11px] text-[hsl(var(--notfair-ink-4))]">
+ {metricName ?? "Measured goal"}
+ </div>
+ </div>
+ <div className="px-4 py-3">
+ <div className="text-[10px] font-medium tracking-[0.08em] text-[hsl(var(--notfair-ink-4))] uppercase">
+ Target
+ </div>
+ <div className="mt-1 text-[22px] leading-none font-semibold tabular-nums tracking-[-0.03em] text-[hsl(var(--notfair-accent))]">
+ {formatMetric(targetValue)}
+ </div>
+ <div className="mt-1 text-[11px] text-[hsl(var(--notfair-ink-4))]">
+ Completed {completedLabel}
+ </div>
+ </div>
+ </div>
+
+ {completionReason && (
+ <p className="mt-3 mb-0 line-clamp-2 text-center text-[12px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">
+ {completionReason}
+ </p>
+ )}
+
+ <div className="mt-5">
+ <p className="mb-2 text-center text-[12px] font-medium text-[hsl(var(--notfair-ink-3))]">
+ Ready to choose what happens next?
+ </p>
+ <div className="grid gap-2 sm:grid-cols-2">
+ <Button
+ type="button"
+ onClick={() => setStep("continue")}
+ disabled={pending}
+ >
+ Set a new target
+ <ArrowRight />
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={archive}
+ disabled={pending}
+ >
+ <Archive />
+ Archive goal
+ </Button>
+ </div>
+ {goalHref && (
+ <Button
+ asChild
+ variant="ghost"
+ className="mt-1 w-full text-[12px] text-[hsl(var(--notfair-ink-4))]"
+ >
+ <Link href={goalHref} onClick={() => setOpen(false)}>
+ View the full story
+ <ExternalLink />
+ </Link>
+ </Button>
+ )}
+ <p className="mt-2 mb-0 text-center text-[11px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">
+ Not ready? Close this window. The Completed badge will stay
+ in your sidebar until you decide.
+ </p>
+ </div>
+ </div>
+ </>
+ ) : (
+ <form
+ className="p-6"
+ onSubmit={(event) => {
+ event.preventDefault();
+ continueGoal();
+ }}
+ >
+ <DialogHeader>
+ <button
+ type="button"
+ className="mb-3 flex w-fit items-center gap-1 rounded-md text-[12px] text-[hsl(var(--notfair-ink-4))] outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={() => setStep("celebrate")}
+ >
+ <ArrowLeft className="size-3.5" />
+ Back to your result
+ </button>
+ <DialogTitle className="text-[22px] tracking-[-0.025em]">
+ What’s the next milestone?
+ </DialogTitle>
+ <DialogDescription
+ className="leading-relaxed"
+ >
+ Keep the same metric, history, and agent. Set a target{" "}
+ {directionWord} your completed result of{" "}
+ <span className="font-medium tabular-nums text-[hsl(var(--notfair-ink-2))]">
+ {formatMetric(currentValue)}
+ </span>
+ , and the goal will start running again.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="mt-6 grid gap-5">
+ <div className="grid gap-2">
+ <Label htmlFor={`next-target-${goalId}`}>
+ New target
+ </Label>
+ <Input
+ id={`next-target-${goalId}`}
+ type="number"
+ inputMode="decimal"
+ step="any"
+ value={target}
+ onChange={(event) => updateTarget(event.target.value)}
+ placeholder={`${directionWord[0].toUpperCase()}${directionWord.slice(1)} ${formatMetric(currentValue)}`}
+ autoFocus
+ required
+ />
+ <p className="m-0 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ {metricName ?? "The same verified metric"} will stay as the
+ source of truth.
+ </p>
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor={`next-label-${goalId}`}>
+ Goal name
+ </Label>
+ <Input
+ id={`next-label-${goalId}`}
+ value={nextLabel}
+ onChange={(event) => {
+ setNextLabel(event.target.value);
+ setLabelEdited(true);
+ }}
+ maxLength={120}
+ required
+ />
+ <p className="m-0 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ This is how the new milestone appears in your sidebar.
+ </p>
+ </div>
+ <div className="grid gap-2">
+ <Label htmlFor={`next-deadline-${goalId}`}>
+ Deadline <span className="font-normal text-[hsl(var(--notfair-ink-4))]">(optional)</span>
+ </Label>
+ <Input
+ id={`next-deadline-${goalId}`}
+ type="date"
+ min={new Date().toISOString().slice(0, 10)}
+ value={deadline}
+ onChange={(event) => setDeadline(event.target.value)}
+ />
+ </div>
+ </div>
+
+ <DialogFooter className="mt-7">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setStep("celebrate")}
+ disabled={pending}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ disabled={pending || !target.trim() || !nextLabel.trim()}
+ >
+ {pending ? "Starting…" : "Start next milestone"}
+ <ArrowRight />
+ </Button>
+ </DialogFooter>
+ </form>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/notfair/src/components/sidebar-goal-group.tsx b/notfair/src/components/sidebar-goal-group.tsx
index 3c28b6bc..97faafb4 100644
--- a/notfair/src/components/sidebar-goal-group.tsx
+++ b/notfair/src/components/sidebar-goal-group.tsx
@@ -6,6 +6,7 @@ import { useEffect, useState, useTransition, type DragEvent } from "react";
import { toast } from "sonner";
import {
ChevronRight,
+ CircleCheck,
LayoutDashboard,
MoreVertical,
Pencil,
@@ -53,12 +54,15 @@ export function SidebarGoalGroup({
groupId,
name,
href,
+ completedCount = 0,
children,
}: {
groupId: string;
name: string;
/** Group dashboard route. */
href: string;
+ /** Unarchived achievements inside a collapsed group remain discoverable. */
+ completedCount?: number;
children?: React.ReactNode;
}) {
const router = useRouter();
@@ -133,6 +137,15 @@ export function SidebarGoalGroup({
)}
>
<span className="truncate">{name}</span>
+ {completedCount > 0 && (
+ <span
+ aria-label={`${completedCount} completed goal${completedCount === 1 ? "" : "s"}`}
+ className="ml-auto flex shrink-0 items-center gap-1 rounded-full bg-[hsl(var(--notfair-accent-soft))] px-1.5 py-0.5 text-[9px] font-semibold tabular-nums text-[hsl(var(--notfair-accent))]"
+ >
+ <CircleCheck className="!size-3" />
+ {completedCount}
+ </span>
+ )}
<ChevronRight
data-group-chevron
aria-hidden
diff --git a/notfair/src/components/sidebar-goal-item.tsx b/notfair/src/components/sidebar-goal-item.tsx
index 89e394a7..15c20c32 100644
--- a/notfair/src/components/sidebar-goal-item.tsx
+++ b/notfair/src/components/sidebar-goal-item.tsx
@@ -15,6 +15,7 @@ import {
Pin,
PinOff,
Play,
+ Sparkles,
Trash2,
TriangleAlert,
} from "lucide-react";
@@ -56,9 +57,19 @@ import {
moveGoalToGroupAction,
} from "@/server/actions/goal-groups";
import { GOAL_DRAG_TYPE } from "@/components/sidebar-goal-group";
+import { GoalCompletionDialog } from "@/components/goal-completion-dialog";
import { cn } from "@/lib/utils";
-type LiveStatus = "intake" | "proposed" | "active" | "paused";
+type SidebarStatus = "intake" | "proposed" | "active" | "paused" | "achieved";
+
+type CompletionSummary = {
+ metricName: string | null;
+ currentValue: number | null;
+ targetValue: number | null;
+ metricDirection: "increase" | "decrease" | null;
+ completionReason: string | null;
+ completedAt: string;
+};
/**
* One goal row in the sidebar rail: link to the goal screen plus a ⋮ menu
@@ -78,13 +89,14 @@ export function SidebarGoalItem({
groups,
groupId,
needsAttention = false,
+ completion,
}: {
href: string;
/** Project home — where the user lands after deleting the open goal. */
homeHref: string;
goalId: string;
label: string;
- status: LiveStatus;
+ status: SidebarStatus;
pinned: boolean;
labelClass: string;
projectSlug: string;
@@ -94,6 +106,8 @@ export function SidebarGoalItem({
groupId: string | null;
/** Open "Needs you" escalations — renders the amber attention mark. */
needsAttention?: boolean;
+ /** Achievement evidence for the celebration handoff. */
+ completion?: CompletionSummary;
}) {
const router = useRouter();
const pathname = usePathname();
@@ -141,6 +155,7 @@ export function SidebarGoalItem({
<SidebarMenuButton asChild>
<Link
href={href}
+ className={cn(status === "achieved" && "pr-[7.4rem]!")}
draggable
onDragStart={(e) => {
e.dataTransfer.setData(GOAL_DRAG_TYPE, goalId);
@@ -163,6 +178,30 @@ export function SidebarGoalItem({
</Link>
</SidebarMenuButton>
+ {status === "achieved" && completion && (
+ <GoalCompletionDialog
+ goalId={goalId}
+ label={label}
+ metricName={completion.metricName}
+ currentValue={completion.currentValue}
+ targetValue={completion.targetValue}
+ metricDirection={completion.metricDirection}
+ completionReason={completion.completionReason}
+ completedAt={completion.completedAt}
+ goalHref={href}
+ trigger={
+ <SidebarMenuAction
+ data-completion-badge
+ className="ns-completed-badge right-7 top-1 !h-6 !w-auto gap-1 rounded-full bg-[hsl(var(--notfair-accent-soft))] px-2 text-[10px] font-semibold text-[hsl(var(--notfair-accent))] shadow-[inset_0_0_0_1px_hsl(var(--notfair-accent-border))] hover:bg-[hsl(var(--notfair-accent-soft))] hover:text-[hsl(var(--notfair-accent))]"
+ aria-label={`Celebrate completed goal: ${label}`}
+ >
+ <Sparkles className="!size-3" />
+ <span>Completed</span>
+ </SidebarMenuAction>
+ }
+ />
+ )}
+
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuAction showOnHover aria-label={`Goal actions: ${label}`}>
diff --git a/notfair/src/server/actions/goals.test.ts b/notfair/src/server/actions/goals.test.ts
index 62797437..d9dba596 100644
--- a/notfair/src/server/actions/goals.test.ts
+++ b/notfair/src/server/actions/goals.test.ts
@@ -1,6 +1,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
+ archiveAchievedGoal: vi.fn(),
+ continueAchievedGoal: vi.fn(),
revalidatePath: vi.fn(),
createGoal: vi.fn(),
deleteGoalsForAgent: vi.fn(),
@@ -15,6 +17,7 @@ const mocks = vi.hoisted(() => ({
cascadeDeleteAgentArtifacts: vi.fn(),
getProject: vi.fn(),
provisionGoalAgent: vi.fn(),
+ syncGoalIdentity: vi.fn(),
agentExistsOnDisk: vi.fn(),
listProjectAgents: vi.fn(),
runGoalIntake: vi.fn(),
@@ -24,6 +27,8 @@ const mocks = vi.hoisted(() => ({
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
vi.mock("@/server/db/goals", () => ({
+ archiveAchievedGoal: mocks.archiveAchievedGoal,
+ continueAchievedGoal: mocks.continueAchievedGoal,
createGoal: mocks.createGoal,
deleteGoalsForAgent: mocks.deleteGoalsForAgent,
endActionObservation: mocks.endActionObservation,
@@ -44,6 +49,7 @@ vi.mock("@/server/goals/provision", () => ({
goalAgentIdFor: (slug: string, n: number) => `${slug}--goal-${n}`,
goalAgentUrlSlug: (n: number) => `goal-${n}`,
provisionGoalAgent: mocks.provisionGoalAgent,
+ syncGoalIdentity: mocks.syncGoalIdentity,
}));
vi.mock("@/server/agent-meta", () => ({
agentExistsOnDisk: mocks.agentExistsOnDisk,
@@ -54,6 +60,8 @@ vi.mock("@/server/goals/tick", () => ({ runGoalTick: mocks.runGoalTick }));
vi.mock("@/server/goals/checks", () => ({ listCheckRows: mocks.listCheckRows }));
import {
+ archiveCompletedGoalAction,
+ continueCompletedGoalAction,
createGoalAgentAction,
deleteGoalAction,
getAgentGoalAction,
@@ -82,7 +90,10 @@ beforeEach(() => {
mocks.listProjectAgents.mockResolvedValue([]);
mocks.agentExistsOnDisk.mockResolvedValue(false);
mocks.createGoal.mockReturnValue(goal);
+ mocks.archiveAchievedGoal.mockReturnValue({ ...goal, status: "achieved" });
+ mocks.continueAchievedGoal.mockReturnValue(goal);
mocks.provisionGoalAgent.mockResolvedValue(undefined);
+ mocks.syncGoalIdentity.mockResolvedValue(undefined);
mocks.runGoalIntake.mockResolvedValue(undefined);
mocks.runGoalTick.mockResolvedValue(undefined);
mocks.getGoal.mockReturnValue(goal);
@@ -183,6 +194,36 @@ describe("goal lifecycle actions", () => {
await expect(resumeGoalAction(goal.id)).resolves.toEqual({ ok: true });
expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "active", "resumed by user");
});
+
+ it("archives an achievement without deleting it", async () => {
+ await expect(archiveCompletedGoalAction(goal.id)).resolves.toEqual({ ok: true });
+ expect(mocks.archiveAchievedGoal).toHaveBeenCalledWith(goal.id);
+ expect(mocks.deleteGoalsForAgent).not.toHaveBeenCalled();
+
+ mocks.archiveAchievedGoal.mockReturnValue(null);
+ await expect(archiveCompletedGoalAction(goal.id)).resolves.toMatchObject({
+ ok: false,
+ });
+ });
+
+ it("continues an achievement with a new milestone and immediate check", async () => {
+ const continued = { ...goal, target_value: 150 };
+ mocks.continueAchievedGoal.mockReturnValue(continued);
+ await expect(
+ continueCompletedGoalAction(goal.id, {
+ target_value: 150,
+ deadline: "2030-12-31",
+ label: "Qualified visits → 150",
+ }),
+ ).resolves.toEqual({ ok: true });
+ expect(mocks.continueAchievedGoal).toHaveBeenCalledWith(goal.id, {
+ target_value: 150,
+ deadline: "2030-12-31",
+ short_label: "Qualified visits → 150",
+ });
+ expect(mocks.syncGoalIdentity).toHaveBeenCalledWith(continued);
+ expect(mocks.runGoalTick).toHaveBeenCalledWith(continued, "manual");
+ });
});
describe("deletion, locks, and escalations", () => {
diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.ts
index 58dea7cc..3cda1cf6 100644
--- a/notfair/src/server/actions/goals.ts
+++ b/notfair/src/server/actions/goals.ts
@@ -2,6 +2,8 @@
import { revalidatePath } from "next/cache";
import {
+ archiveAchievedGoal,
+ continueAchievedGoal,
createGoal,
deleteGoalsForAgent,
endActionObservation,
@@ -24,6 +26,7 @@ import {
import { agentExistsOnDisk, listProjectAgents } from "@/server/agent-meta";
import { runGoalIntake } from "@/server/goals/intake";
import { runGoalTick } from "@/server/goals/tick";
+import { syncGoalIdentity } from "@/server/goals/provision";
import { listCheckRows, type CheckFilter, type CheckRow } from "@/server/goals/checks";
export type GoalActionResult = {
@@ -140,6 +143,80 @@ export async function killGoalAction(
return { ok: true };
}
+/**
+ * Remove a completed goal from daily navigation while preserving its
+ * achievement, agent workspace, conversation, checks, and evidence.
+ */
+export async function archiveCompletedGoalAction(
+ goal_id: string,
+): Promise<GoalActionResult> {
+ const goal = archiveAchievedGoal(goal_id);
+ if (!goal) {
+ return { ok: false, error: "Only a completed goal can be archived." };
+ }
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/**
+ * Continue an achieved goal with a more ambitious target. The metric and
+ * history stay intact, the heartbeat restarts, and an immediate check lets
+ * the same agent re-anchor on the new milestone.
+ */
+export async function continueCompletedGoalAction(
+ goal_id: string,
+ input: {
+ target_value: number;
+ deadline?: string | null;
+ label?: string | null;
+ },
+): Promise<GoalActionResult> {
+ const deadline = input.deadline?.trim() || null;
+ if (
+ deadline &&
+ (!/^\d{4}-\d{2}-\d{2}$/.test(deadline) ||
+ Number.isNaN(new Date(`${deadline}T23:59:59`).getTime()))
+ ) {
+ return { ok: false, error: "Enter a valid deadline." };
+ }
+ if (
+ deadline &&
+ new Date(`${deadline}T23:59:59`).getTime() < Date.now()
+ ) {
+ return { ok: false, error: "Choose today or a future deadline." };
+ }
+ const label = input.label?.trim() || null;
+ if (label && label.length > 120) {
+ return { ok: false, error: "Keep the goal name to 120 characters." };
+ }
+
+ let goal;
+ try {
+ goal = continueAchievedGoal(goal_id, {
+ target_value: input.target_value,
+ deadline,
+ short_label: label,
+ });
+ } catch (err) {
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ };
+ }
+ if (!goal) {
+ return { ok: false, error: "This goal is no longer awaiting a next step." };
+ }
+
+ void syncGoalIdentity(goal).catch((err) =>
+ console.warn("[goal-actions] continued-goal identity sync failed:", err),
+ );
+ void runGoalTick(goal, "manual").catch((err) =>
+ console.error("[goal-actions] continued-goal check failed:", err),
+ );
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
/** Rename the goal's display label (the sidebar/board handle). */
export async function renameGoalAction(
goal_id: string,
diff --git a/notfair/src/server/actions/harness.test.ts b/notfair/src/server/actions/harness.test.ts
index b12bfbce..047899d5 100644
--- a/notfair/src/server/actions/harness.test.ts
+++ b/notfair/src/server/actions/harness.test.ts
@@ -5,11 +5,15 @@ const mocks = vi.hoisted(() => ({
homedir: vi.fn(() => "/home/user"),
spawn: vi.fn(),
refreshUsage: vi.fn(),
+ resolveCodexBinary: vi.fn(() => "codex"),
}));
vi.mock("node:os", () => ({ default: { homedir: mocks.homedir } }));
vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
vi.mock("@/server/harness-usage", () => ({ refreshHarnessUsage: mocks.refreshUsage }));
+vi.mock("@/server/adapters/codex-local/binary", () => ({
+ resolveCodexBinary: mocks.resolveCodexBinary,
+}));
import { refreshCodexUsageAction, startCodexLoginAction } from "./harness";
diff --git a/notfair/src/server/actions/harness.ts b/notfair/src/server/actions/harness.ts
index 27f7b48d..01010ae3 100644
--- a/notfair/src/server/actions/harness.ts
+++ b/notfair/src/server/actions/harness.ts
@@ -6,8 +6,7 @@ import {
refreshHarnessUsage,
type HarnessUsage,
} from "@/server/harness-usage";
-
-const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
+import { resolveCodexBinary } from "@/server/adapters/codex-local/binary";
export type StartCodexLoginResult =
| { ok: true; alreadySignedIn: boolean }
@@ -29,7 +28,7 @@ export async function startCodexLoginAction(): Promise<StartCodexLoginResult> {
}
try {
- const child = spawn(CODEX_BIN, ["login"], {
+ const child = spawn(resolveCodexBinary(), ["login"], {
cwd: os.homedir(),
detached: true,
stdio: "ignore",
diff --git a/notfair/src/server/adapters/codex-local/binary.test.ts b/notfair/src/server/adapters/codex-local/binary.test.ts
new file mode 100644
index 00000000..cb02b724
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/binary.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from "vitest";
+import { resolveCodexBinary } from "./binary";
+
+describe("resolveCodexBinary", () => {
+ it("honors an explicit executable override", () => {
+ const isExecutable = vi.fn();
+
+ expect(
+ resolveCodexBinary({
+ env: {
+ NOTFAIR_CODEX_BIN: " /custom/codex-nightly ",
+ PATH: "/bin",
+ },
+ isExecutable,
+ }),
+ ).toBe("/custom/codex-nightly");
+ expect(isExecutable).not.toHaveBeenCalled();
+ });
+
+ it("prefers an executable already present on PATH", () => {
+ expect(
+ resolveCodexBinary({
+ env: { PATH: "/managed/bin:/usr/bin" },
+ homeDir: "/Users/tester",
+ platform: "darwin",
+ isExecutable: (candidate) => candidate === "/managed/bin/codex",
+ }),
+ ).toBe("/managed/bin/codex");
+ });
+
+ it("finds the Codex executable bundled with ChatGPT on macOS", () => {
+ expect(
+ resolveCodexBinary({
+ env: { PATH: "/usr/bin:/bin" },
+ homeDir: "/Users/tester",
+ platform: "darwin",
+ isExecutable: (candidate) =>
+ candidate === "/Applications/ChatGPT.app/Contents/Resources/codex",
+ }),
+ ).toBe("/Applications/ChatGPT.app/Contents/Resources/codex");
+ });
+
+ it("checks a user-local ChatGPT installation", () => {
+ expect(
+ resolveCodexBinary({
+ env: { PATH: "/usr/bin:/bin" },
+ homeDir: "/Users/tester",
+ platform: "darwin",
+ isExecutable: (candidate) =>
+ candidate ===
+ "/Users/tester/Applications/ChatGPT.app/Contents/Resources/codex",
+ }),
+ ).toBe(
+ "/Users/tester/Applications/ChatGPT.app/Contents/Resources/codex",
+ );
+ });
+
+ it("falls back to the command name so spawn can report the final error", () => {
+ expect(
+ resolveCodexBinary({
+ env: { PATH: "/usr/bin:/bin" },
+ homeDir: "/home/tester",
+ platform: "linux",
+ isExecutable: () => false,
+ }),
+ ).toBe("codex");
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/binary.ts b/notfair/src/server/adapters/codex-local/binary.ts
new file mode 100644
index 00000000..a09ab89e
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/binary.ts
@@ -0,0 +1,64 @@
+import { accessSync, constants } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+type ResolveCodexBinaryOptions = {
+ env?: {
+ PATH?: string;
+ NOTFAIR_CODEX_BIN?: string;
+ };
+ homeDir?: string;
+ platform?: NodeJS.Platform;
+ isExecutable?: (candidate: string) => boolean;
+};
+
+function canExecute(candidate: string): boolean {
+ try {
+ accessSync(candidate, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Resolve Codex without assuming the server inherited an interactive shell's
+ * PATH. macOS background services commonly miss app-bundled executables even
+ * though Codex is available through the ChatGPT desktop app.
+ */
+export function resolveCodexBinary(
+ options: ResolveCodexBinaryOptions = {},
+): string {
+ const env = options.env ?? process.env;
+ const explicit = env.NOTFAIR_CODEX_BIN?.trim();
+ if (explicit) return explicit;
+
+ const platform = options.platform ?? process.platform;
+ const homeDir = options.homeDir ?? homedir();
+ const executableName = platform === "win32" ? "codex.exe" : "codex";
+ const pathSeparator = platform === "win32" ? ";" : ":";
+ const candidates = (env.PATH ?? "")
+ .split(pathSeparator)
+ .filter(Boolean)
+ .map((directory) => join(directory, executableName));
+
+ if (platform === "darwin") {
+ candidates.push(
+ "/Applications/ChatGPT.app/Contents/Resources/codex",
+ join(homeDir, "Applications/ChatGPT.app/Contents/Resources/codex"),
+ "/Applications/Codex.app/Contents/Resources/codex",
+ join(homeDir, "Applications/Codex.app/Contents/Resources/codex"),
+ );
+ }
+
+ if (platform !== "win32") {
+ candidates.push(
+ join(homeDir, ".local/bin/codex"),
+ "/opt/homebrew/bin/codex",
+ "/usr/local/bin/codex",
+ );
+ }
+
+ const isExecutable = options.isExecutable ?? canExecute;
+ return [...new Set(candidates)].find(isExecutable) ?? "codex";
+}
diff --git a/notfair/src/server/adapters/codex-local/execute.test.ts b/notfair/src/server/adapters/codex-local/execute.test.ts
index a7aaa316..5287a458 100644
--- a/notfair/src/server/adapters/codex-local/execute.test.ts
+++ b/notfair/src/server/adapters/codex-local/execute.test.ts
@@ -9,11 +9,15 @@ import type { HarnessEvent, HarnessExecuteContext } from "../types";
const mocks = vi.hoisted(() => ({
spawn: vi.fn(),
+ resolveCodexBinary: vi.fn(() => "codex"),
getOrCreateMcpServerSecret: vi.fn(() => "machine-secret"),
listProjectMcpTokens: vi.fn(() => [] as { server_name: string; access_token_enc: string }[]),
}));
vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+vi.mock("./binary", () => ({
+ resolveCodexBinary: mocks.resolveCodexBinary,
+}));
vi.mock("@/server/mcp-server/secret", () => ({
getOrCreateMcpServerSecret: mocks.getOrCreateMcpServerSecret,
}));
diff --git a/notfair/src/server/adapters/codex-local/execute.ts b/notfair/src/server/adapters/codex-local/execute.ts
index 87b707cf..63c86f2a 100644
--- a/notfair/src/server/adapters/codex-local/execute.ts
+++ b/notfair/src/server/adapters/codex-local/execute.ts
@@ -4,11 +4,10 @@ import { join } from "node:path";
import type { HarnessEvent, HarnessExecuteContext } from "../types";
import { makeCodexStreamState, parseCodexLine } from "./parse";
import { bearerEnvVarForServer } from "./mcp";
+import { resolveCodexBinary } from "./binary";
import { getOrCreateMcpServerSecret } from "@/server/mcp-server/secret";
import { listProjectMcpTokens } from "@/server/mcp/tokens";
-const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
-
/**
* Stream one chat turn through the Codex CLI.
*
@@ -79,7 +78,7 @@ export async function* executeCodexLocal(
for (const token of listProjectMcpTokens(ctx.projectSlug)) {
mcpEnv[bearerEnvVarForServer(token.server_name)] = token.access_token_enc;
}
- const child = spawn(CODEX_BIN, args, {
+ const child = spawn(resolveCodexBinary(), args, {
cwd: ctx.workspaceDir,
env: {
...process.env,
diff --git a/notfair/src/server/adapters/codex-local/test.test.ts b/notfair/src/server/adapters/codex-local/test.test.ts
index e3da2179..c53a2189 100644
--- a/notfair/src/server/adapters/codex-local/test.test.ts
+++ b/notfair/src/server/adapters/codex-local/test.test.ts
@@ -2,8 +2,14 @@ import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ resolveCodexBinary: vi.fn(() => "codex"),
+}));
vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+vi.mock("./binary", () => ({
+ resolveCodexBinary: mocks.resolveCodexBinary,
+}));
import { testCodexLocalEnvironment } from "./test";
@@ -61,7 +67,7 @@ describe("testCodexLocalEnvironment", () => {
scriptVersionCmd({ spawnError: true });
const health = await testCodexLocalEnvironment();
expect(health.ok).toBe(false);
- expect(health.message).toContain("`codex` not found on PATH");
+ expect(health.message).toContain("Codex CLI check failed for `codex`");
});
it("times out a hung probe instead of waiting forever", async () => {
diff --git a/notfair/src/server/adapters/codex-local/test.ts b/notfair/src/server/adapters/codex-local/test.ts
index ff79709e..ebfd0081 100644
--- a/notfair/src/server/adapters/codex-local/test.ts
+++ b/notfair/src/server/adapters/codex-local/test.ts
@@ -1,15 +1,15 @@
import { spawn } from "node:child_process";
import type { HarnessEnvironmentHealth } from "../types";
-
-const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
+import { resolveCodexBinary } from "./binary";
export async function testCodexLocalEnvironment(): Promise<HarnessEnvironmentHealth> {
- const versionResult = await runCmd(CODEX_BIN, ["--version"]);
+ const codexBin = resolveCodexBinary();
+ const versionResult = await runCmd(codexBin, ["--version"]);
if (versionResult.code !== 0) {
return {
ok: false,
auth: "unknown",
- message: `\`${CODEX_BIN}\` not found on PATH. Install: https://github.com/openai/codex`,
+ message: `Codex CLI check failed for \`${codexBin}\`. Install Codex or set NOTFAIR_CODEX_BIN to its executable path.`,
};
}
return {
diff --git a/notfair/src/server/db/goals.test.ts b/notfair/src/server/db/goals.test.ts
index cca2dcae..9ba84519 100644
--- a/notfair/src/server/db/goals.test.ts
+++ b/notfair/src/server/db/goals.test.ts
@@ -13,16 +13,24 @@ vi.hoisted(() => {
import { getDb } from "./db";
import {
+ archiveAchievedGoal,
+ continueAchievedGoal,
createGoal,
createGoalAction,
deleteGoalsForAgent,
endActionObservation,
getGoal,
getPinnedGoalIds,
+ isGoalArchived,
listGatedActions,
+ listSidebarGoals,
+ proposeTarget,
recordMetricSnapshot,
renameGoal,
+ setGoalMetric,
setGoalPinned,
+ setGoalStatus,
+ updateGoalCurrentValue,
} from "./goals";
const SLUG = "proj";
@@ -70,6 +78,70 @@ describe("goal pins", () => {
});
});
+describe("completed-goal handoff", () => {
+ it("keeps an achievement in the sidebar until archive, then can continue it", () => {
+ const goal = createGoal({
+ project_slug: SLUG,
+ agent_id: "a-achieved",
+ statement: "Reach 100 qualified visits",
+ });
+ setGoalMetric(goal.id, {
+ metric_name: "Qualified visits",
+ metric_source_key: "local",
+ metric_source_tool: "shell",
+ metric_source_args_json: "{}",
+ metric_direction: "increase",
+ baseline_value: 50,
+ });
+ proposeTarget(goal.id, { target_value: 100 });
+ updateGoalCurrentValue(goal.id, 112);
+ setGoalStatus(goal.id, "achieved", "Measured 112 qualified visits.");
+
+ expect(listSidebarGoals(SLUG).map((item) => item.id)).toContain(goal.id);
+ expect(isGoalArchived(goal.id)).toBe(false);
+
+ expect(archiveAchievedGoal(goal.id)?.status).toBe("achieved");
+ expect(isGoalArchived(goal.id)).toBe(true);
+ expect(listSidebarGoals(SLUG).map((item) => item.id)).not.toContain(goal.id);
+
+ const continued = continueAchievedGoal(goal.id, {
+ target_value: 150,
+ deadline: "2030-12-31",
+ short_label: "Qualified visits → 150",
+ });
+ expect(continued).toMatchObject({
+ status: "active",
+ target_value: 150,
+ deadline: "2030-12-31",
+ status_reason: null,
+ short_label: "Qualified visits → 150",
+ });
+ expect(continued?.next_tick_at).not.toBeNull();
+ expect(isGoalArchived(goal.id)).toBe(false);
+ expect(listSidebarGoals(SLUG).map((item) => item.id)).toContain(goal.id);
+ });
+
+ it("requires a next target beyond the completed value", () => {
+ const goal = createGoal({
+ project_slug: SLUG,
+ agent_id: "a-achieved-direction",
+ statement: "Reduce errors",
+ });
+ getDb()
+ .prepare(
+ `UPDATE goals
+ SET status = 'achieved', metric_direction = 'decrease',
+ current_value = 4, target_value = 5
+ WHERE id = ?`,
+ )
+ .run(goal.id);
+
+ expect(() =>
+ continueAchievedGoal(goal.id, { target_value: 6, deadline: null }),
+ ).toThrow(/below the completed value/i);
+ });
+});
+
describe("endActionObservation", () => {
it("releases a gated action into review-due without touching its status", () => {
const goal = createGoal({ project_slug: SLUG, agent_id: "a-unlock", statement: "x" });
diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.ts
index c6b623e7..6e7ce88c 100644
--- a/notfair/src/server/db/goals.ts
+++ b/notfair/src/server/db/goals.ts
@@ -13,6 +13,8 @@ import { getDb } from "./db";
* │
* ▼
* achieved | failed | killed (terminal)
+ * │
+ * └── user sets next milestone ──▶ active
*
* intake — goal agent is authoring + testing the metric query
* proposed — metric verified server-side, baseline measured; awaiting the
@@ -231,6 +233,114 @@ export function listLiveGoals(project_slug: string): Goal[] {
.all(project_slug) as Goal[];
}
+/**
+ * Goals shown in daily navigation. Achievements remain visible until the user
+ * explicitly archives them, which prevents the completion moment from
+ * silently disappearing between sidebar refreshes.
+ */
+export function listSidebarGoals(project_slug: string): Goal[] {
+ return getDb()
+ .prepare(
+ `SELECT g.* FROM goals g
+ LEFT JOIN goal_archives a ON a.goal_id = g.id
+ WHERE g.project_slug = ?
+ AND (
+ g.status IN ('intake','proposed','active','paused')
+ OR (g.status = 'achieved' AND a.goal_id IS NULL)
+ )
+ ORDER BY
+ CASE WHEN g.status = 'achieved' THEN 0 ELSE 1 END,
+ CASE WHEN g.status = 'achieved' THEN g.updated_at END DESC,
+ g.created_at ASC`,
+ )
+ .all(project_slug) as Goal[];
+}
+
+/** Whether an achieved goal has been dismissed from daily navigation. */
+export function isGoalArchived(id: string): boolean {
+ return Boolean(
+ getDb().prepare("SELECT 1 FROM goal_archives WHERE goal_id = ?").get(id),
+ );
+}
+
+/**
+ * Archive an achievement without changing its historical status. Idempotent
+ * so a double click cannot corrupt or rewrite the completion record.
+ */
+export function archiveAchievedGoal(id: string): Goal | null {
+ const goal = getGoal(id);
+ if (!goal || goal.status !== "achieved") return null;
+ getDb()
+ .prepare(
+ "INSERT OR IGNORE INTO goal_archives (goal_id, archived_at) VALUES (?, ?)",
+ )
+ .run(id, now());
+ return goal;
+}
+
+/**
+ * Turn a completed achievement into the next measurable milestone. This is
+ * the one intentional terminal → live transition: it keeps the same metric,
+ * evidence, chat, and agent, but requires a target beyond the freshly
+ * completed value.
+ */
+export function continueAchievedGoal(
+ id: string,
+ input: {
+ target_value: number;
+ deadline: string | null;
+ short_label?: string | null;
+ },
+): Goal | null {
+ const goal = getGoal(id);
+ if (!goal || goal.status !== "achieved") return null;
+ if (goal.current_value === null || goal.metric_direction === null) {
+ throw new Error("This goal has no current measured value to continue from.");
+ }
+ if (!Number.isFinite(input.target_value)) {
+ throw new Error("Enter a valid target.");
+ }
+ const movesForward =
+ goal.metric_direction === "increase"
+ ? input.target_value > goal.current_value
+ : input.target_value < goal.current_value;
+ if (!movesForward) {
+ const direction = goal.metric_direction === "increase" ? "above" : "below";
+ throw new Error(
+ `Set the next target ${direction} the completed value (${goal.current_value}).`,
+ );
+ }
+ const nextTick = computeNextTick(goal.cadence_cron);
+ if (!nextTick) {
+ throw new Error(`Invalid cadence cron expression: '${goal.cadence_cron}'`);
+ }
+
+ const db = getDb();
+ const update = db.transaction(() => {
+ const result = db
+ .prepare(
+ `UPDATE goals
+ SET target_value = ?, deadline = ?,
+ short_label = COALESCE(?, short_label), status = 'active',
+ status_reason = NULL, next_tick_at = ?, updated_at = ?
+ WHERE id = ? AND status = 'achieved'`,
+ )
+ .run(
+ input.target_value,
+ input.deadline,
+ input.short_label?.trim() || null,
+ nextTick,
+ now(),
+ id,
+ );
+ if (result.changes === 0) return false;
+ db.prepare("DELETE FROM goal_archives WHERE goal_id = ?").run(id);
+ return true;
+ });
+ if (!update()) return null;
+ return getGoal(id);
+}
+
/**
* Chat-intake step 1: record what the user wants (statement) plus any
* constraints they stated. Only while the goal is still in intake.
@@ -482,8 +592,9 @@ export function listGatedActionsForOtherAgents(
/**
* Status transitions outside the intake→proposed→active happy path:
- * pause/resume and the three terminal states. Terminal states are
- * one-way — a closed goal is history, not a resumable draft.
+ * pause/resume and the three terminal states. This generic transition stays
+ * one-way; the explicit achieved → active continuation is isolated in
+ * continueAchievedGoal so a failed or closed goal can never be revived.
*/
export function setGoalStatus(
id: string,
diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.ts
index f5ae6acb..4b302bc1 100644
--- a/notfair/src/server/db/schema.ts
+++ b/notfair/src/server/db/schema.ts
@@ -115,6 +115,15 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_goals_one_live_per_agent
ON goals(agent_id)
WHERE status IN ('intake','proposed','active','paused');
+-- Completing and archiving are deliberately separate moments. An achieved
+-- goal remains in the sidebar until the user celebrates it and chooses to
+-- archive it; archiving only hides it from daily navigation and preserves
+-- the goal, agent, chat, checks, and evidence.
+CREATE TABLE IF NOT EXISTS goal_archives (
+ goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,
+ archived_at TEXT NOT NULL
+);
+
-- 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
diff --git a/notfair/src/server/harness-usage.ts b/notfair/src/server/harness-usage.ts
index 04093994..d0ce5221 100644
--- a/notfair/src/server/harness-usage.ts
+++ b/notfair/src/server/harness-usage.ts
@@ -2,6 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
+import { resolveCodexBinary } from "@/server/adapters/codex-local/binary";
/**
* Read what each local AI-agent harness exposes about the user's account
@@ -85,7 +86,6 @@ export type HarnessUsage =
type CacheEntry = { until: number; value: HarnessUsage };
const cache = new Map<string, CacheEntry>();
const CACHE_TTL_MS = 60_000;
-const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
export async function readHarnessUsage(
adapter: "claude-code-local" | "codex-local",
@@ -271,7 +271,7 @@ async function readCodexLoginStatus(): Promise<CodexAuthStatus> {
return new Promise((resolve) => {
let output = "";
let settled = false;
- const child = spawn(CODEX_BIN, ["login", "status"], {
+ const child = spawn(resolveCodexBinary(), ["login", "status"], {
stdio: ["ignore", "pipe", "pipe"],
});
const finish = () => {