Open-source SEO, GEO, and marketing skills for AI agents.
feat(goals): moves journal in the header — done-framing, manual unlock, PRs dialog
Yuting Zhong00f8af1789dd
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsxindex dcf40b46..3f158ef2 100644--- a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx+++ b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx@@ -5,10 +5,9 @@ import { resolveAgentBySlug } from "@/server/agent-meta";import {getGoalForAgent,getLatestGoalForAgent,- listGatedActions,listGoalActions,+ listOpenGoalActions,loggedSpendTotal,- listActionsDueForReview,listGoalLearnings,listGoalTicks,listMetricSnapshots,@@ -26,7 +25,6 @@ import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/regisimport { projectHref } from "@/lib/project-href";import { goalLabel } from "@/lib/goal-label";import { formatMetric } from "@/lib/format-metric";-import { timeAgo } from "@/lib/time-ago";import { GoalMemoryDialog } from "@/components/goal-memory-dialog";import { Markdown } from "@/components/markdown";import { GoalContextDialog } from "@/components/goal-context-dialog";@@ -40,13 +38,16 @@ import { GoalProgressChart } from "@/components/goal-progress-chart";import { GoalChecksStrip } from "@/components/goal-checks-strip";import { GoalChecksList } from "@/components/goal-checks-list";import { RailSection } from "@/components/rail-section";-import { listGoalPrs, type GoalPr } from "@/server/db/goal-prs";+import { listGoalPrs } from "@/server/db/goal-prs";import {listSupportMetrics,listSupportMetricSnapshots,type GoalSupportMetric,} from "@/server/db/goal-support-metrics";import { GoalSparkline } from "@/components/goal-sparkline";+import { GoalMovesDialog } from "@/components/goal-moves-dialog";+import { type MoveRow } from "@/components/goal-moves";+import { GoalPrsDialog, type PrRow } from "@/components/goal-prs-dialog";import { maybeSyncGoalPrs } from "@/server/goals/pr-sync";import { buildCheckSquares, currentStreak } from "@/lib/goal-streak";@@ -113,6 +114,32 @@ export default async function GoalPage({const live = goal.status === "intake" || goal.status === "proposed" || goal.status === "active" || goal.status === "paused";const learnings = listGoalLearnings(goal.id, 100);+ // Header dialogs: the moves journal (every open action, whatever its+ // stage) and open PRs. Kick a background GitHub sync when PR rows look+ // stale — the page's auto-refresh poll picks up the fresh state.+ const moveRows: MoveRow[] = listOpenGoalActions(goal.id).map((a) => ({+ action_id: a.id,+ kind: a.kind,+ description: a.description,+ resources: JSON.parse(a.resources_touched_json || "[]") as string[],+ made_at: a.created_at,+ observe_until: a.review_after,+ }));+ const openPrs = listGoalPrs(goal.id, 100).filter((pr) => pr.state === "open");+ if (openPrs.length > 0) maybeSyncGoalPrs(goal.id);+ const prRows: PrRow[] = openPrs.map((pr) => ({+ id: pr.id,+ url: pr.url,+ title: pr.title,+ state: pr.state,+ review_decision: pr.review_decision,+ comment_count: pr.comment_count,+ is_draft: Boolean(pr.is_draft),+ branch: pr.branch,+ created_at: pr.created_at,+ sync_error: pr.sync_error,+ }));+return (<div className="flex min-h-0 flex-1 flex-col">{/* Every pre-terminal state before START changes server-side via@@ -153,6 +180,8 @@ export default async function GoalPage({created_at: l.created_at,}))}/>+ <GoalMovesDialog moves={moveRows} nextCheckAt={goal.next_tick_at} />+ <GoalPrsDialog prs={prRows} /></div>{live && (<GoalControls@@ -199,19 +228,10 @@ function GoalRail({}) {const snapshots = listMetricSnapshots(goal.id, 400);const ticks = listGoalTicks(goal.id, 60);- const dueActions = listActionsDueForReview(goal.id);- const gatedActions = listGatedActions(goal.id);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.- // Merged/closed PRs leave the rail section; each stays reachable from- // the check that created it (CheckRow.prs).const supportMetrics = listSupportMetrics(goal.id);- const openPrs = listGoalPrs(goal.id, 100).filter((pr) => pr.state === "open");- if (openPrs.length > 0) maybeSyncGoalPrs(goal.id);// First diary page for the lazy checks list; older pages stream in on// scroll via loadMoreGoalChecksAction.const { rows: checkRows, hasMore: checksHaveMore } = listCheckRows(goal.id);@@ -374,42 +394,6 @@ function GoalRail({</RailSection>)}- {(dueActions.length > 0 || gatedActions.length > 0) && (- <RailSection- title="Open actions"- count={dueActions.length + gatedActions.length}- >- <ul className="m-0 flex list-none flex-col gap-2 p-0">- {dueActions.map((a) => (- <li key={a.id} className="text-[12px] leading-snug">- <span className="ns-tag">review due</span>{" "}- <Markdown className="inline text-[12px] text-[hsl(var(--notfair-ink-3))] [&_p]:m-0 [&_p]:inline">- {a.description}- </Markdown>- </li>- ))}- {gatedActions.map((a) => (- <li key={a.id} className="text-[12px] leading-snug">- <span className="ns-tag-mono">observing → {fmtDate(a.review_after)}</span>{" "}- <Markdown className="inline text-[12px] text-[hsl(var(--notfair-ink-3))] [&_p]:m-0 [&_p]:inline">- {a.description}- </Markdown>- </li>- ))}- </ul>- </RailSection>- )}-- {openPrs.length > 0 && (- <RailSection title="Open pull requests" count={openPrs.length}>- <ul className="m-0 flex list-none flex-col gap-2.5 p-0">- {openPrs.map((pr) => (- <PrItem key={pr.id} pr={pr} />- ))}- </ul>- </RailSection>- )}-<RailSection title="Checks" count={goal.tick_count}>{checkRows.length === 0 ? (<p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">@@ -432,54 +416,6 @@ function GoalRail({);}-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/components/goal-moves-dialog.tsx b/notfair/src/components/goal-moves-dialog.tsxnew file mode 100644index 00000000..e8efa0f5--- /dev/null+++ b/notfair/src/components/goal-moves-dialog.tsx@@ -0,0 +1,61 @@+"use client";++import { useState } from "react";+import { Activity } from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { GoalMoves, type MoveRow } from "@/components/goal-moves";++/**+ * The goal's moves journal, one click from the header. Everything inside+ * is work the agent ALREADY did — the framing exists to kill the+ * "is this a to-do list?" misread. Hidden while there are no open moves.+ */+export function GoalMovesDialog({+ moves,+ nextCheckAt,+}: {+ moves: MoveRow[];+ nextCheckAt: string | null;+}) {+ const [open, setOpen] = useState(false);+ if (moves.length === 0) return null;++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <button+ type="button"+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-[hsl(var(--notfair-surface-2))] px-2.5 py-1 text-[12px] text-[hsl(var(--notfair-ink-3))] transition-colors hover:text-[hsl(var(--notfair-ink-1))]"+ title="Moves the agent has made that aren't scored yet"+ >+ <Activity className="size-3.5" aria-hidden />+ Moves+ <span className="tabular-nums text-[hsl(var(--notfair-ink-4))]">+ {moves.length}+ </span>+ </button>+ </DialogTrigger>+ <DialogContent className="max-h-[75vh] overflow-y-auto sm:max-w-xl">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-[15px]">+ <Activity className="size-4" aria-hidden />+ Moves+ </DialogTitle>+ <DialogDescription>+ Nothing here is a to-do — every move is already done, logged the+ moment the agent acted. A move’s effect is observed for a+ while, then its outcome gets scored at a later check.+ </DialogDescription>+ </DialogHeader>+ <GoalMoves moves={moves} nextCheckAt={nextCheckAt} />+ </DialogContent>+ </Dialog>+ );+}diff --git a/notfair/src/components/goal-moves.test.tsx b/notfair/src/components/goal-moves.test.tsxnew file mode 100644index 00000000..b58b7a67--- /dev/null+++ b/notfair/src/components/goal-moves.test.tsx@@ -0,0 +1,96 @@+// @vitest-environment jsdom+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { GoalMoves, parseResourceLabel, type MoveRow } from "./goal-moves";++// Mock at the server-action / router boundaries, per repo test conventions.+const releaseLock = vi.hoisted(() => vi.fn(async () => ({ ok: true })));+vi.mock("@/server/actions/goals", () => ({ releaseLockAction: releaseLock }));+vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn() }) }));++function move(overrides: Partial<MoveRow>): MoveRow {+ return {+ action_id: "a1",+ kind: "mutation",+ description: "Open one listing PR to acme/awesome-list.",+ resources: ["github:acme/awesome-list"],+ made_at: new Date(Date.now() - 3600_000).toISOString(),+ observe_until: new Date(Date.now() + 3 * 3600_000).toISOString(),+ ...overrides,+ };+}++describe("parseResourceLabel", () => {+ it("splits scope, name, and humanizes the fragment", () => {+ expect(parseResourceLabel("local:gh_leads.db#the-nine-blank-pr_url-rows")).toEqual({+ scope: "local",+ name: "gh_leads.db",+ detail: "the nine blank pr_url rows",+ href: null,+ });+ });++ it("links github owner/repo resources", () => {+ expect(parseResourceLabel("github:acme/awesome-list").href).toBe(+ "https://github.com/acme/awesome-list",+ );+ });++ it("keeps multi-colon names and unscoped labels intact", () => {+ expect(parseResourceLabel("xads:campaign:ol2b7").name).toBe("campaign:ol2b7");+ expect(parseResourceLabel("just-a-label").scope).toBeNull();+ });+});++describe("GoalMoves", () => {+ it("frames an observing move as done, with resources and the window end", () => {+ render(<GoalMoves moves={[move({})]} nextCheckAt={null} />);+ expect(screen.getByText(/Done — observing the effect/)).toBeInTheDocument();+ expect(screen.getByText("✓ done")).toBeInTheDocument();+ expect(screen.getByText(/made 1h ago/)).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: "acme/awesome-list" }).getAttribute("href"),+ ).toBe("https://github.com/acme/awesome-list");+ expect(screen.getByText(/observation ends in 3h ·/)).toBeInTheDocument();+ expect(screen.getByRole("progressbar")).toBeInTheDocument();+ });++ it("queues an expired-window move for the next check", () => {+ render(+ <GoalMoves+ moves={[move({ observe_until: new Date(Date.now() - 60_000).toISOString() })]}+ nextCheckAt="2026-07-17T16:00:00.000Z"+ />,+ );+ expect(screen.getByText(/Done — outcome check queued/)).toBeInTheDocument();+ expect(+ screen.getByText(/records what actually happened at its next check ·/),+ ).toBeInTheDocument();+ // No unlock button once the window is over.+ expect(screen.queryByRole("button", { name: /unlock/i })).toBeNull();+ });++ it("shows windowless research as a note, not a done-badge", () => {+ render(+ <GoalMoves+ moves={[move({ kind: "research", observe_until: null, resources: [] })]}+ nextCheckAt={null}+ />,+ );+ expect(screen.getByText(/Notes & decisions/)).toBeInTheDocument();+ expect(screen.getByText("research")).toBeInTheDocument();+ expect(screen.queryByText("✓ done")).toBeNull();+ });++ it("shows the full description untruncated", () => {+ const long = "A".repeat(400);+ render(<GoalMoves moves={[move({ description: long })]} nextCheckAt={null} />);+ expect(screen.getByText(long)).toBeInTheDocument();+ });++ it("unlocks an observing move via the server action", () => {+ render(<GoalMoves moves={[move({ action_id: "a9" })]} nextCheckAt={null} />);+ fireEvent.click(screen.getByRole("button", { name: /unlock/i }));+ expect(releaseLock).toHaveBeenCalledWith("a9");+ });+});diff --git a/notfair/src/components/goal-moves.tsx b/notfair/src/components/goal-moves.tsxnew file mode 100644index 00000000..8dbc2266--- /dev/null+++ b/notfair/src/components/goal-moves.tsx@@ -0,0 +1,293 @@+"use client";++import { useTransition } from "react";+import { useRouter } from "next/navigation";+import { toast } from "sonner";+import { LockOpen } from "lucide-react";+import { releaseLockAction } from "@/server/actions/goals";+import { timeAgo, timeUntil } from "@/lib/time-ago";++/**+ * The goal's MOVES — work the agent has already done, shown as a journal,+ * never as a to-do list. The agent logs each move the moment it acts;+ * the move then sits in an observation window while its effect matures+ * ("observing"), and once the window ends the outcome gets scored at the+ * next check ("outcome check queued"). Research notes and decisions have+ * no window at all.+ *+ * The stage chip leads every card so the agent's imperative descriptions+ * ("Open one listing PR to …") read as titles of finished work.+ */++export type MoveRow = {+ action_id: string;+ kind: "mutation" | "research" | "decision";+ /** What the agent did — its own words, logged as it acted. */+ description: string;+ /** Parsed resources_touched_json — locked while observing. */+ resources: string[];+ /** ISO time the move was made (and logged). */+ made_at: string;+ /** ISO end of the observation window; null = no window (notes). */+ observe_until: string | null;+};++export type MoveStage = "observing" | "outcome-due" | "note";++export function moveStage(move: MoveRow, now = Date.now()): MoveStage {+ if (!move.observe_until) return "note";+ return Date.parse(move.observe_until) > now ? "observing" : "outcome-due";+}++export type ParsedResource = {+ /** Label prefix (`local`, `github`, `xads`, `page`, …); null if none. */+ scope: string | null;+ /** The thing itself: a file, an `owner/repo`, a campaign id, a path. */+ name: string;+ /** Humanized `#fragment` — the subset of the resource actually locked. */+ detail: string | null;+ /** Outbound link when the name is unambiguous (GitHub repos). */+ href: string | null;+};++export function parseResourceLabel(raw: string): ParsedResource {+ const m = raw.match(/^([a-z][\w-]*):(.+)$/i);+ const scope = m ? m[1]! : null;+ let name = m ? m[2]! : raw;+ let detail: string | null = null;+ const hash = name.indexOf("#");+ if (hash > 0) {+ // Fragments are kebab-case notes ("the-nine-blank-pr_url-rows…") —+ // dashes become spaces; underscores stay (they're inside identifiers).+ detail = name+ .slice(hash + 1)+ .replace(/-+/g, " ")+ .trim();+ name = name.slice(0, hash);+ }+ const href =+ scope === "github" && /^[\w.-]+\/[\w.-]+$/.test(name)+ ? `https://github.com/${name}`+ : null;+ return { scope, name, detail, href };+}++function fmtWhen(iso: string): string {+ return new Date(iso).toLocaleString(undefined, {+ month: "short",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ });+}++/** Elapsed share of the observation window, 0..1. */+function windowProgress(made_at: string, observe_until: string, now = Date.now()): number {+ const start = Date.parse(made_at);+ const end = Date.parse(observe_until);+ if (!(end > start)) return 1;+ return Math.min(1, Math.max(0, (now - start) / (end - start)));+}++const SECTION: Record<MoveStage, { title: string; blurb: string }> = {+ observing: {+ title: "Done — observing the effect",+ blurb:+ "The move is made; its resources stay untouched until the window ends so the effect can be measured cleanly.",+ },+ "outcome-due": {+ title: "Done — outcome check queued",+ blurb: "The window is over; the agent scores what actually happened at its next check.",+ },+ note: {+ title: "Notes & decisions",+ blurb: "Research and decisions the agent recorded — no observation window.",+ },+};++export function GoalMoves({+ moves,+ nextCheckAt,+}: {+ moves: MoveRow[];+ /** ISO time of the next scheduled check, for the outcome-due hint. */+ nextCheckAt: string | null;+}) {+ const router = useRouter();+ const [pending, startTransition] = useTransition();++ function unlock(action_id: string) {+ startTransition(async () => {+ const r = await releaseLockAction(action_id);+ if (!r.ok) {+ toast.error(r.error ?? "Could not unlock.");+ return;+ }+ toast.success("Unlocked — the outcome check is now queued for the next check.");+ router.refresh();+ });+ }++ const groups: Array<{ stage: MoveStage; items: MoveRow[] }> = [+ {+ stage: "observing",+ items: moves+ .filter((m) => moveStage(m) === "observing")+ .sort((a, b) => a.observe_until!.localeCompare(b.observe_until!)),+ },+ {+ stage: "outcome-due",+ items: moves+ .filter((m) => moveStage(m) === "outcome-due")+ .sort((a, b) => a.made_at.localeCompare(b.made_at)),+ },+ {+ stage: "note",+ items: moves+ .filter((m) => moveStage(m) === "note")+ .sort((a, b) => b.made_at.localeCompare(a.made_at)),+ },+ ];++ return (+ <div className="flex flex-col gap-5">+ {groups+ .filter((g) => g.items.length > 0)+ .map((g) => (+ <section key={g.stage} aria-label={SECTION[g.stage].title}>+ <h3 className="m-0 text-[11px] font-semibold tracking-[0.08em] uppercase text-[hsl(var(--notfair-ink-3))]">+ {SECTION[g.stage].title}+ <span className="ml-1 font-normal tabular-nums">({g.items.length})</span>+ </h3>+ <p className="m-0 mt-0.5 mb-2 text-[11.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">+ {SECTION[g.stage].blurb}+ </p>+ <ul className="m-0 flex list-none flex-col gap-2.5 p-0">+ {g.items.map((move) => (+ <MoveCard+ key={move.action_id}+ move={move}+ nextCheckAt={nextCheckAt}+ pending={pending}+ onUnlock={unlock}+ />+ ))}+ </ul>+ </section>+ ))}+ </div>+ );+}++function MoveCard({+ move,+ nextCheckAt,+ pending,+ onUnlock,+}: {+ move: MoveRow;+ nextCheckAt: string | null;+ pending: boolean;+ onUnlock: (action_id: string) => void;+}) {+ const stage = moveStage(move);+ return (+ <li className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)] px-4 py-3.5">+ <div className="flex items-center justify-between gap-3">+ <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">+ {stage === "note" ? (+ <span className="ns-tag-mono mr-1.5">{move.kind}</span>+ ) : (+ <span className="ns-tag mr-1.5">✓ done</span>+ )}+ made {timeAgo(move.made_at)}+ </span>+ {stage === "observing" && (+ <button+ type="button"+ disabled={pending}+ onClick={() => onUnlock(move.action_id)}+ className="ns-btn ns-btn-outline ns-btn-sm shrink-0"+ title="End the observation window now — the outcome check moves to the next check"+ >+ <LockOpen className="size-3" aria-hidden />+ Unlock+ </button>+ )}+ </div>++ {/* The move itself — the agent's own record, in full. */}+ <p className="m-0 mt-2 text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-2))]">+ {move.description}+ </p>++ {stage === "observing" && (+ <>+ {move.resources.length > 0 && (+ <ul className="m-0 mt-2.5 flex list-none flex-col gap-1 p-0">+ {move.resources.map((raw) => {+ const r = parseResourceLabel(raw);+ return (+ <li key={raw} className="text-[12px] leading-relaxed">+ <span className="text-[hsl(var(--notfair-ink-4))]">🔒 </span>+ {r.scope && (+ <span className="ns-tag-mono mr-1.5 align-[1px]">{r.scope}</span>+ )}+ {r.href ? (+ <a+ href={r.href}+ target="_blank"+ rel="noreferrer"+ className="ns-link font-medium break-all"+ >+ {r.name}+ </a>+ ) : (+ <span className="font-medium break-all">{r.name}</span>+ )}+ {r.detail && (+ <span className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">+ {" "}+ — only {r.detail}+ </span>+ )}+ </li>+ );+ })}+ </ul>+ )}+ <div className="mt-2.5">+ <div+ className="h-1 overflow-hidden rounded-full bg-[hsl(var(--notfair-warn)/0.18)]"+ role="progressbar"+ aria-label="Observation window elapsed"+ aria-valuenow={Math.round(+ windowProgress(move.made_at, move.observe_until!) * 100,+ )}+ aria-valuemin={0}+ aria-valuemax={100}+ >+ <div+ className="h-full rounded-full bg-[hsl(var(--notfair-warn))]"+ style={{+ width: `${Math.max(2, windowProgress(move.made_at, move.observe_until!) * 100)}%`,+ }}+ />+ </div>+ <p className="m-0 mt-1.5 text-right text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">+ observation ends {timeUntil(move.observe_until!)} ·{" "}+ {fmtWhen(move.observe_until!)}+ </p>+ </div>+ </>+ )}++ {stage === "outcome-due" && (+ <p className="m-0 mt-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">+ The agent records what actually happened at its next check+ {nextCheckAt ? ` · ${fmtWhen(nextCheckAt)}` : ""}.+ </p>+ )}+ </li>+ );+}diff --git a/notfair/src/components/goal-prs-dialog.tsx b/notfair/src/components/goal-prs-dialog.tsxnew file mode 100644index 00000000..4c140b2b--- /dev/null+++ b/notfair/src/components/goal-prs-dialog.tsx@@ -0,0 +1,117 @@+"use client";++import { useState } from "react";+import { GitPullRequest } from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { timeAgo } from "@/lib/time-ago";++/** Plain-JSON PR row for the dialog (subset of the goal_prs table). */+export type PrRow = {+ id: string;+ url: string;+ title: string;+ state: "open" | "merged" | "closed";+ review_decision: string | null;+ comment_count: number;+ is_draft: boolean;+ branch: string | null;+ created_at: string;+ sync_error: string | null;+};++/**+ * The goal's open pull requests, one click from the header — count on the+ * button like Memory, full list with review state in the modal. Merged and+ * closed PRs stay reachable from the check that produced them; this is the+ * "what's waiting on a human" view. Hidden while nothing is open.+ */+export function GoalPrsDialog({ prs }: { prs: PrRow[] }) {+ const [open, setOpen] = useState(false);+ if (prs.length === 0) return null;++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <button+ type="button"+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-[hsl(var(--notfair-surface-2))] px-2.5 py-1 text-[12px] text-[hsl(var(--notfair-ink-3))] transition-colors hover:text-[hsl(var(--notfair-ink-1))]"+ title="Open pull requests this goal's agent is waiting on"+ >+ <GitPullRequest className="size-3.5" aria-hidden />+ PRs+ <span className="tabular-nums text-[hsl(var(--notfair-ink-4))]">+ {prs.length}+ </span>+ </button>+ </DialogTrigger>+ <DialogContent className="max-h-[70vh] overflow-y-auto sm:max-w-lg">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-[15px]">+ <GitPullRequest className="size-4" aria-hidden />+ Open pull requests+ </DialogTitle>+ <DialogDescription>+ Submissions awaiting review — the agent reacts to each PR’s+ state on every check.+ </DialogDescription>+ </DialogHeader>+ <ul className="m-0 flex list-none flex-col gap-3 p-0">+ {prs.map((pr) => (+ <PrItem key={pr.id} pr={pr} />+ ))}+ </ul>+ </DialogContent>+ </Dialog>+ );+}++function PrItem({ pr }: { pr: PrRow }) {+ return (+ <li className="rounded-md bg-[hsl(var(--notfair-surface-2)/0.5)] px-3 py-2.5 text-[12.5px] 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-1 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>+ );+}diff --git a/notfair/src/lib/time-ago.test.ts b/notfair/src/lib/time-ago.test.tsnew file mode 100644index 00000000..cc2e0227--- /dev/null+++ b/notfair/src/lib/time-ago.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";+import { timeUntil } from "./time-ago";++const NOW = Date.parse("2026-07-17T12:00:00.000Z");++describe("timeUntil", () => {+ it("formats each magnitude compactly", () => {+ expect(timeUntil("2026-07-17T12:00:30.000Z", NOW)).toBe("in 30s");+ expect(timeUntil("2026-07-17T12:45:00.000Z", NOW)).toBe("in 45m");+ expect(timeUntil("2026-07-17T15:00:00.000Z", NOW)).toBe("in 3h");+ expect(timeUntil("2026-07-19T12:00:00.000Z", NOW)).toBe("in 2d");+ });++ it("rounds up so a lock never reads as shorter than it is", () => {+ expect(timeUntil("2026-07-17T13:00:01.000Z", NOW)).toBe("in 2h");+ expect(timeUntil("2026-07-17T12:00:31.000Z", NOW)).toBe("in 31s");+ });++ it("reads 'now' once the moment has passed", () => {+ expect(timeUntil("2026-07-17T11:59:00.000Z", NOW)).toBe("now");+ expect(timeUntil("2026-07-17T12:00:00.000Z", NOW)).toBe("now");+ });+});diff --git a/notfair/src/lib/time-ago.ts b/notfair/src/lib/time-ago.tsindex 480edc1d..43f38013 100644--- a/notfair/src/lib/time-ago.ts+++ b/notfair/src/lib/time-ago.ts@@ -6,3 +6,15 @@ export function timeAgo(iso: string): string {if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;return `${Math.floor(seconds / 86400)}d ago`;}++/** Compact future counterpart: "in 42s", "in 5m", "in 3h", "in 2d".+ * A timestamp already in the past reads "now" — the state flips on the+ * next refresh, so don't pretend there's time left. */+export function timeUntil(iso: string, now = Date.now()): string {+ const seconds = (new Date(iso).getTime() - now) / 1000;+ if (seconds <= 0) return "now";+ if (seconds < 60) return `in ${Math.ceil(seconds)}s`;+ if (seconds < 3600) return `in ${Math.ceil(seconds / 60)}m`;+ if (seconds < 86400) return `in ${Math.ceil(seconds / 3600)}h`;+ return `in ${Math.ceil(seconds / 86400)}d`;+}diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.tsindex 8343f172..dc241d73 100644--- a/notfair/src/server/actions/goals.ts+++ b/notfair/src/server/actions/goals.ts@@ -4,6 +4,7 @@ import { revalidatePath } from "next/cache";import {createGoal,deleteGoalsForAgent,+ endActionObservation,getGoal,getGoalForAgent,renameGoal,@@ -198,6 +199,20 @@ export async function deleteGoalAction(goal_id: string): Promise<GoalActionResulreturn { ok: true };}+/**+ * Manual unlock: end an action's observation window now. The resources+ * release immediately; the action becomes due for review, so the agent+ * scores its outcome on the next check exactly as it would at expiry.+ */+export async function releaseLockAction(action_id: string): Promise<GoalActionResult> {+ const released = endActionObservation(action_id);+ if (!released) {+ return { ok: false, error: "Lock not found — it may already be released." };+ }+ revalidatePath("/", "layout");+ return { ok: true };+}+/*** Manual "Run tick now". Fire-and-forget for the turn itself, but the* check row is claimed synchronously inside runGoalTick's pre-awaitdiff --git a/notfair/src/server/db/goals.test.ts b/notfair/src/server/db/goals.test.tsindex bdb978a3..cca2dcae 100644--- a/notfair/src/server/db/goals.test.ts+++ b/notfair/src/server/db/goals.test.ts@@ -14,9 +14,12 @@ vi.hoisted(() => {import { getDb } from "./db";import {createGoal,+ createGoalAction,deleteGoalsForAgent,+ endActionObservation,getGoal,getPinnedGoalIds,+ listGatedActions,recordMetricSnapshot,renameGoal,setGoalPinned,@@ -67,6 +70,26 @@ describe("goal pins", () => {});});+describe("endActionObservation", () => {+ it("releases a gated action into review-due without touching its status", () => {+ const goal = createGoal({ project_slug: SLUG, agent_id: "a-unlock", statement: "x" });+ const action = createGoalAction({+ goal_id: goal.id,+ kind: "mutation",+ description: "gated",+ expected_effect: "n/a",+ review_after: new Date(Date.now() + 3600_000).toISOString(),+ });+ expect(listGatedActions(goal.id)).toHaveLength(1);++ const released = endActionObservation(action.id);+ expect(released?.status).toBe("open");+ expect(listGatedActions(goal.id)).toHaveLength(0);+ // Releasing twice (or releasing a windowless action) is a no-op.+ expect(endActionObservation(action.id)).toBeNull();+ });+});+describe("deleteGoalsForAgent", () => {it("deletes the goal rows and cascades child tables", () => {const goal = createGoal({ project_slug: SLUG, agent_id: "a-del", statement: "delete me" });diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.tsindex c737e740..d51fb51b 100644--- a/notfair/src/server/db/goals.ts+++ b/notfair/src/server/db/goals.ts@@ -699,6 +699,24 @@ export function listActionsDueForReview(goal_id: string, nowIso = now()): GoalAc.all(goal_id, nowIso) as GoalAction[];}+/**+ * End an action's observation window NOW — the user's manual unlock.+ * The action stays open and becomes immediately due for review, so the+ * agent scores it on its next check; nothing is deleted or rewritten.+ */+export function endActionObservation(id: string): GoalAction | null {+ const ts = now();+ const r = getDb()+ .prepare(+ `UPDATE goal_actions SET review_after = ?+ WHERE id = ? AND status = 'open'+ AND review_after IS NOT NULL AND review_after > ?`,+ )+ .run(ts, id, ts);+ if (r.changes === 0) return null;+ return getGoalAction(id);+}+/** Open mutations still inside their observation window — the gate. */export function listGatedActions(goal_id: string, nowIso = now()): GoalAction[] {return getDb()