Skip to content

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

feat: governed goal code changes and truthful Codex UI (#95)

Yuting Zhonga56534be2357
diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.md
index 64442f32..6950d2a2 100644
--- a/notfair/CHANGELOG.md
+++ b/notfair/CHANGELOG.md
@@ -2,6 +2,16 @@
## Unreleased
+**Codex account and model state now match the local CLI.** The sidebar reads authentication independently from usage availability, shows the correct ChatGPT Pro label, keeps authenticated users signed in when a rate-limit window is absent, and offers a working manual sign-in button when Codex is actually logged out. The chat model selector now names the configured Codex model instead of showing an opaque “Default” label.
+
+**Completed checks stop looking active.** A harness final event now renders as a static “Turn complete” state with no spinner, heartbeat, shimmer, or increasing timer. Read-only check logs also explain that follow-up belongs in the goal chat instead of implying the agent is still working forever.
+
+**Code changes go through pull requests — and the loop tracks them natively.** Goals whose levers live in your website's code (SEO above all) now have a sanctioned, governed channel: the agent may change code only inside the workspace's **Codebase folder** (new Settings card, validated + editable any time), only on a `notfair/…` branch, and only via a PR it registers with the new `register_pull_request` tool — never a direct push, never merging its own PR. You review and merge on GitHub, exactly like any teammate's PR. The platform syncs PR state through your authenticated `gh` CLI on every check (and when you view the goal), so each tick brief carries the live truth: changes requested → the agent addresses your review comments that tick; awaiting review → your Goal tab and the goals index show a "PR needs your review" badge; merged → the observation window measures from there; closed unmerged → the agent scores the action as rejected and learns. Open PRs also pin the heartbeat to its normal cadence (no smart-sleep past a pending review). Without a codebase folder set, code stays off-limits and agents log recommendations instead.
+
+**Fix: the START button now appears without a manual reload.** The goal page only auto-refreshed during `intake` and `active`, so once the metric verified (→ `proposed`) the page went static — the agent would say "press START" but the button never rendered until you reloaded. `proposed` goals now poll too, so the target recording and the START card surface live.
+
+**Goal creation gets a platform focus — dynamic per workspace.** The goal form (goals index and a new onboarding step 3, "First goal") shows one focus chip per connected platform — Google Ads, Meta Ads, SEO (Search Console), X Ads, Analytics — plus "Other". Picking a focus swaps in platform-appropriate placeholder text and tap-to-fill example statements, and the choice rides along to the agent's intake kickoff so it explores the right platform even when the statement is ambiguous. Connect Search Console and SEO goals are one tap away — without auto-flooding the index with machine-proposed goals (the audited X Ads suggestions remain the only auto-generated ones). Onboarding now ends by minting that first goal instead of dropping you on an empty index; skippable, and the workspace form is identical.
+
**Pick which account each connection targets — right where you connect.** Multi-account MCPs (Google Ads, Meta Ads, Search Console) now resolve their workspace account/property on the Connections page, not just in onboarding. Finishing OAuth auto-keeps a still-valid selection, silently persists the only reachable account, and otherwise opens a picker dialog listing what the new token can reach. Each card carries one action tracking its setup state — **Connect** → **Choose account/property** → a quiet **Switch account/property** — with the persisted selection shown on the card (`Search Console property: sc-domain:example.com`) and Disconnect / Remove tucked into the ⋯ menu, so switching accounts never requires reconnecting. Selections persist on the workspace row and feed every goal agent's identity, keeping each workspace's agents on exactly one account per platform. Onboarding's connect step now renders the same `McpCard` rows and picker dialog as the Connections page — its bespoke connector tiles and three full-page picker steps are gone, so the Connect → Choose → Switch lifecycle is identical on both surfaces, and the picker's rows use the design system's elevated surfaces instead of borders. The account-selection layer is covered by the repo's first vitest suite (`pnpm test`).
## 0.9.0 — 2026-07-10
diff --git a/notfair/CLAUDE.md b/notfair/CLAUDE.md
index d731031d..0e4646d7 100644
--- a/notfair/CLAUDE.md
+++ b/notfair/CLAUDE.md
@@ -23,6 +23,10 @@ This repo carries no migrations or legacy/compat code. Verification is:
Mock at the server-action / db-module boundary (`vi.mock`), not deeper.
Test pure logic and user-visible component behavior — don't unit-test
Next.js pages or route handlers; the live smoke covers those.
+ SQLite tests use the real better-sqlite3 against a tmpdir — and the
+ `NOTFAIR_DATA_DIR` override MUST be set inside `vi.hoisted(...)`:
+ static imports evaluate before module-level statements, so a plain
+ assignment points the suite at the developer's live `~/.notfair`.
3. `pnpm build` — must be clean.
4. Live smoke: `pnpm dev` (port 3326), then walk the affected flow in the
browser (goal index → goal page → chat / START / checks).
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx
index 8b6ef9a6..cc442222 100644
--- a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx
@@ -69,6 +69,8 @@ export default async function CheckTranscriptPage({
initialEvents={initialEvents}
initialCursor={initialCursor}
composerDisabled
+ disabledComposerPlaceholder="This check log is read-only — follow up from the goal chat"
+ showCompletedStatus
mcpCatalog={mcpCatalog}
/>
</div>
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
index 63459d29..2c21ab5c 100644
--- a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
@@ -37,6 +37,8 @@ import { GoalStartButton } from "@/components/goal-start-button";
import { GoalAutoRefresh } from "@/components/goal-auto-refresh";
import { GoalProgressChart } from "@/components/goal-progress-chart";
import { GoalChecksStrip } from "@/components/goal-checks-strip";
+import { listGoalPrs, type GoalPr } from "@/server/db/goal-prs";
+import { maybeSyncGoalPrs } from "@/server/goals/pr-sync";
import { buildCheckSquares, currentStreak } from "@/lib/goal-streak";
export const dynamic = "force-dynamic";
@@ -112,9 +114,15 @@ export default async function GoalPage({
return (
<div className="flex min-h-0 flex-1 flex-col">
- {(goal.status === "intake" || goal.status === "active") && (
- <GoalAutoRefresh intervalMs={8000} />
- )}
+ {/* Every pre-terminal state before START changes server-side via
+ agent tool calls: intake verifies the metric (→ proposed), and a
+ proposed goal's target lands via propose_target — which is what
+ makes the START button appear. Without polling `proposed`, the
+ user is told "press START" but the button never renders until a
+ manual reload. */}
+ {(goal.status === "intake" ||
+ goal.status === "proposed" ||
+ goal.status === "active") && <GoalAutoRefresh intervalMs={8000} />}
{/* Header: the goal is the title. */}
<header className="flex items-center gap-3 px-5 py-2.5">
@@ -191,6 +199,11 @@ function GoalRail({
const allActions = listGoalActions(goal.id, 100);
const targetMet = isTargetMet(goal);
const tickRunning = ticks.some((t) => t.status === "running");
+ // PRs the agent opened against the codebase. Kick a background GitHub
+ // sync when rows look stale — the page's auto-refresh poll picks up the
+ // fresh state a moment later without blocking this render.
+ const prs = listGoalPrs(goal.id, 10);
+ if (prs.some((pr) => pr.state === "open")) maybeSyncGoalPrs(goal.id);
// Chart data — plain-JSON props for the client component.
const chartPoints = snapshots.map((sn) => ({
@@ -364,6 +377,17 @@ function GoalRail({
</div>
)}
+ {prs.length > 0 && (
+ <div>
+ <RailHeading>Pull requests</RailHeading>
+ <ul className="m-0 flex list-none flex-col gap-2.5 p-0">
+ {prs.map((pr) => (
+ <PrItem key={pr.id} pr={pr} />
+ ))}
+ </ul>
+ </div>
+ )}
+
<div>
<RailHeading>Checks</RailHeading>
{ticks.length === 0 ? (
@@ -436,6 +460,54 @@ function TickItem({
);
}
+function PrItem({ pr }: { pr: GoalPr }) {
+ const needsReview =
+ pr.state === "open" &&
+ !pr.is_draft &&
+ pr.review_decision !== "CHANGES_REQUESTED";
+ return (
+ <li className="text-[12px] leading-snug">
+ <div className="flex items-baseline justify-between gap-2">
+ <a
+ href={pr.url}
+ target="_blank"
+ rel="noreferrer"
+ className="ns-link min-w-0 truncate font-medium"
+ >
+ {pr.title}
+ </a>
+ <span className="shrink-0 text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {timeAgo(pr.created_at)}
+ </span>
+ </div>
+ <p className="m-0 mt-0.5 flex flex-wrap items-center gap-1.5">
+ {pr.state === "merged" ? (
+ <span className="ns-tag">merged</span>
+ ) : pr.state === "closed" ? (
+ <span className="ns-tag-red">closed unmerged</span>
+ ) : pr.is_draft ? (
+ <span className="ns-tag">draft</span>
+ ) : pr.review_decision === "CHANGES_REQUESTED" ? (
+ <span className="ns-tag-amber">changes requested — agent's turn</span>
+ ) : (
+ <span className="ns-tag-accent">needs your review</span>
+ )}
+ {pr.comment_count > 0 && (
+ <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">
+ {pr.comment_count} comment{pr.comment_count === 1 ? "" : "s"}
+ </span>
+ )}
+ {pr.branch && <span className="ns-tag-mono">{pr.branch}</span>}
+ </p>
+ {pr.sync_error && (
+ <p className="m-0 mt-0.5 text-[11px] text-[hsl(var(--notfair-warn))]">
+ sync failed: {pr.sync_error}
+ </p>
+ )}
+ </li>
+ );
+}
+
function RailCard({ children }: { children: React.ReactNode }) {
return <div className="ns-card p-3.5">{children}</div>;
}
diff --git a/notfair/src/app/(app)/[project]/page.tsx b/notfair/src/app/(app)/[project]/page.tsx
index d71672a8..a6610b76 100644
--- a/notfair/src/app/(app)/[project]/page.tsx
+++ b/notfair/src/app/(app)/[project]/page.tsx
@@ -10,6 +10,7 @@ import {
type Goal,
} from "@/server/db/goals";
import { listProjectMcpTokens } from "@/server/mcp/tokens";
+import { listPrsAwaitingReview } from "@/server/db/goal-prs";
import { listOpenSuggestions } from "@/server/db/suggestions";
import {
listSuggestionRuns,
@@ -71,7 +72,13 @@ export default async function ProjectGoalsPage({
}
return { agent: a, goal, snapshots, delta };
});
- const connectedCount = listProjectMcpTokens(slug).length;
+ const connectedMcpKeys = listProjectMcpTokens(slug).map((t) => t.server_name);
+ const connectedCount = connectedMcpKeys.length;
+ // Goals with a PR sitting on the user's side of the net — surfaced as a
+ // badge on the row so review requests are visible from the index.
+ const goalIdsAwaitingPrReview = new Set(
+ listPrsAwaitingReview(slug).map((pr) => pr.goal_id),
+ );
// Account analysis → suggested goals. First index visit after a connect
// (or after a restart dropped a run) kicks the audit in the background;
@@ -94,7 +101,7 @@ export default async function ProjectGoalsPage({
</header>
<div className="mb-6">
- <NewGoalForm projectSlug={slug} />
+ <NewGoalForm projectSlug={slug} connectedMcpKeys={connectedMcpKeys} />
</div>
{connectedCount === 0 && (
@@ -175,6 +182,9 @@ export default async function ProjectGoalsPage({
<span className="ns-row-title-row">
<span className="ns-row-title">{goal ? goalLabel(goal) : agent.name}</span>
{goal && <span className="ns-tag">{STATUS_LABEL[goal.status]}</span>}
+ {goal && goalIdsAwaitingPrReview.has(goal.id) && (
+ <span className="ns-tag-accent">PR needs your review</span>
+ )}
</span>
<span className="ns-row-desc block">
{goal?.statement?.trim()
diff --git a/notfair/src/app/(app)/[project]/settings/page.tsx b/notfair/src/app/(app)/[project]/settings/page.tsx
index 30782c81..8833c927 100644
--- a/notfair/src/app/(app)/[project]/settings/page.tsx
+++ b/notfair/src/app/(app)/[project]/settings/page.tsx
@@ -2,6 +2,7 @@ import { notFound } from "next/navigation";
import { getProject } from "@/server/db/projects";
import { DangerZone } from "@/components/danger-zone";
import { ProjectRenameCard } from "@/components/project-rename-card";
+import { CodebasePathCard } from "@/components/codebase-path-card";
import { WorkspaceBrowserCard } from "@/components/workspace-browser-card";
export default async function SettingsPage({
@@ -61,6 +62,16 @@ export default async function SettingsPage({
</div>
</section>
+ <section>
+ <h2 className="ns-h2">
+ <span>Codebase</span>
+ </h2>
+ <CodebasePathCard
+ projectSlug={project.slug}
+ currentPath={project.codebase_path}
+ />
+ </section>
+
<section>
<h2 className="ns-h2">
<span>Workspace browser</span>
diff --git a/notfair/src/app/onboarding/page.tsx b/notfair/src/app/onboarding/page.tsx
index 864bd512..534a5605 100644
--- a/notfair/src/app/onboarding/page.tsx
+++ b/notfair/src/app/onboarding/page.tsx
@@ -2,6 +2,7 @@ import { Suspense } from "react";
import { OnboardingFlow } from "@/components/onboarding-flow";
import { getProject } from "@/server/db/projects";
import { prefetchAccountChoice } from "@/server/mcp/account-selection";
+import { listProjectMcpTokens } from "@/server/mcp/tokens";
export const dynamic = "force-dynamic";
@@ -22,11 +23,18 @@ export default async function OnboardingPage({
const pendingChoice =
project && mcp_key ? await prefetchAccountChoice(project, mcp_key) : null;
+ // The first-goal step's focus chips derive from what got connected.
+ // Fresh on every render — stepping Connect → Goal is a full RSC pass.
+ const connectedMcpKeys = project
+ ? listProjectMcpTokens(project.slug).map((t) => t.server_name)
+ : [];
+
return (
<Suspense fallback={null}>
<OnboardingFlow
pickerMcpKey={pendingChoice && mcp_key ? mcp_key : null}
pickerPrefetch={pendingChoice?.prefetch ?? null}
+ connectedMcpKeys={connectedMcpKeys}
/>
</Suspense>
);
diff --git a/notfair/src/components/codebase-path-card.tsx b/notfair/src/components/codebase-path-card.tsx
new file mode 100644
index 00000000..cc8ee7b6
--- /dev/null
+++ b/notfair/src/components/codebase-path-card.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { FolderOpen, Loader2 } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { setProjectCodebasePathAction } from "@/server/actions/projects";
+
+/**
+ * Settings card for the workspace's local codebase folder — the sanctioned
+ * root for agent code changes. Agents can only touch the site's code via
+ * the branch + PR protocol, and only inside this folder; without it, code
+ * changes are off the table and agents log recommendations instead.
+ */
+export function CodebasePathCard({
+ projectSlug,
+ currentPath,
+}: {
+ projectSlug: string;
+ currentPath: string | null;
+}) {
+ const [value, setValue] = useState(currentPath ?? "");
+ const [picking, setPicking] = useState(false);
+ const [pending, startTransition] = useTransition();
+
+ async function onBrowse() {
+ setPicking(true);
+ try {
+ const res = await fetch("/api/fs/pick-folder", { method: "POST" });
+ const body = (await res.json()) as
+ | { ok: true; path: string }
+ | { ok: false; kind: "cancelled" }
+ | { ok: false; kind: "unsupported" | "error"; message?: string };
+ if (body.ok) {
+ setValue(body.path);
+ return;
+ }
+ if (body.kind === "cancelled") return;
+ toast.error(body.message ?? "Couldn't open the folder picker.");
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : String(err));
+ } finally {
+ setPicking(false);
+ }
+ }
+
+ function onSave() {
+ startTransition(async () => {
+ const r = await setProjectCodebasePathAction({
+ project_slug: projectSlug,
+ codebase_path: value,
+ });
+ if (!r.ok) {
+ toast.error(r.error);
+ return;
+ }
+ toast.success(
+ r.codebase_path
+ ? "Codebase folder saved — agents can now propose code changes via pull requests."
+ : "Codebase folder cleared — agents can no longer change code.",
+ );
+ });
+ }
+
+ const dirty = (currentPath ?? "") !== value.trim();
+
+ return (
+ <div className="ns-card p-[18px]">
+ <p className="m-0 mb-1 text-[13px] font-medium">Codebase folder</p>
+ <p className="m-0 mb-3 text-[12px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">
+ The local git checkout of your website. Goal agents may change code
+ only here, only on a branch, and only through a pull request you
+ review and merge on GitHub. Leave empty to keep code off-limits.
+ </p>
+ <div className="flex gap-2">
+ <Input
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder="/path/to/your/site"
+ maxLength={500}
+ disabled={pending || picking}
+ aria-label="Local codebase folder"
+ />
+ <Button
+ type="button"
+ variant="outline"
+ onClick={onBrowse}
+ disabled={pending || picking}
+ aria-label="Browse for a folder"
+ >
+ {picking ? (
+ <Loader2 className="mr-1.5 size-4 animate-spin" />
+ ) : (
+ <FolderOpen className="mr-1.5 size-4" />
+ )}
+ Browse&hellip;
+ </Button>
+ <Button type="button" onClick={onSave} disabled={pending || !dirty}>
+ {pending ? <Loader2 className="mr-1.5 size-4 animate-spin" /> : null}
+ Save
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/notfair/src/components/harness-footer.test.tsx b/notfair/src/components/harness-footer.test.tsx
new file mode 100644
index 00000000..d40364ec
--- /dev/null
+++ b/notfair/src/components/harness-footer.test.tsx
@@ -0,0 +1,96 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { HarnessFooter } from "@/components/harness-footer";
+import { startCodexLoginAction } from "@/server/actions/harness";
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh: vi.fn() }),
+}));
+vi.mock("@/server/actions/harness", () => ({
+ startCodexLoginAction: vi.fn(),
+ refreshCodexUsageAction: vi.fn(),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("HarnessFooter Codex account state", () => {
+ it("shows Pro and a single weekly limit for the prolite tier", () => {
+ render(
+ <HarnessFooter
+ adapter="codex-local"
+ usage={{
+ kind: "codex",
+ auth: "chatgpt",
+ plan: "prolite",
+ email: "[email protected]",
+ rateLimits: [
+ {
+ label: "Weekly",
+ used_percent: 8,
+ limit_window_seconds: 604_800,
+ reset_at: Math.floor(Date.now() / 1000) + 86_400,
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(screen.getByText("ChatGPT Pro")).toBeInTheDocument();
+ expect(screen.getByRole("progressbar", { name: "Weekly usage" })).toBeInTheDocument();
+ expect(screen.queryByText(/Sign in to Codex/)).toBeNull();
+ });
+
+ it("does not call an authenticated user signed out when usage is unavailable", () => {
+ render(
+ <HarnessFooter
+ adapter="codex-local"
+ usage={{
+ kind: "codex",
+ auth: "chatgpt",
+ plan: "prolite",
+ email: "[email protected]",
+ rateLimits: [],
+ }}
+ />,
+ );
+
+ expect(screen.getByText(/Signed in as [email protected]/)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Sign in to Codex" })).toBeNull();
+ });
+
+ it("offers a working manual sign-in action only when the CLI is actually signed out", async () => {
+ vi.mocked(startCodexLoginAction).mockResolvedValue({
+ ok: true,
+ alreadySignedIn: false,
+ });
+ render(
+ <HarnessFooter
+ adapter="codex-local"
+ usage={{
+ kind: "codex",
+ auth: "signed-out",
+ plan: null,
+ email: null,
+ rateLimits: [],
+ }}
+ />,
+ );
+
+ expect(screen.getByText("Codex is signed out")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Sign in to Codex" }),
+ ).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Sign in to Codex" }));
+ await waitFor(() => {
+ expect(startCodexLoginAction).toHaveBeenCalledOnce();
+ expect(
+ screen.getByRole("button", { name: "Waiting for sign-in…" }),
+ ).toBeDisabled();
+ });
+ });
+});
diff --git a/notfair/src/components/harness-footer.tsx b/notfair/src/components/harness-footer.tsx
index cdd91a51..a81a3390 100644
--- a/notfair/src/components/harness-footer.tsx
+++ b/notfair/src/components/harness-footer.tsx
@@ -1,8 +1,17 @@
"use client";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
import { ChevronDown } from "lucide-react";
-import type { HarnessUsage, RateLimitWindow } from "@/server/harness-usage";
+import type {
+ CodexUsage,
+ HarnessUsage,
+ RateLimitWindow,
+} from "@/server/harness-usage";
+import {
+ refreshCodexUsageAction,
+ startCodexLoginAction,
+} from "@/server/actions/harness";
type Props = {
adapter: "claude-code-local" | "codex-local";
@@ -29,7 +38,12 @@ const COLLAPSE_KEY = "NotFair:harness-footer:collapsed";
* reloads. Default is expanded.
*/
export function HarnessFooter({ adapter, usage }: Props) {
+ const router = useRouter();
const harnessName = HARNESS_LABEL[adapter];
+ const [currentUsage, setCurrentUsage] = useState(usage);
+ const [signingIn, setSigningIn] = useState(false);
+ const [signInError, setSignInError] = useState<string | null>(null);
+ const pollingRef = useRef(false);
// Default to expanded; hydrate from localStorage after mount so SSR
// and first paint stay deterministic.
const [collapsed, setCollapsed] = useState(false);
@@ -55,42 +69,111 @@ export function HarnessFooter({ adapter, usage }: Props) {
}
}, [collapsed, hydrated]);
- if (usage.kind === "codex") {
- const planLabel = formatPlan(usage.plan);
+ useEffect(() => setCurrentUsage(usage), [usage]);
+
+ useEffect(() => {
+ if (!signingIn) return;
+ let attempts = 0;
+ const id = window.setInterval(async () => {
+ if (pollingRef.current) return;
+ pollingRef.current = true;
+ try {
+ const next = await refreshCodexUsageAction();
+ setCurrentUsage(next);
+ attempts += 1;
+ if (
+ next.kind === "codex" &&
+ next.auth !== "signed-out" &&
+ next.auth !== "unknown"
+ ) {
+ setSigningIn(false);
+ setSignInError(null);
+ router.refresh();
+ } else if (attempts >= 60) {
+ setSigningIn(false);
+ setSignInError("Sign-in was not completed. Try again when ready.");
+ }
+ } catch (err) {
+ attempts += 1;
+ if (attempts >= 60) {
+ setSigningIn(false);
+ setSignInError(
+ err instanceof Error
+ ? err.message
+ : "Couldn’t refresh Codex sign-in status.",
+ );
+ }
+ } finally {
+ pollingRef.current = false;
+ }
+ }, 2_000);
+ return () => window.clearInterval(id);
+ }, [router, signingIn]);
+
+ if (currentUsage.kind === "codex") {
+ const planLabel = formatPlan(currentUsage.plan);
+ const signedIn =
+ currentUsage.auth !== "signed-out" && currentUsage.auth !== "unknown";
return (
<FooterShell>
<FooterHeader
harness={harnessName}
- chip={planLabel ? `ChatGPT ${planLabel}` : null}
- chipTone="accent"
+ chip={codexChip(currentUsage, planLabel)}
+ chipTone={signedIn ? "accent" : "neutral"}
collapsed={collapsed}
onToggle={() => setCollapsed((v) => !v)}
/>
{!collapsed &&
- (usage.rateLimit ? (
+ (currentUsage.rateLimits.length > 0 ? (
<div className="mt-2 space-y-2">
- <UsageBar label="5-hour" window={usage.rateLimit.primary} />
- <UsageBar label="Weekly" window={usage.rateLimit.secondary} />
+ {currentUsage.rateLimits.map((window) => (
+ <UsageBar
+ key={`${window.label}:${window.limit_window_seconds}`}
+ label={window.label}
+ window={window}
+ />
+ ))}
+ </div>
+ ) : currentUsage.auth === "signed-out" ? (
+ <div className="mt-1.5 space-y-1.5">
+ <FooterDetail>Codex is signed out</FooterDetail>
+ <button
+ type="button"
+ disabled={signingIn}
+ onClick={async () => {
+ setSignInError(null);
+ const result = await startCodexLoginAction();
+ if (!result.ok) {
+ setSignInError(result.error);
+ return;
+ }
+ setSigningIn(true);
+ }}
+ className="ns-btn ns-btn-outline ns-btn-sm w-full justify-center disabled:opacity-60"
+ >
+ {signingIn ? "Waiting for sign-in…" : "Sign in to Codex"}
+ </button>
+ {signInError && <FooterError>{signInError}</FooterError>}
</div>
) : (
- <FooterDetail>Sign in to Codex to see usage limits</FooterDetail>
+ <FooterDetail>{codexSignedInDetail(currentUsage)}</FooterDetail>
))}
</FooterShell>
);
}
- if (usage.kind === "claude-code") {
- const detail = usage.stale
- ? lastSeenLabel(usage.lastComputedDate)
- : `${formatCount(usage.messagesToday)} msg · ${formatTokens(
- usage.tokensToday,
+ if (currentUsage.kind === "claude-code") {
+ const detail = currentUsage.stale
+ ? lastSeenLabel(currentUsage.lastComputedDate)
+ : `${formatCount(currentUsage.messagesToday)} msg · ${formatTokens(
+ currentUsage.tokensToday,
)} today`;
return (
<FooterShell>
<FooterHeader
harness={harnessName}
- chip={usage.stale ? "Idle" : "Active today"}
- chipTone={usage.stale ? "neutral" : "accent"}
+ chip={currentUsage.stale ? "Idle" : "Active today"}
+ chipTone={currentUsage.stale ? "neutral" : "accent"}
collapsed={collapsed}
onToggle={() => setCollapsed((v) => !v)}
/>
@@ -181,6 +264,31 @@ function FooterDetail({ children }: { children: React.ReactNode }) {
);
}
+function FooterError({ children }: { children: React.ReactNode }) {
+ return (
+ <p className="m-0 text-[10.5px] leading-snug text-destructive">{children}</p>
+ );
+}
+
+function codexChip(usage: CodexUsage, planLabel: string | null): string | null {
+ if (planLabel) return `ChatGPT ${planLabel}`;
+ if (usage.auth === "api-key") return "API key";
+ if (usage.auth === "agent-identity") return "Access token";
+ if (usage.auth === "chatgpt") return "ChatGPT";
+ return null;
+}
+
+function codexSignedInDetail(usage: CodexUsage): string {
+ if (usage.auth === "api-key") return "Signed in · usage billed by API";
+ if (usage.auth === "agent-identity") return "Signed in with access token";
+ if (usage.auth === "chatgpt") {
+ return usage.email
+ ? `Signed in as ${usage.email} · usage unavailable`
+ : "Signed in · usage limits unavailable";
+ }
+ return "Couldn’t check Codex sign-in";
+}
+
/**
* Usage bar — label + remaining percent + thin progress track + reset
* timestamp. Mirrors the ChatGPT settings page bars but compact enough
@@ -238,7 +346,9 @@ function formatPlan(slug: string | null): string | null {
// wham/usage returns lowercase plan slugs like "prolite", "pro",
// "free", "plus". Title-case and tidy a couple of multi-word ones.
const map: Record<string, string> = {
- prolite: "Plus",
+ // `prolite` is the provider's internal slug for the lower Pro tier.
+ // It is still sold and presented to users as ChatGPT Pro.
+ prolite: "Pro",
pro: "Pro",
free: "Free",
plus: "Plus",
diff --git a/notfair/src/components/live-transcript.tsx b/notfair/src/components/live-transcript.tsx
index 66e9be49..9091df3c 100644
--- a/notfair/src/components/live-transcript.tsx
+++ b/notfair/src/components/live-transcript.tsx
@@ -103,10 +103,17 @@ type Props = {
/** Byte offset *after* `initialEvents` — polls start from here. */
initialCursor: number;
/**
- * When true, disables the composer (e.g., task is running and the user
- * shouldn't send mid-run input). Default: composer always enabled.
+ * When true, disables the composer. This does not imply that a turn is
+ * still running; read-only transcript views also disable the composer.
*/
composerDisabled?: boolean;
+ /**
+ * Optional explanation shown inside a disabled composer. Read-only
+ * transcript views use this instead of claiming the agent is working.
+ */
+ disabledComposerPlaceholder?: string;
+ /** Keep a static terminal status visible in read-only transcript views. */
+ showCompletedStatus?: boolean;
/**
* Set when the agent's task is parked in `blocked` (e.g., waiting on a
* pending approval). Replaces the "thinking…" / "wrapping up…" indicator
@@ -134,12 +141,11 @@ type Props = {
*/
leadingContent?: React.ReactNode;
/**
- * Models the composer's selector offers for this project's harness
- * (from HARNESS_MODEL_OPTIONS, passed down by the server page). A
- * "Default" choice (no override) is always prepended. Omitted/empty =
- * no selector rendered.
+ * Models the composer's selector offers for this project's harness.
+ * The option marked `is_default` names the model used when no override
+ * flag is sent. Omitted/empty = no selector rendered.
*/
- modelOptions?: Array<{ value: string; label: string }>;
+ modelOptions?: Array<{ value: string; label: string; is_default?: boolean }>;
};
export function LiveTranscript({
@@ -150,6 +156,8 @@ export function LiveTranscript({
initialEvents,
initialCursor,
composerDisabled = false,
+ disabledComposerPlaceholder,
+ showCompletedStatus = false,
blockedReason,
mcpCatalog,
leadingContent,
@@ -177,6 +185,11 @@ export function LiveTranscript({
if (value) window.localStorage.setItem(modelStorageKey, value);
else window.localStorage.removeItem(modelStorageKey);
}
+ const defaultModelLabel =
+ modelOptions.find((option) => option.is_default)?.label ?? "Default";
+ const selectedModelLabel =
+ modelOptions.find((option) => option.value === model)?.label ??
+ defaultModelLabel;
const [cursor, setCursor] = useState(initialCursor);
const [input, setInput] = useState("");
const [sendingChat, setSendingChat] = useState(false);
@@ -336,10 +349,9 @@ export function LiveTranscript({
}
}, [agentSlug, cursor, projectSlug, threadId]);
- // Poll faster while the parent says the task is in flight — typical
- // first-task experience is "land on workspace, watch the audit run."
- // 2s feels laggy when nothing's on screen; 800ms keeps the pulse fresh.
- const pollIntervalMs = composerDisabled ? 800 : POLL_INTERVAL_MS;
+ // Poll faster only during an active send. A disabled composer can also
+ // mean "read-only history," which should not be treated as live work.
+ const pollIntervalMs = sendingChat ? 800 : POLL_INTERVAL_MS;
// Background polling: runs while mounted, paused during an active send so
// we don't double-render content we're already streaming via SSE.
@@ -467,21 +479,20 @@ export function LiveTranscript({
// Same store the selector next to Send uses.
const wanted = action.value.toLowerCase();
const names = [
- "default",
+ `${defaultModelLabel} (default)`,
...modelOptions.map((m) => m.label),
].join(", ");
if (!wanted) {
toast.message("Model", {
description: `Current: ${
- modelOptions.find((m) => m.value === model)?.label ??
- "Default"
+ selectedModelLabel
}. Options: ${names}.`,
});
return;
}
if (wanted === "default") {
onPickModel("");
- toast.success("Model reset to default.");
+ toast.success(`Model reset to ${defaultModelLabel}.`);
return;
}
const match = modelOptions.find(
@@ -614,18 +625,21 @@ export function LiveTranscript({
);
const rendered = useMemo(() => collapseEvents(events), [events]);
- // Show the working indicator any time the agent is plausibly running —
- // the user just sent (sendingChat) OR the parent says the task is in
- // flight (composerDisabled). Keep it at the bottom of the transcript
- // throughout the turn, BELOW pending tool calls and streaming text,
- // so the user sees the same anchor whether the agent is mid-call,
- // mid-stream, or waiting on the next model token.
+ const transcriptEnded = events.some(
+ (e) => e.kind === "lifecycle" && e.phase === "done",
+ );
+ // Keep the indicator at the bottom of the transcript throughout a live
+ // turn. Read-only logs can opt into a static completed status, but merely
+ // disabling the composer must never manufacture a forever-running state.
//
// (Earlier we hid the indicator once anything pending was rendered.
// That made the chat read as "stuck" the moment streaming started —
// there was no longer any active animation to telegraph "I'm still
// working.")
- const showThinking = sendingChat || composerDisabled || Boolean(blockedReason);
+ const showThinking =
+ sendingChat ||
+ Boolean(blockedReason) ||
+ (showCompletedStatus && transcriptEnded);
return (
<div className="flex h-full flex-col">
@@ -756,7 +770,8 @@ export function LiveTranscript({
disabled={composerDisabled}
placeholder={
composerDisabled
- ? "The agent is working — the transcript updates live"
+ ? disabledComposerPlaceholder ??
+ "The agent is working — the transcript updates live"
: blockedReason
? "Reply — the agent will see your message"
: "Message this goal's agent… (type / for commands)"
@@ -778,8 +793,7 @@ export function LiveTranscript({
className="inline-flex max-w-44 items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
>
<span className="truncate">
- {modelOptions.find((m) => m.value === model)?.label ??
- "Default"}
+ {selectedModelLabel}
</span>
<ChevronDown className="size-3 shrink-0" aria-hidden />
</button>
@@ -790,7 +804,7 @@ export function LiveTranscript({
onValueChange={onPickModel}
>
<DropdownMenuRadioItem value="">
- Default
+ {defaultModelLabel} (default)
</DropdownMenuRadioItem>
{modelOptions.map((m) => (
<DropdownMenuRadioItem key={m.value} value={m.value}>
@@ -825,16 +839,18 @@ export function LiveTranscript({
)}
</div>
</form>
- <p className="pt-1.5 text-center text-[10px] text-muted-foreground">
- {sendingChat ? (
- <span className="inline-flex items-center gap-1.5">
- <RunningDot size="sm" aria-label="" />
- Streaming — click stop to abort
- </span>
- ) : (
- <>Enter to send · Shift+Enter for newline</>
- )}
- </p>
+ {(sendingChat || !composerDisabled) && (
+ <p className="pt-1.5 text-center text-[10px] text-muted-foreground">
+ {sendingChat ? (
+ <span className="inline-flex items-center gap-1.5">
+ <RunningDot size="sm" aria-label="" />
+ Streaming — click stop to abort
+ </span>
+ ) : (
+ <>Enter to send · Shift+Enter for newline</>
+ )}
+ </p>
+ )}
</div>
</div>
</div>
@@ -1370,10 +1386,15 @@ function LiveWorkingIndicator({
hasPendingAssistant?: boolean;
}) {
const [now, setNow] = useState<number>(() => Date.now());
+ const visiblyEnded =
+ events.some((e) => e.kind === "lifecycle" && e.phase === "done") &&
+ !pendingTools?.some((t) => !t.done) &&
+ !hasPendingAssistant;
useEffect(() => {
+ if (visiblyEnded) return;
const id = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(id);
- }, []);
+ }, [visiblyEnded]);
const view = deriveWorkingView({
agentDisplayName,
@@ -1398,7 +1419,10 @@ function LiveWorkingIndicator({
if (turnStartedAt && lastTs) return Math.max(turnStartedAt, lastTs);
return turnStartedAt ?? lastTs;
})();
- const elapsedMs = anchorTs != null ? Math.max(0, now - anchorTs) : null;
+ const elapsedMs =
+ view.mood !== "ended" && anchorTs != null
+ ? Math.max(0, now - anchorTs)
+ : null;
return (
<WorkingIndicator
@@ -1465,10 +1489,9 @@ function deriveWorkingView(input: {
: events;
// Turn-ended signal: the harness emits a `final` event when its run
// completes; transcript-tail surfaces it as `{ kind: "lifecycle",
- // phase: "done" }`. Once we've seen it, the agent has stopped
- // producing tokens — keep the trajectory chips but stop the spinning
- // "Wrapping up" pill (which otherwise rolls on indefinitely while the
- // task waits for the agent's now-missing `submit_task_status` call).
+ // phase: "done" }`. Once we've seen it, the agent has stopped producing
+ // tokens. Keep the trajectory chips, but switch every live affordance
+ // to the static completed presentation.
const turnEnded = turnEvents.some(
(e) => e.kind === "lifecycle" && e.phase === "done",
);
@@ -1486,16 +1509,12 @@ function deriveWorkingView(input: {
})();
const phases = buildPhases(turnEvents, pendingTools);
- // Highest precedence: the run has ended cleanly. Don't lie to the user
- // by showing "Wrapping up" with a spinner for what is in fact a
- // completed turn that's now parked waiting for the agent to either
- // call submit_task_status (which it forgot) or for the user to
- // intervene.
+ // Highest precedence: the harness has emitted its normal final event.
+ // This is a completed turn, not a parked task and not an error.
if (turnEnded && !pendingInFlightTool && !hasPendingAssistant) {
return {
- headline: "Turn ended",
- subtitle:
- "Agent stopped without closing the task — open Approvals or send a follow-up.",
+ headline: "Turn complete",
+ subtitle: null,
phases,
mood: "ended",
};
diff --git a/notfair/src/components/new-goal-form.test.tsx b/notfair/src/components/new-goal-form.test.tsx
new file mode 100644
index 00000000..841238bb
--- /dev/null
+++ b/notfair/src/components/new-goal-form.test.tsx
@@ -0,0 +1,113 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { NewGoalForm } from "@/components/new-goal-form";
+import { createGoalAgentAction } from "@/server/actions/goals";
+
+const push = vi.fn();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push, refresh: vi.fn(), replace: vi.fn() }),
+}));
+vi.mock("@/server/actions/goals", () => ({
+ createGoalAgentAction: vi.fn(),
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("NewGoalForm focus chips", () => {
+ it("shows no focus row when nothing is connected", () => {
+ render(<NewGoalForm projectSlug="proj" connectedMcpKeys={[]} />);
+ expect(screen.queryByRole("group", { name: "Goal focus" })).toBeNull();
+ });
+
+ it("shows one chip per connected platform, plus Other", () => {
+ render(
+ <NewGoalForm
+ projectSlug="proj"
+ connectedMcpKeys={["notfair-googlesearchconsole", "notfair-xads"]}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "SEO" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "X Ads" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Other" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Google Ads" })).toBeNull();
+ });
+
+ it("selecting a focus swaps the placeholder and offers tap-to-fill examples", () => {
+ render(
+ <NewGoalForm
+ projectSlug="proj"
+ connectedMcpKeys={["notfair-googlesearchconsole"]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "SEO" }));
+ const textarea = screen.getByLabelText<HTMLTextAreaElement>(
+ "What do you want to achieve?",
+ );
+ expect(textarea.placeholder).toMatch(/organic clicks/i);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Grow organic clicks 30% in 90 days" }),
+ );
+ expect(textarea.value).toBe("Grow organic clicks 30% in 90 days");
+ });
+
+ it("passes the chosen focus to goal creation and lands in the agent chat", async () => {
+ vi.mocked(createGoalAgentAction).mockResolvedValue({
+ ok: true,
+ goal_id: "g1",
+ agent_slug: "goal-1",
+ });
+ render(
+ <NewGoalForm
+ projectSlug="proj"
+ connectedMcpKeys={["notfair-googlesearchconsole"]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "SEO" }));
+ fireEvent.change(screen.getByLabelText("What do you want to achieve?"), {
+ target: { value: "Grow organic clicks 30% in 90 days" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Create goal" }));
+
+ await waitFor(() => {
+ expect(createGoalAgentAction).toHaveBeenCalledWith({
+ project_slug: "proj",
+ statement: "Grow organic clicks 30% in 90 days",
+ focus:
+ "SEO / organic search — measure via the notfair-googlesearchconsole MCP",
+ });
+ expect(push).toHaveBeenCalledWith("/proj/goals/goal-1");
+ });
+ });
+
+ it("sends no focus when Other (or nothing) is chosen", async () => {
+ vi.mocked(createGoalAgentAction).mockResolvedValue({
+ ok: true,
+ goal_id: "g1",
+ agent_slug: "goal-1",
+ });
+ render(
+ <NewGoalForm
+ projectSlug="proj"
+ connectedMcpKeys={["notfair-googlesearchconsole"]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Other" }));
+ fireEvent.change(screen.getByLabelText("What do you want to achieve?"), {
+ target: { value: "Double our newsletter signups" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Create goal" }));
+
+ await waitFor(() => {
+ expect(createGoalAgentAction).toHaveBeenCalledWith({
+ project_slug: "proj",
+ statement: "Double our newsletter signups",
+ focus: null,
+ });
+ });
+ });
+});
diff --git a/notfair/src/components/new-goal-form.tsx b/notfair/src/components/new-goal-form.tsx
index 2f6965e6..626e3fce 100644
--- a/notfair/src/components/new-goal-form.tsx
+++ b/notfair/src/components/new-goal-form.tsx
@@ -4,25 +4,49 @@ import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { toast } from "sonner";
import { createGoalAgentAction } from "@/server/actions/goals";
+import {
+ goalPlatformsForConnected,
+ type GoalPlatform,
+} from "@/lib/goal-platforms";
import { projectHref } from "@/lib/project-href";
+import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
+const DEFAULT_PLACEHOLDER =
+ 'e.g. "Cut our Google Ads CAC to $30" or "Get to 100 signups a month from paid"';
+
/**
- * Statement-first goal creation: the user states the ambition (the only
- * thing on their mind), the platform auto-names an agent for it, and on
- * success we drop straight into the agent's chat — where it is already
- * working out how to measure the goal.
+ * Statement-first goal creation, shared by the goals index and
+ * onboarding's first-goal step. When the workspace has connected
+ * platforms, a focus row appears — one chip per connected platform
+ * (Google Ads, SEO, …) plus "Other" — with tap-to-fill example
+ * statements per focus. The chosen focus rides along to the agent's
+ * intake kickoff so it explores the right platform; the statement
+ * stays the user's words.
*/
-export function NewGoalForm({ projectSlug }: { projectSlug: string }) {
+export function NewGoalForm({
+ projectSlug,
+ connectedMcpKeys = [],
+}: {
+ projectSlug: string;
+ /** Drives which focus chips show. Omit/empty → no focus row. */
+ connectedMcpKeys?: string[];
+}) {
const router = useRouter();
const [pending, startTransition] = useTransition();
const [statement, setStatement] = useState("");
+ // null = nothing chosen yet; "other" = explicit free-form choice.
+ const [selected, setSelected] = useState<GoalPlatform | "other" | null>(null);
+ const platform = selected && selected !== "other" ? selected : null;
+
+ const platforms = goalPlatformsForConnected(connectedMcpKeys);
function submit() {
startTransition(async () => {
const r = await createGoalAgentAction({
project_slug: projectSlug,
statement,
+ focus: platform?.focus ?? null,
});
if (!r.ok || !r.agent_slug) {
toast.error(r.error ?? "Could not create the goal.");
@@ -38,10 +62,35 @@ export function NewGoalForm({ projectSlug }: { projectSlug: string }) {
<label htmlFor="new-goal-statement" className="text-[13px] font-medium">
What do you want to achieve?
</label>
+
+ {platforms.length > 0 && (
+ <div
+ className="flex flex-wrap items-center gap-1.5"
+ role="group"
+ aria-label="Goal focus"
+ >
+ {platforms.map((p) => (
+ <FocusChip
+ key={p.key}
+ label={p.label}
+ active={platform?.key === p.key}
+ disabled={pending}
+ onClick={() => setSelected(platform?.key === p.key ? null : p)}
+ />
+ ))}
+ <FocusChip
+ label="Other"
+ active={selected === "other"}
+ disabled={pending}
+ onClick={() => setSelected(selected === "other" ? null : "other")}
+ />
+ </div>
+ )}
+
<textarea
id="new-goal-statement"
className="min-h-20 w-full resize-y rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent))]"
- placeholder={'e.g. "Cut our Google Ads CAC to $30" or "Get to 100 signups a month from paid"'}
+ placeholder={platform?.placeholder ?? DEFAULT_PLACEHOLDER}
value={statement}
onChange={(e) => setStatement(e.target.value)}
onKeyDown={(e) => {
@@ -52,6 +101,23 @@ export function NewGoalForm({ projectSlug }: { projectSlug: string }) {
}}
disabled={pending}
/>
+
+ {platform && platform.examples.length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {platform.examples.map((example) => (
+ <button
+ key={example}
+ type="button"
+ disabled={pending}
+ onClick={() => setStatement(example)}
+ className="rounded-lg bg-[hsl(var(--notfair-surface-2)/0.6)] px-2.5 py-1 text-[12px] text-[hsl(var(--notfair-ink-3))] shadow-[var(--notfair-shadow-sm)] transition-colors hover:bg-[hsl(var(--notfair-surface-2))] hover:text-[hsl(var(--notfair-ink-1))]"
+ >
+ {example}
+ </button>
+ ))}
+ </div>
+ )}
+
<div className="flex items-center justify-between gap-3">
<p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
An agent takes it from here: it turns this into a measured metric,
@@ -64,3 +130,32 @@ export function NewGoalForm({ projectSlug }: { projectSlug: string }) {
</div>
);
}
+
+function FocusChip({
+ label,
+ active,
+ disabled,
+ onClick,
+}: {
+ label: string;
+ active: boolean;
+ disabled: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={onClick}
+ aria-pressed={active}
+ className={cn(
+ "rounded-full px-3 py-1 text-[12.5px] font-medium transition-colors",
+ active
+ ? "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))]",
+ )}
+ >
+ {label}
+ </button>
+ );
+}
diff --git a/notfair/src/components/onboarding-flow.tsx b/notfair/src/components/onboarding-flow.tsx
index deb331dc..612c1b37 100644
--- a/notfair/src/components/onboarding-flow.tsx
+++ b/notfair/src/components/onboarding-flow.tsx
@@ -19,9 +19,10 @@ import {
} from "@/server/onboarding/accounts";
import { AddMcpServerMenu } from "@/components/add-mcp-server-card";
import { McpCard } from "@/components/mcp-card";
+import { NewGoalForm } from "@/components/new-goal-form";
import type { AccountPickerPrefetch } from "@/components/mcp-account-picker-dialog";
-type Step = "name" | "connect";
+type Step = "name" | "connect" | "goal";
/**
* The post-OAuth account/property choice for a multi-account MCP, as
@@ -37,9 +38,12 @@ type PendingAccountChoice = {
export function OnboardingFlow({
pickerMcpKey = null,
pickerPrefetch = null,
+ connectedMcpKeys = [],
}: {
pickerMcpKey?: string | null;
pickerPrefetch?: AccountPickerPrefetch | null;
+ /** Feeds the first-goal step's focus chips (server-computed). */
+ connectedMcpKeys?: string[];
}) {
return (
<Suspense fallback={null}>
@@ -49,6 +53,7 @@ export function OnboardingFlow({
? { mcp_key: pickerMcpKey, prefetch: pickerPrefetch }
: null
}
+ connectedMcpKeys={connectedMcpKeys}
/>
</Suspense>
);
@@ -56,8 +61,10 @@ export function OnboardingFlow({
function OnboardingFlowInner({
autoPicker,
+ connectedMcpKeys,
}: {
autoPicker: PendingAccountChoice | null;
+ connectedMcpKeys: string[];
}) {
const router = useRouter();
const params = useSearchParams();
@@ -66,8 +73,8 @@ function OnboardingFlowInner({
const mcpConnected = params.get("mcp_connected") ?? undefined;
const mcpError = params.get("mcp_error") ?? undefined;
const mcpAnalyzing = params.get("mcp_analyzing") === "1";
- const step: Step = stepParam === "connect" ? "connect" : "name";
- const phase: "name" | "connect" = step;
+ const step: Step =
+ stepParam === "connect" ? "connect" : stepParam === "goal" ? "goal" : "name";
return (
<div className="ns-page">
@@ -88,12 +95,20 @@ function OnboardingFlowInner({
<span className="ns-topbar-label">NotFair</span>
<div className="ml-auto">
<div className="ns-progress">
- <Pip n={1} label="Workspace" state={phase === "name" ? "active" : "done"} />
+ <Pip n={1} label="Workspace" state={step === "name" ? "active" : "done"} />
<span className="ns-pip-line" />
<Pip
n={2}
label="Connect"
- state={phase === "name" ? "pending" : "active"}
+ state={
+ step === "name" ? "pending" : step === "connect" ? "active" : "done"
+ }
+ />
+ <span className="ns-pip-line" />
+ <Pip
+ n={3}
+ label="First goal"
+ state={step === "goal" ? "active" : "pending"}
/>
</div>
</div>
@@ -116,7 +131,10 @@ function OnboardingFlowInner({
{step === "connect" && slug && (
<ConnectStep slug={slug} autoPicker={autoPicker} />
)}
- {step === "connect" && !slug && <MissingSlug />}
+ {step === "goal" && slug && (
+ <FirstGoalStep slug={slug} connectedMcpKeys={connectedMcpKeys} />
+ )}
+ {step !== "name" && !slug && <MissingSlug />}
</main>
</div>
);
@@ -451,9 +469,15 @@ function ConnectStep({
function onDone() {
setAdvancing(true);
- // Straight to the workspace: the user mints their first goal agent
- // there and defines the goal in its chat. Nothing to provision here.
- router.replace(projectHref(slug, ""));
+ // With sources connected, the wizard's last step mints the first
+ // goal — focus options derive from what just got connected. With
+ // nothing connected there's nothing measurable to focus on, so the
+ // Skip path drops straight into the workspace.
+ if (view.phase === "loaded" && view.any_connected) {
+ router.push(`/onboarding?step=goal&slug=${encodeURIComponent(slug)}`);
+ } else {
+ router.replace(projectHref(slug, ""));
+ }
}
if (view.phase === "loading") {
@@ -581,6 +605,46 @@ function ConnectStep({
);
}
+// ── Step 3: First goal ─────────────────────────────────────────────
+//
+// The same statement-first creation form the goals index uses — one
+// component, one experience. Focus chips derive from the platforms the
+// user just connected (SEO for Search Console, Google Ads, …); creating
+// drops them straight into the new agent's chat, already working.
+
+function FirstGoalStep({
+ slug,
+ connectedMcpKeys,
+}: {
+ slug: string;
+ connectedMcpKeys: string[];
+}) {
+ return (
+ <>
+ <header>
+ <h1 className="ns-hero-title">Create your first goal.</h1>
+ <p className="ns-hero-sub">
+ Pick a focus, state the ambition. An agent measures it, shows you
+ the baseline, and waits for your START.
+ </p>
+ </header>
+
+ <div className="mt-5">
+ <NewGoalForm projectSlug={slug} connectedMcpKeys={connectedMcpKeys} />
+ </div>
+
+ <div className="ns-foot">
+ <p className="ns-footnote">
+ Not sure yet? Your workspace has this same form.
+ </p>
+ <Link href={projectHref(slug, "")} className="ns-btn ns-btn-ghost">
+ Skip for now
+ </Link>
+ </div>
+ </>
+ );
+}
+
function MissingSlug() {
return (
<div className="mt-10 space-y-4">
diff --git a/notfair/src/components/working-indicator.test.tsx b/notfair/src/components/working-indicator.test.tsx
new file mode 100644
index 00000000..6ce666f6
--- /dev/null
+++ b/notfair/src/components/working-indicator.test.tsx
@@ -0,0 +1,32 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+
+import { WorkingIndicator } from "@/components/working-indicator";
+
+describe("WorkingIndicator completed state", () => {
+ it("renders a completed turn without live motion or an increasing timer", () => {
+ const { container } = render(
+ <WorkingIndicator
+ agentDisplayName="Growth agent"
+ headline="Turn complete"
+ subtitle={null}
+ phases={[
+ {
+ id: "unfinished-tool",
+ label: "Inspecting data",
+ state: "active",
+ },
+ ]}
+ elapsedMs={65_000}
+ mood="ended"
+ />,
+ );
+
+ expect(
+ screen.getByRole("status", { name: "Growth agent Turn complete" }),
+ ).toBeInTheDocument();
+ expect(container.querySelector('[class*="animate-"]')).toBeNull();
+ expect(screen.queryByText("1:05")).toBeNull();
+ });
+});
diff --git a/notfair/src/components/working-indicator.tsx b/notfair/src/components/working-indicator.tsx
index 8f8c8fb8..10a17f3a 100644
--- a/notfair/src/components/working-indicator.tsx
+++ b/notfair/src/components/working-indicator.tsx
@@ -58,6 +58,7 @@ export function WorkingIndicator({
mood: WorkingMood;
}) {
const palette = MOOD_PALETTES[mood];
+ const ended = mood === "ended";
// Only show the last few phases — older ones scroll off-screen, the
// full transcript is the source of truth for history. Three keeps the
// strip dense without wrapping at common widths.
@@ -74,21 +75,23 @@ export function WorkingIndicator({
palette.ring,
)}
>
- {/* Aurora top edge — primary "alive" signal. */}
- <span
- aria-hidden
- className="pointer-events-none absolute inset-x-0 top-0 h-[2px] overflow-hidden"
- >
+ {!ended && (
+ /* Aurora top edge — primary "alive" signal. */
<span
- className={cn(
- "absolute inset-y-0 left-0 w-1/3",
- "motion-safe:animate-aurora-sweep",
- )}
- style={{
- backgroundImage: `linear-gradient(to right, transparent, ${palette.beam}, transparent)`,
- }}
- />
- </span>
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 top-0 h-[2px] overflow-hidden"
+ >
+ <span
+ className={cn(
+ "absolute inset-y-0 left-0 w-1/3",
+ "motion-safe:animate-aurora-sweep",
+ )}
+ style={{
+ backgroundImage: `linear-gradient(to right, transparent, ${palette.beam}, transparent)`,
+ }}
+ />
+ </span>
+ )}
<div className="flex items-start gap-3 px-3.5 py-2.5">
{/* Mood dot: scaling heartbeat with a soft halo. */}
@@ -106,7 +109,7 @@ export function WorkingIndicator({
className={cn(
"relative inline-block h-2 w-2 rounded-full",
palette.dotBg,
- "motion-safe:animate-heartbeat",
+ !ended && "motion-safe:animate-heartbeat",
)}
/>
</span>
@@ -120,7 +123,7 @@ export function WorkingIndicator({
<span className="text-muted-foreground/60">·</span>
<span className="text-foreground/85">
{headline}
- <BreathingDots />
+ {!ended && <BreathingDots />}
</span>
</div>
@@ -139,7 +142,11 @@ export function WorkingIndicator({
key={phase.id}
className="flex items-center gap-1"
>
- <PhaseChip phase={phase} palette={palette} />
+ <PhaseChip
+ phase={phase}
+ palette={palette}
+ animated={!ended}
+ />
{idx < visiblePhases.length - 1 && (
<ChevronRight
className="size-3 text-muted-foreground/35"
@@ -153,7 +160,7 @@ export function WorkingIndicator({
</div>
{/* Elapsed readout — small digital pill, right aligned. */}
- {elapsedMs != null && (
+ {!ended && elapsedMs != null && (
<span
className={cn(
"inline-flex shrink-0 items-center rounded border px-1.5 py-0.5",
@@ -167,21 +174,23 @@ export function WorkingIndicator({
)}
</div>
- {/* Shimmer bottom edge — continuous motion when waiting. */}
- <span
- aria-hidden
- className="pointer-events-none absolute inset-x-0 bottom-0 h-[1.5px] overflow-hidden"
- >
+ {!ended && (
+ /* Shimmer bottom edge — continuous motion when waiting. */
<span
- className={cn(
- "absolute inset-y-0 left-0 w-1/4 opacity-70",
- "motion-safe:animate-shimmer-bar",
- )}
- style={{
- backgroundImage: `linear-gradient(to right, transparent, ${palette.beam}, transparent)`,
- }}
- />
- </span>
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-[1.5px] overflow-hidden"
+ >
+ <span
+ className={cn(
+ "absolute inset-y-0 left-0 w-1/4 opacity-70",
+ "motion-safe:animate-shimmer-bar",
+ )}
+ style={{
+ backgroundImage: `linear-gradient(to right, transparent, ${palette.beam}, transparent)`,
+ }}
+ />
+ </span>
+ )}
</div>
);
}
@@ -189,9 +198,11 @@ export function WorkingIndicator({
function PhaseChip({
phase,
palette,
+ animated,
}: {
phase: WorkingPhase;
palette: MoodPalette;
+ animated: boolean;
}) {
if (phase.state === "done") {
return (
@@ -238,15 +249,17 @@ function PhaseChip({
<span className="max-w-[14rem] truncate font-mono text-[10px] font-medium">
{phase.label}
</span>
- {/* tiny in-chip pulse ring */}
- <span
- aria-hidden
- className={cn(
- "absolute inset-0 rounded-full ring-1 ring-inset",
- palette.chipRing,
- "motion-safe:animate-phase-glow",
- )}
- />
+ {animated && (
+ /* tiny in-chip pulse ring */
+ <span
+ aria-hidden
+ className={cn(
+ "absolute inset-0 rounded-full ring-1 ring-inset",
+ palette.chipRing,
+ "motion-safe:animate-phase-glow",
+ )}
+ />
+ )}
</span>
);
}
@@ -373,9 +386,8 @@ const MOOD_PALETTES: Record<WorkingMood, MoodPalette> = {
beam: "hsl(38 92% 55%)",
},
ended: {
- // Muted slate — visually static, no urgency. The aurora bar + dot
- // heartbeat still animate per shared component, but the cold palette
- // reads as "done, parked" rather than "actively working".
+ // Muted slate and fully static. A completed turn must not retain any
+ // of the motion language used to communicate active work.
ring: "ring-slate-500/15",
dotBg: "bg-slate-500",
haloBg: "bg-slate-400/30",
diff --git a/notfair/src/lib/goal-platforms.test.ts b/notfair/src/lib/goal-platforms.test.ts
new file mode 100644
index 00000000..87c211a4
--- /dev/null
+++ b/notfair/src/lib/goal-platforms.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ GOAL_PLATFORMS,
+ goalPlatformsForConnected,
+} from "@/lib/goal-platforms";
+
+describe("goalPlatformsForConnected", () => {
+ it("returns nothing when nothing is connected", () => {
+ expect(goalPlatformsForConnected([])).toEqual([]);
+ });
+
+ it("unlocks SEO when Search Console is connected", () => {
+ const platforms = goalPlatformsForConnected([
+ "notfair-googlesearchconsole",
+ ]);
+ expect(platforms.map((p) => p.key)).toEqual(["seo"]);
+ });
+
+ it("maps each connected MCP to its focus option, in registry order", () => {
+ const platforms = goalPlatformsForConnected([
+ "notfair-xads",
+ "notfair-googleads",
+ "notfair-googlesearchconsole",
+ ]);
+ expect(platforms.map((p) => p.key)).toEqual(["google-ads", "seo", "x-ads"]);
+ });
+
+ it("ignores MCPs without a goal-platform mapping", () => {
+ expect(goalPlatformsForConnected(["stripe", "supabase"])).toEqual([]);
+ });
+});
+
+describe("GOAL_PLATFORMS registry", () => {
+ it("every entry is fully usable by the form and the intake kickoff", () => {
+ for (const p of GOAL_PLATFORMS) {
+ expect(p.key, p.mcp_key).toBeTruthy();
+ expect(p.label).toBeTruthy();
+ expect(p.focus).toContain(p.mcp_key);
+ expect(p.placeholder).toBeTruthy();
+ expect(p.examples.length).toBeGreaterThan(0);
+ }
+ });
+
+ it("keys and mcp_keys are unique", () => {
+ const keys = GOAL_PLATFORMS.map((p) => p.key);
+ const mcpKeys = GOAL_PLATFORMS.map((p) => p.mcp_key);
+ expect(new Set(keys).size).toBe(keys.length);
+ expect(new Set(mcpKeys).size).toBe(mcpKeys.length);
+ });
+});
diff --git a/notfair/src/lib/goal-platforms.ts b/notfair/src/lib/goal-platforms.ts
new file mode 100644
index 00000000..0747f0e9
--- /dev/null
+++ b/notfair/src/lib/goal-platforms.ts
@@ -0,0 +1,99 @@
+/**
+ * Goal-platform registry: which "focus" options the goal-creation form
+ * offers, derived from the MCPs the workspace has connected. Connecting
+ * Search Console unlocks an SEO focus, Google Ads a paid-search focus,
+ * and so on — the form shows only what's actually measurable, plus a
+ * free-form "Other".
+ *
+ * Used by both goal-creation surfaces (the goals index and onboarding's
+ * first-goal step) so the experience is identical. Pure data — safe to
+ * import from client and server.
+ */
+
+export type GoalPlatform = {
+ /** Stable id for the chip (also what tests key on). */
+ key: string;
+ /** MCP catalog key that unlocks this focus. */
+ mcp_key: string;
+ /** Chip label the user picks: "SEO", "Google Ads", … */
+ label: string;
+ /**
+ * Focus line threaded into the intake kickoff so the agent explores
+ * the right platform even when the statement itself is ambiguous.
+ */
+ focus: string;
+ /** Textarea placeholder while this focus is selected. */
+ placeholder: string;
+ /** Tap-to-fill starter statements — static, digestible, per platform. */
+ examples: string[];
+};
+
+export const GOAL_PLATFORMS: GoalPlatform[] = [
+ {
+ key: "google-ads",
+ mcp_key: "notfair-googleads",
+ label: "Google Ads",
+ focus: "Google Ads (paid search) — measure via the notfair-googleads MCP",
+ placeholder: 'e.g. "Cut our Google Ads CAC to $30"',
+ examples: [
+ "Cut wasted Google Ads spend to $0/week",
+ "Get Google Ads CAC under $50",
+ "Grow conversions from Google Ads 25% without raising spend",
+ ],
+ },
+ {
+ key: "meta-ads",
+ mcp_key: "notfair-metaads",
+ label: "Meta Ads",
+ focus:
+ "Meta Ads (Facebook + Instagram paid social) — measure via the notfair-metaads MCP",
+ placeholder: 'e.g. "Get Meta Ads ROAS above 3x"',
+ examples: [
+ "Get Meta Ads ROAS above 3x",
+ "Cut Meta Ads cost per lead under $25",
+ ],
+ },
+ {
+ key: "seo",
+ mcp_key: "notfair-googlesearchconsole",
+ label: "SEO",
+ focus:
+ "SEO / organic search — measure via the notfair-googlesearchconsole MCP",
+ placeholder: 'e.g. "Grow organic clicks 30% in 90 days"',
+ examples: [
+ "Grow organic clicks 30% in 90 days",
+ "Lift CTR on our top 20 queries above 4%",
+ "Grow impressions for our money keywords 50%",
+ ],
+ },
+ {
+ key: "x-ads",
+ mcp_key: "notfair-xads",
+ label: "X Ads",
+ focus: "X (Twitter) Ads — measure via the notfair-xads MCP",
+ placeholder: 'e.g. "Keep X Ads CPM under $8"',
+ examples: [
+ "Keep X Ads CPM under $8 while holding impressions steady",
+ "Grow X Ads engagement rate to 2%",
+ ],
+ },
+ {
+ key: "analytics",
+ mcp_key: "notfair-googleanalytics",
+ label: "Analytics",
+ focus: "Site analytics (GA4) — measure via the notfair-googleanalytics MCP",
+ placeholder: 'e.g. "Grow weekly sessions 20%"',
+ examples: [
+ "Grow weekly sessions 20%",
+ "Lift signup conversion rate to 3%",
+ ],
+ },
+];
+
+/** The focus options a workspace has actually unlocked, in registry order. */
+export function goalPlatformsForConnected(
+ connectedMcpKeys: string[],
+): GoalPlatform[] {
+ const connected = new Set(connectedMcpKeys);
+ return GOAL_PLATFORMS.filter((p) => connected.has(p.mcp_key));
+}
diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.ts
index 06ce2ca8..fec2c47b 100644
--- a/notfair/src/server/actions/goals.ts
+++ b/notfair/src/server/actions/goals.ts
@@ -49,6 +49,13 @@ async function nextGoalNumber(project_slug: string): Promise<number> {
export async function createGoalAgentAction(input: {
project_slug: string;
statement: string;
+ /**
+ * Platform focus picked in the creation form (a `GoalPlatform.focus`
+ * line, e.g. "SEO / organic search — measure via the
+ * notfair-googlesearchconsole MCP"). Threaded into the intake kickoff
+ * only — the statement stays the user's words.
+ */
+ focus?: string | null;
}): Promise<GoalActionResult> {
const project = getProject(input.project_slug);
if (!project) return { ok: false, error: "Project not found." };
@@ -80,7 +87,7 @@ export async function createGoalAgentAction(input: {
// The agent starts working immediately; the goal screen's embedded
// chat streams it live.
- void runGoalIntake(goal).catch((err) =>
+ void runGoalIntake(goal, { focus: input.focus }).catch((err) =>
console.error("[goal-intake] kickoff failed:", err),
);
diff --git a/notfair/src/server/actions/harness.ts b/notfair/src/server/actions/harness.ts
new file mode 100644
index 00000000..27f7b48d
--- /dev/null
+++ b/notfair/src/server/actions/harness.ts
@@ -0,0 +1,54 @@
+"use server";
+
+import os from "node:os";
+import { spawn } from "node:child_process";
+import {
+ refreshHarnessUsage,
+ type HarnessUsage,
+} from "@/server/harness-usage";
+
+const CODEX_BIN = process.env.NOTFAIR_CODEX_BIN?.trim() || "codex";
+
+export type StartCodexLoginResult =
+ | { ok: true; alreadySignedIn: boolean }
+ | { ok: false; error: string };
+
+/**
+ * Start Codex's official browser login without tying the child process to
+ * the lifetime of this server-action request. The client polls auth status
+ * and updates itself as soon as the browser callback completes.
+ */
+export async function startCodexLoginAction(): Promise<StartCodexLoginResult> {
+ const current = await refreshHarnessUsage("codex-local");
+ if (
+ current.kind === "codex" &&
+ current.auth !== "signed-out" &&
+ current.auth !== "unknown"
+ ) {
+ return { ok: true, alreadySignedIn: true };
+ }
+
+ try {
+ const child = spawn(CODEX_BIN, ["login"], {
+ cwd: os.homedir(),
+ detached: true,
+ stdio: "ignore",
+ env: process.env,
+ });
+ await new Promise<void>((resolve, reject) => {
+ child.once("spawn", resolve);
+ child.once("error", reject);
+ });
+ child.unref();
+ return { ok: true, alreadySignedIn: false };
+ } catch (err) {
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ };
+ }
+}
+
+export async function refreshCodexUsageAction(): Promise<HarnessUsage> {
+ return refreshHarnessUsage("codex-local");
+}
diff --git a/notfair/src/server/actions/projects.ts b/notfair/src/server/actions/projects.ts
index 4715f354..4b292aeb 100644
--- a/notfair/src/server/actions/projects.ts
+++ b/notfair/src/server/actions/projects.ts
@@ -349,3 +349,47 @@ export async function deleteProjectAction(
},
};
}
+
+/**
+ * Set (or clear) the workspace's local codebase folder — the sanctioned
+ * root for agent code changes (branch + PR protocol). Validates the path
+ * is an existing directory, persists it, and re-renders every goal
+ * agent's identity so the "Codebase" workspace fact updates immediately.
+ */
+export async function setProjectCodebasePathAction(input: {
+ project_slug: string;
+ codebase_path: string;
+}): Promise<{ ok: true; codebase_path: string | null } | { ok: false; error: string }> {
+ const slug = input.project_slug.trim();
+ if (!slug) return { ok: false, error: "Missing project slug." };
+ const raw = input.codebase_path.trim();
+
+ let normalized: string | null = null;
+ if (raw) {
+ const { stat } = await import("node:fs/promises");
+ try {
+ const s = await stat(raw);
+ if (!s.isDirectory()) {
+ return { ok: false, error: `Not a folder: ${raw}` };
+ }
+ } catch {
+ return { ok: false, error: `Folder not found: ${raw}` };
+ }
+ normalized = raw;
+ }
+
+ const { setProjectCodebasePath } = await import("@/server/db/projects");
+ const updated = setProjectCodebasePath(slug, normalized);
+ if (!updated) return { ok: false, error: "Project not found." };
+
+ // Agents carry the codebase path in their identity's workspace facts.
+ try {
+ const { syncProjectAgents } = await import("@/server/goals/provision");
+ await syncProjectAgents(slug);
+ } catch (err) {
+ console.warn("[settings] identity re-render after codebase change failed:", err);
+ }
+
+ revalidatePath("/", "layout");
+ return { ok: true, codebase_path: updated.codebase_path };
+}
diff --git a/notfair/src/server/adapters/codex-local/models.test.ts b/notfair/src/server/adapters/codex-local/models.test.ts
new file mode 100644
index 00000000..977d87aa
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/models.test.ts
@@ -0,0 +1,50 @@
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { listCodexModels } from "./models";
+
+async function fixture(config: string, models: unknown[]) {
+ const dir = await mkdtemp(join(tmpdir(), "notfair-codex-models-"));
+ const configFile = join(dir, "config.toml");
+ const cacheFile = join(dir, "models_cache.json");
+ await Promise.all([
+ writeFile(configFile, config, "utf8"),
+ writeFile(cacheFile, JSON.stringify({ models }), "utf8"),
+ ]);
+ return { configFile, cacheFile };
+}
+
+describe("listCodexModels", () => {
+ it("marks the root configured model as the concrete no-override model", async () => {
+ const files = await fixture(
+ 'model = "gpt-5.6-sol"\n\n[profiles.fast]\nmodel = "gpt-5.4"\n',
+ [
+ { slug: "gpt-5.4", display_name: "GPT-5.4", priority: 1 },
+ { slug: "gpt-5.6-sol", display_name: "GPT-5.6-Sol", priority: 2 },
+ ],
+ );
+
+ const models = await listCodexModels(files.cacheFile, files.configFile);
+
+ expect(models.find((model) => model.is_default)).toMatchObject({
+ value: "gpt-5.6-sol",
+ label: "GPT-5.6-Sol",
+ });
+ });
+
+ it("keeps a configured model visible when the provider cache is stale", async () => {
+ const files = await fixture('model = "gpt-custom"\n', [
+ { slug: "gpt-5.4", display_name: "GPT-5.4", priority: 1 },
+ ]);
+
+ const models = await listCodexModels(files.cacheFile, files.configFile);
+
+ expect(models[0]).toEqual({
+ value: "gpt-custom",
+ label: "gpt-custom",
+ is_default: true,
+ });
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/models.ts b/notfair/src/server/adapters/codex-local/models.ts
index 4d3dbbfd..995fc44e 100644
--- a/notfair/src/server/adapters/codex-local/models.ts
+++ b/notfair/src/server/adapters/codex-local/models.ts
@@ -35,9 +35,62 @@ const FALLBACK: HarnessModelOption[] = [
{ value: "gpt-5.4", label: "GPT-5.4" },
];
+async function readConfiguredModel(configFile: string): Promise<string | null> {
+ try {
+ const raw = await readFile(configFile, "utf8");
+ // NotFair invokes Codex without a profile, so only the root-level `model`
+ // applies. Stop at the first TOML table to avoid mistaking a nested key
+ // for the CLI's effective default.
+ for (const line of raw.split(/\r?\n/)) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith("[")) break;
+ const match = /^model\s*=\s*("(?:\\.|[^"\\])*"|'[^']*'|[^\s#]+)\s*(?:#.*)?$/.exec(
+ trimmed,
+ );
+ if (!match) continue;
+ const value = match[1];
+ if (value.startsWith('"')) {
+ try {
+ return JSON.parse(value) as string;
+ } catch {
+ return null;
+ }
+ }
+ return value.startsWith("'") ? value.slice(1, -1) : value;
+ }
+ } catch {
+ // Missing or unreadable config means Codex uses its provider default.
+ }
+ return null;
+}
+
+function markDefaultModel(
+ models: HarnessModelOption[],
+ configuredModel: string | null,
+): HarnessModelOption[] {
+ const defaultValue = configuredModel ?? models[0]?.value;
+ if (!defaultValue) return models;
+
+ let found = false;
+ const marked = models.map((model) => {
+ const isDefault = model.value === defaultValue;
+ if (isDefault) found = true;
+ return isDefault ? { ...model, is_default: true } : model;
+ });
+
+ // A configured model can be absent from a stale provider cache. Keep it
+ // visible as the effective default rather than falling back to a wrong
+ // label until Codex refreshes models_cache.json.
+ return found
+ ? marked
+ : [{ value: defaultValue, label: defaultValue, is_default: true }, ...marked];
+}
+
export async function listCodexModels(
cacheFile: string = join(codexConfigDir(), "models_cache.json"),
+ configFile: string = join(codexConfigDir(), "config.toml"),
): Promise<HarnessModelOption[]> {
+ const configuredModel = await readConfiguredModel(configFile);
try {
const raw = await readFile(cacheFile, "utf8");
const parsed = JSON.parse(raw) as { models?: CachedModel[] };
@@ -60,8 +113,8 @@ export async function listCodexModels(
? { context_window: m.context_window }
: {}),
}));
- return models.length > 0 ? models : FALLBACK;
+ return markDefaultModel(models.length > 0 ? models : FALLBACK, configuredModel);
} catch {
- return FALLBACK;
+ return markDefaultModel(FALLBACK, configuredModel);
}
}
diff --git a/notfair/src/server/adapters/types.ts b/notfair/src/server/adapters/types.ts
index 1c345205..875b6d28 100644
--- a/notfair/src/server/adapters/types.ts
+++ b/notfair/src/server/adapters/types.ts
@@ -132,6 +132,12 @@ export interface HarnessModelOption {
value: string;
/** Human label for the dropdown. */
label: string;
+ /**
+ * True when omitting the model flag resolves to this model. The composer
+ * keeps the empty value as a genuine no-override selection, but uses this
+ * metadata to show the concrete model name instead of a vague "Default".
+ */
+ is_default?: boolean;
/**
* Input context window in tokens, when the provider exposes it (codex
* publishes it in models_cache.json). Absent when unknown.
diff --git a/notfair/src/server/db/goal-prs.test.ts b/notfair/src/server/db/goal-prs.test.ts
new file mode 100644
index 00000000..45227ca8
--- /dev/null
+++ b/notfair/src/server/db/goal-prs.test.ts
@@ -0,0 +1,125 @@
+import { beforeAll, beforeEach, 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-prs-"));
+});
+
+import {
+ applyGoalPrSync,
+ createGoalPr,
+ findGoalPrByUrl,
+ listGoalPrs,
+ listOpenGoalPrs,
+ listPrsAwaitingReview,
+ markGoalPrSyncError,
+} from "@/server/db/goal-prs";
+import { getDb } from "@/server/db/db";
+import { createGoal } from "@/server/db/goals";
+
+const SLUG = "proj";
+let goalId: string;
+
+beforeAll(() => {
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",
+ )
+ .run(SLUG, new Date().toISOString());
+ goalId = createGoal({
+ project_slug: SLUG,
+ agent_id: "agent-1",
+ statement: "Grow organic clicks",
+ }).id;
+});
+
+beforeEach(() => {
+ getDb().prepare("DELETE FROM goal_prs").run();
+ vi.restoreAllMocks();
+});
+
+const URL1 = "https://github.com/acme/site/pull/12";
+
+describe("goal_prs data layer", () => {
+ it("creates a PR row in open state and finds it by url", () => {
+ const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "Fix titles" });
+ expect(pr.state).toBe("open");
+ expect(pr.review_decision).toBeNull();
+ expect(findGoalPrByUrl(goalId, URL1)?.id).toBe(pr.id);
+ expect(listGoalPrs(goalId)).toHaveLength(1);
+ });
+
+ it("returns the winning row when the same goal and url are inserted twice", () => {
+ const first = createGoalPr({
+ goal_id: goalId,
+ url: URL1,
+ title: "Fix titles",
+ });
+ const duplicate = createGoalPr({
+ goal_id: goalId,
+ url: URL1,
+ title: "Duplicate registration",
+ });
+
+ expect(duplicate.id).toBe(first.id);
+ expect(duplicate.title).toBe("Fix titles");
+ expect(listGoalPrs(goalId)).toHaveLength(1);
+ });
+
+ it("applies a GitHub sync and clears prior sync errors", () => {
+ const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });
+ markGoalPrSyncError(pr.id, "gh not found");
+ const synced = applyGoalPrSync(pr.id, {
+ state: "merged",
+ title: "Fix titles",
+ review_decision: "APPROVED",
+ comment_count: 3,
+ is_draft: false,
+ merged_at: "2026-07-13T00:00:00Z",
+ })!;
+ expect(synced.state).toBe("merged");
+ expect(synced.title).toBe("Fix titles");
+ expect(synced.comment_count).toBe(3);
+ expect(synced.sync_error).toBeNull();
+ expect(listOpenGoalPrs(goalId)).toHaveLength(0);
+ });
+
+ it("awaiting-review covers open non-draft PRs unless changes were requested", () => {
+ const a = createGoalPr({ goal_id: goalId, url: URL1, title: "a" });
+ const b = createGoalPr({
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/13",
+ title: "b",
+ });
+ const c = createGoalPr({
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/14",
+ title: "c",
+ });
+ // a: untouched (never synced) → awaiting review.
+ // b: user requested changes → ball is with the agent, not the user.
+ applyGoalPrSync(b.id, {
+ state: "open",
+ review_decision: "CHANGES_REQUESTED",
+ comment_count: 2,
+ is_draft: false,
+ merged_at: null,
+ });
+ // c: merged → terminal, not awaiting anything.
+ applyGoalPrSync(c.id, {
+ state: "merged",
+ review_decision: "APPROVED",
+ comment_count: 0,
+ is_draft: false,
+ merged_at: "2026-07-13T00:00:00Z",
+ });
+ const awaiting = listPrsAwaitingReview(SLUG);
+ expect(awaiting.map((p) => p.id)).toEqual([a.id]);
+ });
+});
diff --git a/notfair/src/server/db/goal-prs.ts b/notfair/src/server/db/goal-prs.ts
new file mode 100644
index 00000000..735e427e
--- /dev/null
+++ b/notfair/src/server/db/goal-prs.ts
@@ -0,0 +1,163 @@
+import { randomUUID } from "node:crypto";
+import { getDb } from "./db";
+
+/**
+ * Pull requests a goal agent opened against the workspace's codebase.
+ *
+ * A PR row is the loop's handle on a code mutation: the agent registers
+ * the PR right after `gh pr create` (via the `register_pull_request`
+ * tool), the platform syncs its state from GitHub (`gh pr view`) at tick
+ * time and on goal-page views, and the tick brief carries the live state —
+ * so the agent reacts to review comments, and merge/close are facts the
+ * loop observes rather than claims.
+ */
+
+export type GoalPrState = "open" | "merged" | "closed";
+
+export type GoalPr = {
+ id: string;
+ goal_id: string;
+ action_id: string | null;
+ url: string;
+ title: string;
+ branch: string | null;
+ state: GoalPrState;
+ /** GitHub reviewDecision (APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED
+ * / "" for repos without required reviews). Null until first sync. */
+ review_decision: string | null;
+ comment_count: number;
+ is_draft: boolean;
+ merged_at: string | null;
+ last_synced_at: string | null;
+ sync_error: string | null;
+ created_at: string;
+ updated_at: string;
+};
+
+type GoalPrRow = Omit<GoalPr, "is_draft"> & { is_draft: number };
+
+function mapRow(row: GoalPrRow): GoalPr {
+ return { ...row, is_draft: !!row.is_draft };
+}
+
+export function createGoalPr(input: {
+ goal_id: string;
+ url: string;
+ title: string;
+ branch?: string | null;
+ action_id?: string | null;
+}): GoalPr {
+ const db = getDb();
+ const now = new Date().toISOString();
+ const id = randomUUID();
+ db.prepare(
+ `INSERT OR IGNORE INTO goal_prs (id, goal_id, action_id, url, title, branch, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ id,
+ input.goal_id,
+ input.action_id ?? null,
+ input.url,
+ input.title,
+ input.branch ?? null,
+ now,
+ now,
+ );
+ // UNIQUE(goal_id, url) makes registration idempotent even when two tool
+ // calls race between their read and insert. The winner's row is canonical.
+ return findGoalPrByUrl(input.goal_id, input.url)!;
+}
+
+export function getGoalPr(id: string): GoalPr | null {
+ const row = getDb()
+ .prepare("SELECT * FROM goal_prs WHERE id = ?")
+ .get(id) as GoalPrRow | undefined;
+ return row ? mapRow(row) : null;
+}
+
+export function findGoalPrByUrl(goal_id: string, url: string): GoalPr | null {
+ const row = getDb()
+ .prepare("SELECT * FROM goal_prs WHERE goal_id = ? AND url = ?")
+ .get(goal_id, url) as GoalPrRow | undefined;
+ return row ? mapRow(row) : null;
+}
+
+export function listGoalPrs(goal_id: string, limit = 50): GoalPr[] {
+ const rows = getDb()
+ .prepare(
+ "SELECT * FROM goal_prs WHERE goal_id = ? ORDER BY created_at DESC LIMIT ?",
+ )
+ .all(goal_id, limit) as GoalPrRow[];
+ return rows.map(mapRow);
+}
+
+/** PRs still awaiting a GitHub outcome — the ones worth syncing. */
+export function listOpenGoalPrs(goal_id: string): GoalPr[] {
+ const rows = getDb()
+ .prepare(
+ "SELECT * FROM goal_prs WHERE goal_id = ? AND state = 'open' ORDER BY created_at DESC",
+ )
+ .all(goal_id) as GoalPrRow[];
+ return rows.map(mapRow);
+}
+
+/**
+ * Open PRs across a project's goals that are waiting on the user — feeds
+ * the goals-index "PR awaiting your review" tag. A PR waits on the user
+ * unless GitHub says changes were requested (then the ball is back with
+ * the agent).
+ */
+export function listPrsAwaitingReview(project_slug: string): GoalPr[] {
+ const rows = getDb()
+ .prepare(
+ `SELECT p.* FROM goal_prs p
+ JOIN goals g ON g.id = p.goal_id
+ WHERE g.project_slug = ? AND p.state = 'open' AND p.is_draft = 0
+ AND (p.review_decision IS NULL OR p.review_decision != 'CHANGES_REQUESTED')
+ ORDER BY p.created_at DESC`,
+ )
+ .all(project_slug) as GoalPrRow[];
+ return rows.map(mapRow);
+}
+
+export function applyGoalPrSync(
+ id: string,
+ sync: {
+ state: GoalPrState;
+ title?: string | null;
+ review_decision: string | null;
+ comment_count: number;
+ is_draft: boolean;
+ merged_at: string | null;
+ },
+): GoalPr | null {
+ const db = getDb();
+ const now = new Date().toISOString();
+ db.prepare(
+ `UPDATE goal_prs
+ SET state = ?, title = COALESCE(?, title), review_decision = ?,
+ comment_count = ?, is_draft = ?, merged_at = ?,
+ last_synced_at = ?, sync_error = NULL, updated_at = ?
+ WHERE id = ?`,
+ ).run(
+ sync.state,
+ sync.title ?? null,
+ sync.review_decision,
+ sync.comment_count,
+ sync.is_draft ? 1 : 0,
+ sync.merged_at,
+ now,
+ now,
+ id,
+ );
+ return getGoalPr(id);
+}
+
+export function markGoalPrSyncError(id: string, error: string): void {
+ const now = new Date().toISOString();
+ getDb()
+ .prepare(
+ "UPDATE goal_prs SET sync_error = ?, last_synced_at = ?, updated_at = ? WHERE id = ?",
+ )
+ .run(error.slice(0, 500), now, now, id);
+}
diff --git a/notfair/src/server/db/projects.ts b/notfair/src/server/db/projects.ts
index 633ceab8..d3779133 100644
--- a/notfair/src/server/db/projects.ts
+++ b/notfair/src/server/db/projects.ts
@@ -127,6 +127,21 @@ export function setProjectMetaAdsAccount(
return getProject(slug);
}
+/** Same shape as setProjectGoogleAdsAccount but for the local codebase path. */
+export function setProjectCodebasePath(
+ slug: string,
+ codebase_path: string | null,
+): Project | null {
+ const db = getDb();
+ const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);
+ if (!existing) return null;
+ db.prepare("UPDATE projects SET codebase_path = ? WHERE slug = ?").run(
+ codebase_path,
+ slug,
+ );
+ return getProject(slug);
+}
+
/** Same shape as setProjectGoogleAdsAccount but for the GSC property id. */
export function setProjectGscProperty(
slug: string,
diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.ts
index 1ceb73cb..1a6f7966 100644
--- a/notfair/src/server/db/schema.ts
+++ b/notfair/src/server/db/schema.ts
@@ -183,6 +183,34 @@ CREATE TABLE IF NOT EXISTS goal_suggestions (
CREATE INDEX IF NOT EXISTS idx_goal_suggestions_project
ON goal_suggestions(project_slug, status);
+-- Pull requests a goal agent opened to change the workspace's codebase.
+-- The PR is the approval gate for code mutations: the agent never merges
+-- its own PR; the user reviews on GitHub. State is synced from the gh
+-- CLI at tick time and on goal-page views, so the loop reacts to reviews,
+-- comment counts, merges, and closes.
+CREATE TABLE IF NOT EXISTS goal_prs (
+ id TEXT PRIMARY KEY,
+ goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
+ action_id TEXT REFERENCES goal_actions(id) ON DELETE SET NULL,
+ url TEXT NOT NULL,
+ title TEXT NOT NULL,
+ branch TEXT,
+ state TEXT NOT NULL DEFAULT 'open'
+ CHECK (state IN ('open','merged','closed')),
+ -- GitHub reviewDecision: APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED
+ -- (empty for repos without required reviews). NULL until first sync.
+ review_decision TEXT,
+ comment_count INTEGER NOT NULL DEFAULT 0,
+ is_draft INTEGER NOT NULL DEFAULT 0,
+ merged_at TEXT,
+ last_synced_at TEXT,
+ sync_error TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(goal_id, url)
+);
+CREATE INDEX IF NOT EXISTS idx_goal_prs_goal ON goal_prs(goal_id, state);
+
CREATE TABLE IF NOT EXISTS goal_ticks (
id TEXT PRIMARY KEY,
goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
diff --git a/notfair/src/server/goals/handlers.ts b/notfair/src/server/goals/handlers.ts
index d3c43b04..65d1ea05 100644
--- a/notfair/src/server/goals/handlers.ts
+++ b/notfair/src/server/goals/handlers.ts
@@ -623,3 +623,73 @@ function syncIdentity(goal: Goal): Promise<void> {
.then(({ syncGoalIdentity }) => syncGoalIdentity(goal))
.catch((err) => console.warn("[goal-handlers] identity sync failed:", err));
}
+
+// ── register_pull_request ───────────────────────────────────────────────
+
+export type RegisterPullRequestInput = {
+ goal_id: string;
+ url: string;
+ title: string;
+ branch?: string;
+ action_id?: string;
+};
+
+const GITHUB_PR_URL = /^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+$/;
+
+/**
+ * Record a pull request the agent just opened against the workspace's
+ * codebase. The PR is the approval gate for code mutations: the platform
+ * syncs its state from GitHub on every tick and surfaces it to the user
+ * for review — the agent never merges its own PR.
+ */
+export async function handleRegisterPullRequest(
+ input: RegisterPullRequestInput,
+ ctx: HandlerContext,
+): Promise<HandlerResult<{ pr_id: string; state: string }>> {
+ const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });
+ if (!r.ok) return r;
+ const goal = r.data;
+
+ const url = input.url.trim().replace(/\/$/, "");
+ if (!GITHUB_PR_URL.test(url)) {
+ return {
+ ok: false,
+ error:
+ "url must be a GitHub pull-request URL like https://github.com/owner/repo/pull/123.",
+ };
+ }
+ if (input.action_id) {
+ const action = getGoalAction(input.action_id);
+ if (!action || action.goal_id !== goal.id) {
+ return {
+ ok: false,
+ error: `action_id '${input.action_id}' is not an action of this goal.`,
+ };
+ }
+ }
+
+ const { createGoalPr, findGoalPrByUrl } = await import("@/server/db/goal-prs");
+ const existing = findGoalPrByUrl(goal.id, url);
+ const pr =
+ existing ??
+ createGoalPr({
+ goal_id: goal.id,
+ url,
+ title: input.title.trim(),
+ branch: input.branch?.trim() || null,
+ action_id: input.action_id ?? null,
+ });
+
+ // Pull the live state right away so the UI's review callout and the
+ // next tick brief start accurate. Best-effort — a gh hiccup lands on
+ // the row's sync_error, not on this call.
+ const { syncGoalPrs } = await import("./pr-sync");
+ await syncGoalPrs(goal.id);
+ const { getGoalPr } = await import("@/server/db/goal-prs");
+ const fresh = getGoalPr(pr.id) ?? pr;
+
+ return {
+ ok: true,
+ data: { pr_id: fresh.id, state: fresh.state },
+ };
+}
diff --git a/notfair/src/server/goals/identity.ts b/notfair/src/server/goals/identity.ts
index 82466a8b..ff3280be 100644
--- a/notfair/src/server/goals/identity.ts
+++ b/notfair/src/server/goals/identity.ts
@@ -72,6 +72,10 @@ State lives in tool calls, never in prose. Every tool requires
spend_usd when the move commits incremental spend.
- \`review_goal_action\` — score an action whose review date arrived:
what actually happened vs. expected_effect.
+- \`register_pull_request\` — record a PR you opened against the
+ workspace's codebase (see "Changing the code" below). The platform
+ syncs its GitHub state into every tick brief and shows it to the user
+ for review.
- \`log_learning\` / \`search_learnings\` — your durable memory.
- \`update_goal_status\` — declare achieved / failed, or pause. Requires
a reason grounded in the measured metric.
@@ -160,6 +164,43 @@ Pick the window by what the platform needs to show a real effect:
When in doubt, longer. Reading noise as signal is the main way this
loop fails.
+### Changing the code (website / codebase mutations)
+
+Some goals — SEO especially — are achieved by changing the user's
+website, and that means changing their code. The pull request is the
+ONLY sanctioned channel; the user's GitHub review replaces any other
+approval step. Non-negotiable rules:
+
+1. **Only inside the workspace codebase.** Work exclusively in the
+ "Codebase" path from your workspace facts. If none is set, you CANNOT
+ change code — say so in your diary and point the user at
+ Settings → Codebase; log your recommendation as a \`decision\`
+ action instead.
+2. **Branch → commit → push → PR — in a git worktree, never in the
+ user's checkout.** The codebase path is the USER'S working copy: do
+ not switch its branch, stash, or touch its uncommitted files. Work in
+ an isolated worktree instead:
+ \`git -C <codebase> worktree add <your-workspace>/pr-<slug> -b notfair/<goal>-<slug>\`,
+ edit there, commit, push, then
+ \`git -C <codebase> worktree remove <your-workspace>/pr-<slug>\`.
+ Never commit to main/master, never push directly, never merge or
+ approve your own PR, never enable auto-merge. Keep the diff minimal;
+ open the PR with \`gh pr create\` (clear title, body explaining the
+ expected metric effect).
+3. **Log then register.** \`log_goal_action\` the mutation FIRST (the
+ observation window should cover merge + deploy + measurement — code
+ changes usually need 168h+), then \`register_pull_request\` with the
+ URL and the action_id so they travel together.
+4. **React to the PR's state, don't poll it.** Every tick brief carries
+ the live GitHub state. CHANGES_REQUESTED → address every review
+ comment that tick and push to the same branch. Awaiting review →
+ nudge in your diary; do not open a second PR for the same change.
+ Merged → the change is live; measure from there. Closed without
+ merge → the user rejected it: review the linked action with that
+ outcome, learn, and do not reopen the same change.
+5. **One open PR at a time.** A PR is a mutation; the one-mutation rule
+ applies until it reaches a terminal state.
+
### Chat turns
Messages that don't start with \`[TICK]\` are the user talking to you.
@@ -213,6 +254,9 @@ Do NOT invent other values.`;
const factLines = [
project?.website_url ? `- Website: ${project.website_url}` : null,
+ project?.codebase_path
+ ? `- Codebase: ${project.codebase_path} (code changes ONLY via branch + PR — see "Changing the code")`
+ : `- Codebase: none set — you cannot change the website's code until the user sets one in Settings`,
project?.google_ads_account_id
? `- Google Ads account: ${project.google_ads_account_id}`
: null,
diff --git a/notfair/src/server/goals/intake.ts b/notfair/src/server/goals/intake.ts
index 5de808f1..86dd9e25 100644
--- a/notfair/src/server/goals/intake.ts
+++ b/notfair/src/server/goals/intake.ts
@@ -16,12 +16,15 @@ export function buildIntakeKickoffMessage(input: {
goal: Goal;
connectedMcpKeys: string[];
hasSharedContext: boolean;
+ /** Platform focus the user picked at creation ("SEO / organic search —
+ * measure via the notfair-googlesearchconsole MCP"). Optional. */
+ focus?: string | null;
}): string {
- const { goal, connectedMcpKeys, hasSharedContext } = input;
+ const { goal, connectedMcpKeys, hasSharedContext, focus } = input;
return `[INTAKE] The user just created you for this ambition:
> ${goal.statement}
-
+${focus ? `\nThe user tagged this goal's focus: ${focus}. Explore and measure on that platform unless the statement clearly says otherwise.\n` : ""}
Connected data sources: ${
connectedMcpKeys.length > 0
? connectedMcpKeys.join(", ")
@@ -39,7 +42,10 @@ you record their agreement via propose_target).`;
/** Fire-and-forget from goal creation. The goal screen's embedded chat
* streams it live — one conversation per goal, on the "main" session. */
-export async function runGoalIntake(goal: Goal): Promise<void> {
+export async function runGoalIntake(
+ goal: Goal,
+ opts?: { focus?: string | null },
+): Promise<void> {
const project = getProject(goal.project_slug);
if (!project) {
console.error(`[goal-intake] project not found: ${goal.project_slug}`);
@@ -53,6 +59,7 @@ export async function runGoalIntake(goal: Goal): Promise<void> {
goal,
connectedMcpKeys,
hasSharedContext: Boolean(brief?.trim()),
+ focus: opts?.focus,
});
try {
await streamAgentTurn({
diff --git a/notfair/src/server/goals/pr-sync.test.ts b/notfair/src/server/goals/pr-sync.test.ts
new file mode 100644
index 00000000..ff68c39c
--- /dev/null
+++ b/notfair/src/server/goals/pr-sync.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+
+import { ghStateToPrState, parseGhPrView } from "@/server/goals/pr-sync";
+
+describe("ghStateToPrState", () => {
+ it("maps GitHub states, defaulting unknown to open", () => {
+ expect(ghStateToPrState("OPEN")).toBe("open");
+ expect(ghStateToPrState("MERGED")).toBe("merged");
+ expect(ghStateToPrState("CLOSED")).toBe("closed");
+ expect(ghStateToPrState("merged")).toBe("merged");
+ expect(ghStateToPrState(undefined)).toBe("open");
+ expect(ghStateToPrState("WEIRD")).toBe("open");
+ });
+});
+
+describe("parseGhPrView", () => {
+ it("parses a full gh pr view payload", () => {
+ expect(
+ parseGhPrView({
+ state: "OPEN",
+ title: "Improve /pricing meta",
+ reviewDecision: "CHANGES_REQUESTED",
+ isDraft: false,
+ mergedAt: null,
+ comments: [{}, {}],
+ reviews: [{}],
+ }),
+ ).toEqual({
+ state: "open",
+ title: "Improve /pricing meta",
+ review_decision: "CHANGES_REQUESTED",
+ comment_count: 3,
+ is_draft: false,
+ merged_at: null,
+ });
+ });
+
+ it("handles repos without required reviews (empty decision) and merges", () => {
+ expect(
+ parseGhPrView({
+ state: "MERGED",
+ title: "t",
+ reviewDecision: "",
+ isDraft: false,
+ mergedAt: "2026-07-13T01:02:03Z",
+ comments: [],
+ reviews: [],
+ }),
+ ).toEqual({
+ state: "merged",
+ title: "t",
+ review_decision: "",
+ comment_count: 0,
+ is_draft: false,
+ merged_at: "2026-07-13T01:02:03Z",
+ });
+ });
+
+ it("rejects non-object payloads", () => {
+ expect(parseGhPrView(null)).toBeNull();
+ expect(parseGhPrView("nope")).toBeNull();
+ });
+});
diff --git a/notfair/src/server/goals/pr-sync.ts b/notfair/src/server/goals/pr-sync.ts
new file mode 100644
index 00000000..872756c0
--- /dev/null
+++ b/notfair/src/server/goals/pr-sync.ts
@@ -0,0 +1,114 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+
+import {
+ applyGoalPrSync,
+ listOpenGoalPrs,
+ markGoalPrSyncError,
+ type GoalPr,
+ type GoalPrState,
+} from "@/server/db/goal-prs";
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * Sync goal PRs against GitHub via the user's authenticated `gh` CLI —
+ * the same auth path the agent used to open the PR, so private repos
+ * just work and we hold no GitHub token ourselves.
+ *
+ * Called from the tick runner (fresh state in every brief) and from the
+ * goal page when rows look stale. Failures are recorded per-row and never
+ * throw: a broken `gh` shouldn't stop a tick, and the UI shows the last
+ * good state plus the sync error.
+ */
+
+type GhPrView = {
+ state?: string; // OPEN | MERGED | CLOSED
+ title?: string;
+ reviewDecision?: string;
+ isDraft?: boolean;
+ mergedAt?: string | null;
+ comments?: unknown[];
+ reviews?: unknown[];
+};
+
+const GH_FIELDS = "state,title,reviewDecision,isDraft,mergedAt,comments,reviews";
+
+/** Map GitHub's state string to our row state. Unknown → keep "open". */
+export function ghStateToPrState(state: string | undefined): GoalPrState {
+ switch ((state ?? "").toUpperCase()) {
+ case "MERGED":
+ return "merged";
+ case "CLOSED":
+ return "closed";
+ default:
+ return "open";
+ }
+}
+
+/** Parse a `gh pr view --json` payload into the row-sync shape. */
+export function parseGhPrView(payload: unknown): {
+ state: GoalPrState;
+ title: string | null;
+ review_decision: string | null;
+ comment_count: number;
+ is_draft: boolean;
+ merged_at: string | null;
+} | null {
+ if (!payload || typeof payload !== "object") return null;
+ const view = payload as GhPrView;
+ const comments = Array.isArray(view.comments) ? view.comments.length : 0;
+ const reviews = Array.isArray(view.reviews) ? view.reviews.length : 0;
+ return {
+ state: ghStateToPrState(view.state),
+ title: typeof view.title === "string" && view.title.trim() ? view.title : null,
+ review_decision:
+ typeof view.reviewDecision === "string" ? view.reviewDecision : null,
+ comment_count: comments + reviews,
+ is_draft: !!view.isDraft,
+ merged_at: typeof view.mergedAt === "string" ? view.mergedAt : null,
+ };
+}
+
+async function syncOnePr(pr: GoalPr): Promise<GoalPr | null> {
+ try {
+ const { stdout } = await execFileAsync(
+ "gh",
+ ["pr", "view", pr.url, "--json", GH_FIELDS],
+ { timeout: 15_000, maxBuffer: 4 * 1024 * 1024 },
+ );
+ const parsed = parseGhPrView(JSON.parse(stdout));
+ if (!parsed) {
+ markGoalPrSyncError(pr.id, "gh returned an unexpected payload shape");
+ return null;
+ }
+ return applyGoalPrSync(pr.id, parsed);
+ } catch (err) {
+ markGoalPrSyncError(pr.id, err instanceof Error ? err.message : String(err));
+ return null;
+ }
+}
+
+/** Sync every non-terminal PR for a goal. Never throws. */
+export async function syncGoalPrs(goal_id: string): Promise<void> {
+ const open = listOpenGoalPrs(goal_id);
+ for (const pr of open) {
+ await syncOnePr(pr);
+ }
+}
+
+/**
+ * Fire-and-forget staleness sweep for page renders: sync when any open
+ * PR hasn't been checked in `maxAgeMs`. Rendering never awaits GitHub.
+ */
+export function maybeSyncGoalPrs(goal_id: string, maxAgeMs = 120_000): void {
+ const open = listOpenGoalPrs(goal_id);
+ const cutoff = Date.now() - maxAgeMs;
+ const stale = open.some(
+ (pr) => !pr.last_synced_at || Date.parse(pr.last_synced_at) < cutoff,
+ );
+ if (!stale) return;
+ void syncGoalPrs(goal_id).catch((err) =>
+ console.error(`[pr-sync] background sync failed for goal ${goal_id}:`, err),
+ );
+}
diff --git a/notfair/src/server/goals/register-pr.test.ts b/notfair/src/server/goals/register-pr.test.ts
new file mode 100644
index 00000000..b44dcb7b
--- /dev/null
+++ b/notfair/src/server/goals/register-pr.test.ts
@@ -0,0 +1,98 @@
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+// Hoisted so it runs before static imports evaluate db.ts (which captures
+// NOTFAIR_DATA_DIR at import time) — see goal-prs.test.ts.
+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-regpr-"));
+});
+
+// The handler pulls the live GitHub state right after registering; keep
+// the network out of the test.
+vi.mock("@/server/goals/pr-sync", () => ({
+ syncGoalPrs: vi.fn().mockResolvedValue(undefined),
+ maybeSyncGoalPrs: vi.fn(),
+}));
+
+import { handleRegisterPullRequest } from "@/server/goals/handlers";
+import { getDb } from "@/server/db/db";
+import { createGoal } from "@/server/db/goals";
+import { listGoalPrs } from "@/server/db/goal-prs";
+
+const SLUG = "proj";
+let goalId: string;
+const ctx = { project_slug: SLUG, agent_id: "agent-1" };
+
+beforeAll(() => {
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",
+ )
+ .run(SLUG, new Date().toISOString());
+ goalId = createGoal({
+ project_slug: SLUG,
+ agent_id: "agent-1",
+ statement: "Grow organic clicks",
+ }).id;
+});
+
+describe("handleRegisterPullRequest", () => {
+ it("rejects non-GitHub-PR urls", async () => {
+ for (const url of [
+ "https://github.com/acme/site",
+ "https://gitlab.com/acme/site/-/merge_requests/1",
+ "http://github.com/acme/site/pull/1",
+ "not a url",
+ ]) {
+ const r = await handleRegisterPullRequest(
+ { goal_id: goalId, url, title: "t" },
+ ctx,
+ );
+ expect(r.ok, url).toBe(false);
+ }
+ });
+
+ it("rejects another agent's goal", async () => {
+ const r = await handleRegisterPullRequest(
+ {
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/1",
+ title: "t",
+ },
+ { project_slug: SLUG, agent_id: "someone-else" },
+ );
+ expect(r.ok).toBe(false);
+ });
+
+ it("registers once and is idempotent per url", async () => {
+ const url = "https://github.com/acme/site/pull/42";
+ const first = await handleRegisterPullRequest(
+ { goal_id: goalId, url, title: "Improve /pricing meta", branch: "notfair/pricing" },
+ ctx,
+ );
+ expect(first.ok).toBe(true);
+ const second = await handleRegisterPullRequest(
+ { goal_id: goalId, url: `${url}/`, title: "dup" },
+ ctx,
+ );
+ expect(second.ok).toBe(true);
+ const rows = listGoalPrs(goalId).filter((p) => p.url === url);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.title).toBe("Improve /pricing meta");
+ });
+
+ it("rejects an action_id that belongs to a different goal", async () => {
+ const r = await handleRegisterPullRequest(
+ {
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/43",
+ title: "t",
+ action_id: "not-a-real-action",
+ },
+ ctx,
+ );
+ expect(r.ok).toBe(false);
+ });
+});
diff --git a/notfair/src/server/goals/tick.ts b/notfair/src/server/goals/tick.ts
index c05eb01f..8a076faf 100644
--- a/notfair/src/server/goals/tick.ts
+++ b/notfair/src/server/goals/tick.ts
@@ -29,6 +29,8 @@ import {
type GoalTick,
type GoalTickTrigger,
} from "@/server/db/goals";
+import { listGoalPrs, type GoalPr } from "@/server/db/goal-prs";
+import { syncGoalPrs } from "./pr-sync";
import { measureGoalMetric, type MetricMeasurement } from "./metric";
/**
@@ -59,6 +61,8 @@ export type TickContext = {
loggedSpendUsd: number;
recentLearnings: GoalLearning[];
lastTick: GoalTick | null;
+ /** PRs this goal opened against the codebase, freshly synced from GitHub. */
+ pullRequests: GoalPr[];
/** Extra leading section, e.g. an approval decision on wake-up. */
extraContext?: string;
};
@@ -67,6 +71,28 @@ function fmtValue(v: number | null): string {
return v === null ? "—" : String(v);
}
+/** One line of live PR state for the tick brief. */
+export function describePrForBrief(pr: GoalPr): string {
+ const bits: string[] = [`[${pr.state.toUpperCase()}]`];
+ if (pr.state === "open") {
+ if (pr.is_draft) bits.push("(draft)");
+ if (pr.review_decision === "CHANGES_REQUESTED") {
+ bits.push("CHANGES REQUESTED by the user");
+ } else if (pr.review_decision === "APPROVED") {
+ bits.push("approved, awaiting merge");
+ } else {
+ bits.push("awaiting the user's review");
+ }
+ if (pr.comment_count > 0) bits.push(`${pr.comment_count} comment(s)/review(s)`);
+ } else if (pr.state === "merged") {
+ bits.push(`merged ${pr.merged_at ?? ""}`.trim());
+ } else {
+ bits.push("closed WITHOUT merge");
+ }
+ if (pr.sync_error) bits.push(`(last sync failed: ${pr.sync_error})`);
+ return `${pr.title} — ${pr.url} — ${bits.join(", ")}${pr.action_id ? ` — linked action ${pr.action_id}` : ""}`;
+}
+
function daysUntil(deadline: string, nowIso: string): number {
return Math.ceil(
(new Date(deadline).getTime() - new Date(nowIso).getTime()) / 86_400_000,
@@ -171,6 +197,17 @@ export function buildTickMessage(ctx: TickContext): string {
lines.push("");
}
+ if (ctx.pullRequests.length > 0) {
+ lines.push("## Your pull requests (state synced from GitHub just now)");
+ for (const pr of ctx.pullRequests.slice(0, 6)) {
+ lines.push(`- ${describePrForBrief(pr)}`);
+ }
+ lines.push(
+ "- PR rules: the user merges, never you. CHANGES_REQUESTED → address the review comments this tick and push to the same branch. Open + unreviewed → nudge the user in your diary, don't duplicate the work. Merged → the change is live; its observation window runs from the merge. Closed unmerged → treat as rejected: review the linked action with that outcome and learn from it.",
+ );
+ lines.push("");
+ }
+
lines.push("## Recent learnings");
if (ctx.recentLearnings.length === 0) {
lines.push("- none yet — use search_learnings for older ones once they exist");
@@ -238,11 +275,13 @@ async function runGoalTickInner(
const tickNumber = markGoalTicked(goal.id);
const nowIso = new Date().toISOString();
- // Ground truth first: the platform measures, not the agent.
+ // Ground truth first: the platform measures, not the agent — and PR
+ // state comes from GitHub, not from what the agent remembers.
const measurement = await measureGoalMetric(goal);
if (measurement.ok) {
recordMetricSnapshot(goal.id, measurement.value, "tick");
}
+ await syncGoalPrs(goal.id);
const freshGoal = getGoal(goal.id)!;
const tick = createGoalTick({
@@ -266,6 +305,7 @@ async function runGoalTickInner(
loggedSpendUsd: loggedSpendTotal(goal.id),
recentLearnings: listGoalLearnings(goal.id, 8),
lastTick: getLastFinishedTick(goal.id),
+ pullRequests: listGoalPrs(goal.id, 6),
extraContext: opts.extraContext,
});
@@ -300,6 +340,9 @@ function smartSleep(goalId: string): void {
if (!goal || goal.status !== "active" || !goal.next_tick_at) return;
const nowIso = new Date().toISOString();
if (listActionsDueForReview(goal.id, nowIso).length > 0) return;
+ // An open PR means external state can flip any day (review comments,
+ // merge) and the agent must react on cadence — never oversleep it.
+ if (listGoalPrs(goal.id, 10).some((pr) => pr.state === "open")) return;
const gated = listGatedActions(goal.id, nowIso);
if (gated.length === 0) return;
const earliestReview = gated
diff --git a/notfair/src/server/harness-usage.test.ts b/notfair/src/server/harness-usage.test.ts
new file mode 100644
index 00000000..84b77fd1
--- /dev/null
+++ b/notfair/src/server/harness-usage.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ normalizeCodexRateLimits,
+ parseCodexLoginStatus,
+} from "@/server/harness-usage";
+
+describe("Codex harness usage normalization", () => {
+ it("keeps a valid single weekly window instead of treating it as signed out", () => {
+ expect(
+ normalizeCodexRateLimits({
+ primary_window: {
+ used_percent: 8,
+ limit_window_seconds: 604_800,
+ reset_at: 1_784_487_546,
+ },
+ secondary_window: null,
+ }),
+ ).toEqual([
+ {
+ label: "Weekly",
+ used_percent: 8,
+ limit_window_seconds: 604_800,
+ reset_at: 1_784_487_546,
+ },
+ ]);
+ });
+
+ it("recognizes the CLI's supported login status messages", () => {
+ expect(parseCodexLoginStatus("Logged in using ChatGPT\n")).toBe("chatgpt");
+ expect(parseCodexLoginStatus("Logged in using an API key\n")).toBe("api-key");
+ expect(parseCodexLoginStatus("Not logged in\n")).toBe("signed-out");
+ });
+});
diff --git a/notfair/src/server/harness-usage.ts b/notfair/src/server/harness-usage.ts
index b4f5b901..04093994 100644
--- a/notfair/src/server/harness-usage.ts
+++ b/notfair/src/server/harness-usage.ts
@@ -1,6 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { spawn } from "node:child_process";
/**
* Read what each local AI-agent harness exposes about the user's account
@@ -35,15 +36,28 @@ export type RateLimitWindow = {
reset_at: number;
};
+export type LabeledRateLimitWindow = RateLimitWindow & {
+ /** Stable label derived from the provider's actual window duration. */
+ label: string;
+};
+
+export type CodexAuthStatus =
+ | "chatgpt"
+ | "api-key"
+ | "agent-identity"
+ | "signed-out"
+ | "unknown";
+
export type CodexUsage = {
kind: "codex";
+ /** Authentication comes from `codex login status`, not usage shape. */
+ auth: CodexAuthStatus;
/** Codex plan name from wham/usage (e.g. "prolite", "pro", "free"). */
plan: string | null;
/** Account email from the JWT — used as a tooltip / accessibility hint. */
email: string | null;
- /** Two-window rate limits, or null when the API call failed.
- * primary = short rolling window (~5h); secondary = ~7d window. */
- rateLimit: { primary: RateLimitWindow; secondary: RateLimitWindow } | null;
+ /** Any usage windows returned by the provider, shortest first. */
+ rateLimits: LabeledRateLimitWindow[];
};
export type ClaudeUsage = {
@@ -71,6 +85,7 @@ 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",
@@ -89,26 +104,57 @@ export async function readHarnessUsage(
return value;
}
+/** Force a fresh auth + usage read after an interactive login attempt. */
+export async function refreshHarnessUsage(
+ adapter: "claude-code-local" | "codex-local",
+): Promise<HarnessUsage> {
+ cache.delete(adapter);
+ return readHarnessUsage(adapter);
+}
+
async function readCodexUsage(): Promise<HarnessUsage> {
+ let authStatus = await readCodexLoginStatus();
const authFile = path.join(os.homedir(), ".codex", "auth.json");
if (!fs.existsSync(authFile)) {
- return { kind: "codex", plan: null, email: null, rateLimit: null };
+ return {
+ kind: "codex",
+ auth: authStatus,
+ plan: null,
+ email: null,
+ rateLimits: [],
+ };
}
const auth = JSON.parse(fs.readFileSync(authFile, "utf-8")) as {
- tokens?: { access_token?: string; id_token?: string };
+ auth_mode?: string;
+ tokens?: {
+ access_token?: string;
+ id_token?: string;
+ account_id?: string;
+ };
};
const accessToken = auth.tokens?.access_token;
+ if (authStatus === "unknown") {
+ authStatus = inferAuthStatus(auth.auth_mode, Boolean(accessToken));
+ }
if (!accessToken) {
- return { kind: "codex", plan: null, email: null, rateLimit: null };
+ return {
+ kind: "codex",
+ auth: authStatus,
+ plan: null,
+ email: null,
+ rateLimits: [],
+ };
}
// Decode just to pull the email + chatgpt account id (needed as the
// ChatGPT-Account-Id header so the backend scopes the response to
// the right workspace).
- const { email, accountId } = decodeIdToken(auth.tokens?.id_token);
+ const tokenInfo = decodeIdToken(auth.tokens?.id_token);
+ const email = tokenInfo.email;
+ const accountId = auth.tokens?.account_id ?? tokenInfo.accountId;
- let plan: string | null = null;
- let rateLimit: CodexUsage["rateLimit"] = null;
+ let plan: string | null = tokenInfo.plan;
+ let rateLimits: LabeledRateLimitWindow[] = [];
try {
const ctrl = new AbortController();
const t = setTimeout(() => ctrl.abort(), 4000);
@@ -117,41 +163,40 @@ async function readCodexUsage(): Promise<HarnessUsage> {
Accept: "application/json",
};
if (accountId) headers["ChatGPT-Account-Id"] = accountId;
- const res = await fetch("https://chatgpt.com/backend-api/wham/usage", {
- headers,
- signal: ctrl.signal,
- });
- clearTimeout(t);
- if (res.ok) {
- const body = (await res.json()) as {
- plan_type?: string;
- rate_limit?: {
- primary_window?: RateLimitWindow;
- secondary_window?: RateLimitWindow;
+ try {
+ const res = await fetch("https://chatgpt.com/backend-api/wham/usage", {
+ headers,
+ signal: ctrl.signal,
+ });
+ if (res.ok) {
+ const body = (await res.json()) as {
+ plan_type?: string;
+ rate_limit?: {
+ primary_window?: RateLimitWindow | null;
+ secondary_window?: RateLimitWindow | null;
+ };
};
- };
- if (typeof body.plan_type === "string") plan = body.plan_type;
- const p = body.rate_limit?.primary_window;
- const s = body.rate_limit?.secondary_window;
- if (p && s) {
- rateLimit = { primary: p, secondary: s };
+ if (typeof body.plan_type === "string") plan = body.plan_type;
+ rateLimits = normalizeCodexRateLimits(body.rate_limit);
}
+ } finally {
+ clearTimeout(t);
}
} catch {
- // Network error / abort — leave rateLimit null; the footer falls
- // back to the plan chip only.
+ // Network error / abort. Authentication remains independently known.
}
- return { kind: "codex", plan, email, rateLimit };
+ return { kind: "codex", auth: authStatus, plan, email, rateLimits };
}
function decodeIdToken(idToken: string | undefined): {
email: string | null;
accountId: string | null;
+ plan: string | null;
} {
- if (!idToken) return { email: null, accountId: null };
+ if (!idToken) return { email: null, accountId: null, plan: null };
const parts = idToken.split(".");
- if (parts.length < 2) return { email: null, accountId: null };
+ if (parts.length < 2) return { email: null, accountId: null, plan: null };
try {
const claims = JSON.parse(
Buffer.from(parts[1]!, "base64url").toString("utf-8"),
@@ -166,12 +211,100 @@ function decodeIdToken(idToken: string | undefined): {
typeof authClaims.chatgpt_account_id === "string"
? authClaims.chatgpt_account_id
: null,
+ plan:
+ typeof authClaims.chatgpt_plan_type === "string"
+ ? authClaims.chatgpt_plan_type
+ : null,
};
} catch {
- return { email: null, accountId: null };
+ return { email: null, accountId: null, plan: null };
}
}
+export function normalizeCodexRateLimits(
+ rateLimit:
+ | {
+ primary_window?: RateLimitWindow | null;
+ secondary_window?: RateLimitWindow | null;
+ }
+ | null
+ | undefined,
+): LabeledRateLimitWindow[] {
+ return [rateLimit?.primary_window, rateLimit?.secondary_window]
+ .filter((window): window is RateLimitWindow => isRateLimitWindow(window))
+ .sort((a, b) => a.limit_window_seconds - b.limit_window_seconds)
+ .map((window) => ({ ...window, label: labelForRateLimitWindow(window) }));
+}
+
+function isRateLimitWindow(value: unknown): value is RateLimitWindow {
+ if (!value || typeof value !== "object") return false;
+ const window = value as Partial<RateLimitWindow>;
+ return (
+ typeof window.used_percent === "number" &&
+ typeof window.limit_window_seconds === "number" &&
+ typeof window.reset_at === "number"
+ );
+}
+
+function labelForRateLimitWindow(window: RateLimitWindow): string {
+ const seconds = window.limit_window_seconds;
+ if (seconds === 18_000) return "5-hour";
+ if (seconds === 86_400) return "Daily";
+ if (seconds === 604_800) return "Weekly";
+ if (seconds % 86_400 === 0) return `${seconds / 86_400}-day`;
+ if (seconds % 3_600 === 0) return `${seconds / 3_600}-hour`;
+ return "Usage";
+}
+
+export function parseCodexLoginStatus(output: string): CodexAuthStatus {
+ const normalized = output.trim().toLowerCase();
+ if (normalized.includes("logged in using chatgpt")) return "chatgpt";
+ if (normalized.includes("logged in using an api key")) return "api-key";
+ if (normalized.includes("logged in using agent identity")) {
+ return "agent-identity";
+ }
+ if (normalized.includes("not logged in")) return "signed-out";
+ return "unknown";
+}
+
+async function readCodexLoginStatus(): Promise<CodexAuthStatus> {
+ return new Promise((resolve) => {
+ let output = "";
+ let settled = false;
+ const child = spawn(CODEX_BIN, ["login", "status"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(parseCodexLoginStatus(output));
+ };
+ const timer = setTimeout(() => {
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // Ignore a process that already exited.
+ }
+ finish();
+ }, 3_000);
+ child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
+ child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));
+ child.once("error", finish);
+ child.once("close", finish);
+ });
+}
+
+function inferAuthStatus(
+ authMode: string | undefined,
+ hasAccessToken: boolean,
+): CodexAuthStatus {
+ if (!hasAccessToken) return "unknown";
+ if (authMode === "chatgpt") return "chatgpt";
+ if (authMode === "apikey" || authMode === "api-key") return "api-key";
+ return "unknown";
+}
+
function readClaudeUsage(): HarnessUsage {
const file = path.join(os.homedir(), ".claude", "stats-cache.json");
if (!fs.existsSync(file)) {
diff --git a/notfair/src/server/mcp-server/tools.ts b/notfair/src/server/mcp-server/tools.ts
index 17db3ab2..771b7930 100644
--- a/notfair/src/server/mcp-server/tools.ts
+++ b/notfair/src/server/mcp-server/tools.ts
@@ -11,6 +11,7 @@ import {
handleLogLearning,
handleProposeGoalMetric,
handleProposeTarget,
+ handleRegisterPullRequest,
handleReviewGoalAction,
handleSearchLearnings,
handleSetProjectBrief,
@@ -441,6 +442,39 @@ async function handleSetSharedContextTool(input: unknown): Promise<ToolResult> {
);
}
+// ── register_pull_request ──────────────────────────────────────────────
+
+const registerPullRequestInput = z.object({
+ ...goalIdFields,
+ url: z
+ .string()
+ .min(1)
+ .describe(
+ "The GitHub pull-request URL you just opened, e.g. https://github.com/owner/repo/pull/123.",
+ ),
+ title: z.string().min(1).max(200).describe("The PR title."),
+ branch: z.string().optional().describe("The head branch name."),
+ action_id: z
+ .string()
+ .optional()
+ .describe(
+ "The log_goal_action id this PR executes — link them so the observation gate and the PR travel together.",
+ ),
+});
+
+async function handleRegisterPullRequestTool(
+ input: unknown,
+): Promise<ToolResult> {
+ const parsed = registerPullRequestInput.safeParse(input);
+ if (!parsed.success) return invalid(parsed.error);
+ const { project_slug, agent_id, ...rest } = parsed.data;
+ const r = await handleRegisterPullRequest(rest, { project_slug, agent_id });
+ if (!r.ok) return { ok: false, error: r.error };
+ return txt(
+ `PR registered (state: ${r.data.state}). The user sees it on your Goal tab for review; every tick brief carries its live state (reviews, comments, merged/closed). Do NOT merge it yourself — the user does.`,
+ );
+}
+
// ── Registry ───────────────────────────────────────────────────────────
export const TOOLS: ToolDefinition[] = [
@@ -493,6 +527,13 @@ export const TOOLS: ToolDefinition[] = [
inputSchema: logGoalActionInput,
handler: handleLogGoalActionTool,
},
+ {
+ name: "register_pull_request",
+ description:
+ "Record a pull request you just opened against the workspace's codebase (gh pr create → register here). The PR is the approval gate for code changes: the user reviews and merges on GitHub, the platform syncs its state (review decision, comments, merged/closed) into every tick brief, and your Goal tab shows it for review. Never merge your own PR.",
+ inputSchema: registerPullRequestInput,
+ handler: handleRegisterPullRequestTool,
+ },
{
name: "review_goal_action",
description: