Skip to content

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

feat(goals): checks diary — instant manual ticks, PR links, lazy pages, collapsible rail

Yuting Zhongc6351847dc5c
diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
index 5fc8ca8a..43f632ad 100644
--- a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
+++ b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx
@@ -14,8 +14,8 @@ import {
listMetricSnapshots,
isTargetMet,
type Goal,
- type GoalTick,
} from "@/server/db/goals";
+import { listCheckRows } from "@/server/goals/checks";
import {
listSessionsForAgent,
pickLatestChatSession,
@@ -26,6 +26,7 @@ import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/regis
import { 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";
@@ -37,20 +38,14 @@ 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 { GoalChecksList } from "@/components/goal-checks-list";
+import { RailSection } from "@/components/rail-section";
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";
-function timeAgo(iso: string) {
- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
function fmtDate(iso: string | null): string {
return iso ? iso.slice(0, 10) : "—";
}
@@ -204,8 +199,13 @@ function GoalRail({
// 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);
+ // Merged/closed PRs leave the rail section; each stays reachable from
+ // the check that created it (CheckRow.prs).
+ 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);
// Chart data — plain-JSON props for the client component.
const chartPoints = snapshots.map((sn) => ({
@@ -356,8 +356,10 @@ function GoalRail({
</RailCard>
{(dueActions.length > 0 || gatedActions.length > 0) && (
- <div>
- <RailHeading>Open actions</RailHeading>
+ <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">
@@ -376,34 +378,34 @@ function GoalRail({
</li>
))}
</ul>
- </div>
+ </RailSection>
)}
- {prs.length > 0 && (
- <div>
- <RailHeading>Pull requests</RailHeading>
+ {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">
- {prs.map((pr) => (
+ {openPrs.map((pr) => (
<PrItem key={pr.id} pr={pr} />
))}
</ul>
- </div>
+ </RailSection>
)}
- <div>
- <RailHeading>Checks</RailHeading>
- {ticks.length === 0 ? (
+ <RailSection title="Checks" count={goal.tick_count}>
+ {checkRows.length === 0 ? (
<p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">
None yet — the first runs at {fmtDate(goal.next_tick_at)}.
</p>
) : (
- <ul className="m-0 flex list-none flex-col gap-2.5 p-0">
- {ticks.map((t) => (
- <TickItem key={t.id} slug={slug} agentSlug={agentSlug} goal={goal} tick={t} />
- ))}
- </ul>
+ <GoalChecksList
+ slug={slug}
+ agentSlug={agentSlug}
+ goalId={goal.id}
+ initialRows={checkRows}
+ initialHasMore={checksHaveMore}
+ />
)}
- </div>
+ </RailSection>
</>
)}
@@ -411,60 +413,6 @@ function GoalRail({
);
}
-function TickItem({
- slug,
- agentSlug,
- goal,
- tick,
-}: {
- slug: string;
- agentSlug: string;
- goal: Goal;
- tick: GoalTick;
-}) {
- const threadLabel = tick.trigger_kind === "intake" ? "main" : `tick-${tick.tick_number}`;
- return (
- <li className="text-[12px] leading-snug">
- <div className="flex items-baseline justify-between gap-2">
- <span className="font-medium">
- Check {tick.tick_number}
- {tick.metric_value !== null && (
- <span className={cn("ml-1.5 tabular-nums font-normal text-[hsl(var(--notfair-ink-3))]")}>
- → {formatMetric(tick.metric_value)}
- </span>
- )}
- </span>
- <span className="shrink-0 text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
- {timeAgo(tick.started_at)}
- </span>
- </div>
- {tick.metric_error && (
- <p className="m-0 text-[11.5px] text-[hsl(0_72%_51%)]">{tick.metric_error}</p>
- )}
- <div className="line-clamp-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
- <Markdown className="text-[11.5px] text-[hsl(var(--notfair-ink-4))] [&_p]:m-0 [&_p]:inline [&_p+p]:before:content-['_']">
- {tick.status === "running"
- ? "running…"
- : tick.status === "failed"
- ? `failed: ${tick.summary ?? "(no detail)"}`
- : tick.summary ?? "(no summary)"}
- </Markdown>
- </div>
- {/* Running agent checks are watchable live: the session attaches at
- turn start and the check page's transcript polls as it streams.
- No-op checks never carry a session and stay unlinked. */}
- {(tick.session_id || tick.status === "running") && (
- <Link
- href={projectHref(slug, `/goals/${agentSlug}/checks/${threadLabel}`)}
- className="ns-link text-[10.5px]"
- >
- {tick.status === "running" ? "watch live ›" : "details ›"}
- </Link>
- )}
- </li>
- );
-}
-
function PrItem({ pr }: { pr: GoalPr }) {
const needsReview =
pr.state === "open" &&
@@ -517,14 +465,6 @@ function RailCard({ children }: { children: React.ReactNode }) {
return <div className="ns-card p-3.5">{children}</div>;
}
-function RailHeading({ children }: { children: React.ReactNode }) {
- return (
- <p className="mb-2 mt-0 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-[hsl(var(--notfair-ink-4))]">
- {children}
- </p>
- );
-}
-
function RailStat({ k, v }: { k: string; v: string }) {
return (
<div>
diff --git a/notfair/src/components/goal-checks-list.test.tsx b/notfair/src/components/goal-checks-list.test.tsx
new file mode 100644
index 00000000..3c66f247
--- /dev/null
+++ b/notfair/src/components/goal-checks-list.test.tsx
@@ -0,0 +1,135 @@
+// @vitest-environment jsdom
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { GoalChecksList } from "@/components/goal-checks-list";
+import type { CheckRow } from "@/server/goals/checks";
+
+// Mock at the server-action boundary, per repo test conventions.
+const loadMore = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/goals", () => ({
+ loadMoreGoalChecksAction: loadMore,
+}));
+
+/** Capture IntersectionObserver callbacks so tests can trip the sentinel. */
+let ioCallbacks: IntersectionObserverCallback[];
+beforeEach(() => {
+ ioCallbacks = [];
+ loadMore.mockReset();
+ vi.stubGlobal(
+ "IntersectionObserver",
+ class {
+ constructor(cb: IntersectionObserverCallback) {
+ ioCallbacks.push(cb);
+ }
+ observe() {}
+ disconnect() {}
+ unobserve() {}
+ },
+ );
+});
+afterEach(() => vi.unstubAllGlobals());
+
+function row(tick_number: number, over: Partial<CheckRow> = {}): CheckRow {
+ return {
+ id: `tick-${tick_number}`,
+ goal_id: "g1",
+ tick_number,
+ trigger_kind: "heartbeat",
+ session_id: null,
+ metric_value: 10 + tick_number,
+ metric_error: null,
+ status: "done",
+ summary: `summary ${tick_number}`,
+ started_at: "2026-07-15T00:00:00.000Z",
+ finished_at: "2026-07-15T00:01:00.000Z",
+ prs: [],
+ ...over,
+ } as CheckRow;
+}
+
+const baseProps = {
+ slug: "proj",
+ agentSlug: "goal-1",
+ goalId: "g1",
+};
+
+async function tripSentinel() {
+ await act(async () => {
+ for (const cb of ioCallbacks) {
+ cb(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ {} as IntersectionObserver,
+ );
+ }
+ });
+}
+
+describe("GoalChecksList", () => {
+ it("renders the manual tag and PR pill on the right rows", () => {
+ render(
+ <GoalChecksList
+ {...baseProps}
+ initialRows={[
+ row(2, { trigger_kind: "manual" }),
+ row(1, {
+ prs: [
+ {
+ id: "pr1",
+ url: "https://github.com/acme/site/pull/67",
+ title: "Fix titles",
+ state: "merged",
+ },
+ ],
+ }),
+ ]}
+ initialHasMore={false}
+ />,
+ );
+ expect(screen.getByText("manually triggered")).toBeInTheDocument();
+ const pill = screen.getByRole("link", { name: "PR #67 · merged" });
+ expect(pill).toHaveAttribute("href", "https://github.com/acme/site/pull/67");
+ // hasMore=false → no sentinel, no observer registered.
+ expect(ioCallbacks).toHaveLength(0);
+ });
+
+ it("loads older checks past the cursor when the sentinel appears", async () => {
+ loadMore.mockResolvedValueOnce({ rows: [row(2), row(1)], hasMore: false });
+ render(
+ <GoalChecksList
+ {...baseProps}
+ initialRows={[row(4), row(3)]}
+ initialHasMore={true}
+ />,
+ );
+ await tripSentinel();
+ expect(loadMore).toHaveBeenCalledWith("g1", 3); // strictly older than shown
+ expect(screen.getByText("summary 1")).toBeInTheDocument();
+ expect(screen.getAllByText(/^Check/)).toHaveLength(4);
+ });
+
+ it("merges a refreshed first page without dropping loaded history", async () => {
+ loadMore.mockResolvedValueOnce({ rows: [row(2), row(1)], hasMore: false });
+ const { rerender } = render(
+ <GoalChecksList
+ {...baseProps}
+ initialRows={[row(4), row(3)]}
+ initialHasMore={true}
+ />,
+ );
+ await tripSentinel();
+
+ // The page's 5s auto-refresh re-sends a fresh first page — now with a
+ // new check 5 and check 4 flipped from running to done.
+ rerender(
+ <GoalChecksList
+ {...baseProps}
+ initialRows={[row(5), row(4, { summary: "updated 4" }), row(3)]}
+ initialHasMore={true}
+ />,
+ );
+ expect(screen.getAllByText(/^Check/)).toHaveLength(5);
+ expect(screen.getByText("updated 4")).toBeInTheDocument();
+ expect(screen.getByText("summary 1")).toBeInTheDocument(); // history kept
+ });
+});
diff --git a/notfair/src/components/goal-checks-list.tsx b/notfair/src/components/goal-checks-list.tsx
new file mode 100644
index 00000000..d28033ae
--- /dev/null
+++ b/notfair/src/components/goal-checks-list.tsx
@@ -0,0 +1,182 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useRef, useState } from "react";
+import { Loader2 } from "lucide-react";
+import { loadMoreGoalChecksAction } from "@/server/actions/goals";
+import type { CheckPr, CheckRow } from "@/server/goals/checks";
+import { projectHref } from "@/lib/project-href";
+import { formatMetric } from "@/lib/format-metric";
+import { timeAgo } from "@/lib/time-ago";
+import { cn } from "@/lib/utils";
+import { Markdown } from "@/components/markdown";
+
+/**
+ * The goal rail's Checks diary. Server-renders the newest page; older
+ * checks stream in as the sentinel scrolls into view (cursor-paged by
+ * tick_number). The page's 5s auto-refresh re-sends the first page, which
+ * is merged in by id so freshly loaded history is never dropped.
+ */
+export function GoalChecksList({
+ slug,
+ agentSlug,
+ goalId,
+ initialRows,
+ initialHasMore,
+}: {
+ slug: string;
+ agentSlug: string;
+ goalId: string;
+ initialRows: CheckRow[];
+ initialHasMore: boolean;
+}) {
+ const [rows, setRows] = useState<CheckRow[]>(initialRows);
+ // Only load responses update hasMore: a refresh of the first page says
+ // nothing about whether history below the loaded window remains.
+ const [hasMore, setHasMore] = useState(initialHasMore);
+ const [loading, setLoading] = useState(false);
+ const loadingRef = useRef(false);
+ const sentinelRef = useRef<HTMLDivElement | null>(null);
+ // The observer callback outlives renders; read rows through a ref.
+ const rowsRef = useRef(rows);
+ rowsRef.current = rows;
+
+ useEffect(() => {
+ setRows((prev) => mergeRows(prev, initialRows));
+ }, [initialRows]);
+
+ useEffect(() => {
+ const el = sentinelRef.current;
+ if (!el || !hasMore) return;
+ const io = new IntersectionObserver(async (entries) => {
+ if (!entries.some((e) => e.isIntersecting)) return;
+ if (loadingRef.current) return;
+ loadingRef.current = true;
+ setLoading(true);
+ try {
+ const oldest = Math.min(...rowsRef.current.map((r) => r.tick_number));
+ const res = await loadMoreGoalChecksAction(goalId, oldest);
+ setRows((prev) => mergeRows(prev, res.rows));
+ setHasMore(res.hasMore);
+ } finally {
+ loadingRef.current = false;
+ setLoading(false);
+ }
+ });
+ io.observe(el);
+ return () => io.disconnect();
+ }, [goalId, hasMore]);
+
+ if (rows.length === 0) return null;
+
+ return (
+ <>
+ <ul className="m-0 flex list-none flex-col divide-y divide-border/40 p-0">
+ {rows.map((t) => (
+ <CheckItem key={t.id} slug={slug} agentSlug={agentSlug} tick={t} />
+ ))}
+ </ul>
+ {hasMore && (
+ <div ref={sentinelRef} className="flex justify-center py-2">
+ {loading && (
+ <Loader2 className="size-3.5 animate-spin text-[hsl(var(--notfair-ink-4))]" />
+ )}
+ </div>
+ )}
+ </>
+ );
+}
+
+/** Upsert incoming rows by id, newest check first. */
+function mergeRows(prev: CheckRow[], incoming: CheckRow[]): CheckRow[] {
+ const byId = new Map(prev.map((r) => [r.id, r]));
+ for (const r of incoming) byId.set(r.id, r);
+ return [...byId.values()].sort((a, b) => b.tick_number - a.tick_number);
+}
+
+function CheckItem({
+ slug,
+ agentSlug,
+ tick,
+}: {
+ slug: string;
+ agentSlug: string;
+ tick: CheckRow;
+}) {
+ const threadLabel = tick.trigger_kind === "intake" ? "main" : `tick-${tick.tick_number}`;
+ return (
+ <li className="py-2.5 text-[12px] leading-snug first:pt-0 last:pb-0">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-medium">
+ Check {tick.tick_number}
+ {tick.trigger_kind === "manual" && (
+ <span className="ns-tag ml-1.5 align-middle">manually triggered</span>
+ )}
+ {tick.metric_value !== null && (
+ <span className="ml-1.5 font-normal tabular-nums text-[hsl(var(--notfair-ink-3))]">
+ → {formatMetric(tick.metric_value)}
+ </span>
+ )}
+ </span>
+ <span className="shrink-0 text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">
+ {timeAgo(tick.started_at)}
+ </span>
+ </div>
+ {tick.metric_error && (
+ <p className="m-0 text-[11.5px] text-[hsl(0_72%_51%)]">{tick.metric_error}</p>
+ )}
+ <div className="line-clamp-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">
+ <Markdown className="text-[11.5px] text-[hsl(var(--notfair-ink-4))] [&_p]:m-0 [&_p]:inline [&_p+p]:before:content-['_']">
+ {tick.status === "running"
+ ? "running…"
+ : tick.status === "failed"
+ ? `failed: ${tick.summary ?? "(no detail)"}`
+ : (tick.summary ?? "(no summary)")}
+ </Markdown>
+ </div>
+ {/* Running agent checks are watchable live: the session attaches at
+ turn start and the check page's transcript polls as it streams.
+ No-op checks never carry a session and stay unlinked. */}
+ {(tick.session_id || tick.status === "running" || tick.prs.length > 0) && (
+ <div className="mt-0.5 flex flex-wrap items-center gap-x-2.5 gap-y-1">
+ {(tick.session_id || tick.status === "running") && (
+ <Link
+ href={projectHref(slug, `/goals/${agentSlug}/checks/${threadLabel}`)}
+ className="ns-link text-[10.5px]"
+ >
+ {tick.status === "running" ? "watch live ›" : "details ›"}
+ </Link>
+ )}
+ {tick.prs.map((pr) => (
+ <CheckPrButton key={pr.id} pr={pr} />
+ ))}
+ </div>
+ )}
+ </li>
+ );
+}
+
+/** Compact colored PR pill on a check row — links straight to GitHub. */
+function CheckPrButton({ pr }: { pr: CheckPr }) {
+ const number = pr.url.match(/\/pull\/(\d+)$/)?.[1];
+ const tone =
+ pr.state === "open"
+ ? "ns-tag-accent"
+ : pr.state === "merged"
+ ? "bg-[hsl(217_60%_55%/0.14)] text-[hsl(217_60%_45%)] dark:text-[hsl(217_70%_70%)]"
+ : "ns-tag-red";
+ return (
+ <a
+ href={pr.url}
+ target="_blank"
+ rel="noreferrer"
+ title={pr.title}
+ className={cn(
+ "inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium",
+ tone,
+ )}
+ >
+ PR{number ? ` #${number}` : ""} · {pr.state}
+ </a>
+ );
+}
diff --git a/notfair/src/components/rail-section.test.tsx b/notfair/src/components/rail-section.test.tsx
new file mode 100644
index 00000000..19eb2eaa
--- /dev/null
+++ b/notfair/src/components/rail-section.test.tsx
@@ -0,0 +1,36 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+
+import { RailSection } from "@/components/rail-section";
+
+describe("RailSection", () => {
+ it("shows the body, title, and count by default", () => {
+ render(
+ <RailSection title="Checks" count={12}>
+ <p>diary rows</p>
+ </RailSection>,
+ );
+ expect(screen.getByRole("button", { name: /checks/i })).toHaveAttribute(
+ "aria-expanded",
+ "true",
+ );
+ expect(screen.getByText("(12)")).toBeInTheDocument();
+ expect(screen.getByText("diary rows")).toBeVisible();
+ });
+
+ it("collapses on click without unmounting the body (state survives)", () => {
+ render(
+ <RailSection title="Open actions">
+ <p>action rows</p>
+ </RailSection>,
+ );
+ const toggle = screen.getByRole("button", { name: /open actions/i });
+ fireEvent.click(toggle);
+ expect(toggle).toHaveAttribute("aria-expanded", "false");
+ // Hidden, not removed — client state inside the body must survive.
+ expect(screen.getByText("action rows")).not.toBeVisible();
+ fireEvent.click(toggle);
+ expect(screen.getByText("action rows")).toBeVisible();
+ });
+});
diff --git a/notfair/src/components/rail-section.tsx b/notfair/src/components/rail-section.tsx
new file mode 100644
index 00000000..dcbecbd8
--- /dev/null
+++ b/notfair/src/components/rail-section.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronDown } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+/**
+ * Collapsible goal-rail section: the uppercase heading doubles as the
+ * toggle. Collapsing hides (not unmounts) the body so client state inside
+ * — e.g. the checks list's loaded pages — survives the fold.
+ */
+export function RailSection({
+ title,
+ count,
+ defaultOpen = true,
+ children,
+}: {
+ title: string;
+ count?: number;
+ defaultOpen?: boolean;
+ children: React.ReactNode;
+}) {
+ const [open, setOpen] = useState(defaultOpen);
+ return (
+ <section>
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setOpen((o) => !o)}
+ className="mb-2 flex w-full cursor-pointer items-center justify-between gap-2 border-0 bg-transparent p-0 text-left"
+ >
+ <span className="text-[10.5px] font-semibold uppercase tracking-[0.08em] text-[hsl(var(--notfair-ink-4))]">
+ {title}
+ {count !== undefined && (
+ <span className="ml-1 font-normal tabular-nums">({count})</span>
+ )}
+ </span>
+ <ChevronDown
+ className={cn(
+ "size-3.5 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform",
+ !open && "-rotate-90",
+ )}
+ />
+ </button>
+ <div hidden={!open}>{children}</div>
+ </section>
+ );
+}
diff --git a/notfair/src/lib/time-ago.ts b/notfair/src/lib/time-ago.ts
new file mode 100644
index 00000000..480edc1d
--- /dev/null
+++ b/notfair/src/lib/time-ago.ts
@@ -0,0 +1,8 @@
+/** Compact relative timestamp: "42s ago", "5m ago", "3h ago", "2d ago". */
+export function timeAgo(iso: string): string {
+ const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
+ if (seconds < 60) return `${Math.floor(seconds)}s ago`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.ts
index fec2c47b..8a824986 100644
--- a/notfair/src/server/actions/goals.ts
+++ b/notfair/src/server/actions/goals.ts
@@ -17,6 +17,7 @@ import {
import { agentExistsOnDisk, listProjectAgents } from "@/server/agent-meta";
import { runGoalIntake } from "@/server/goals/intake";
import { runGoalTick } from "@/server/goals/tick";
+import { listCheckRows, type CheckRow } from "@/server/goals/checks";
export type GoalActionResult = {
ok: boolean;
@@ -155,7 +156,12 @@ export async function killGoalAction(
return { ok: true };
}
-/** Manual "Run tick now". Fire-and-forget; the diary shows the result. */
+/**
+ * Manual "Run tick now". Fire-and-forget for the turn itself, but the
+ * check row is claimed synchronously inside runGoalTick's pre-await
+ * prefix, so the Checks list shows the new (running, manual) check the
+ * moment this action returns.
+ */
export async function runTickNowAction(goal_id: string): Promise<GoalActionResult> {
const goal = getGoal(goal_id);
if (!goal) return { ok: false, error: "Goal not found." };
@@ -173,3 +179,17 @@ export async function runTickNowAction(goal_id: string): Promise<GoalActionResul
export async function getAgentGoalAction(agent_id: string) {
return getGoalForAgent(agent_id);
}
+
+/**
+ * Older diary page for the goal screen's Checks list — checks strictly
+ * older than `beforeTick`, newest first. Cursor pagination (not offset)
+ * so rows never shift under the reader when a new check lands mid-scroll.
+ */
+export async function loadMoreGoalChecksAction(
+ goal_id: string,
+ beforeTick: number,
+): Promise<{ rows: CheckRow[]; hasMore: boolean }> {
+ const goal = getGoal(goal_id);
+ if (!goal) return { rows: [], hasMore: false };
+ return listCheckRows(goal.id, { beforeTick });
+}
diff --git a/notfair/src/server/db/goal-prs.ts b/notfair/src/server/db/goal-prs.ts
index c5e74a1b..e28ce82f 100644
--- a/notfair/src/server/db/goal-prs.ts
+++ b/notfair/src/server/db/goal-prs.ts
@@ -22,6 +22,8 @@ export type GoalPr = {
id: string;
goal_id: string;
action_id: string | null;
+ /** The check whose turn registered this PR (null for pre-loop PRs). */
+ tick_number: number | null;
url: string;
title: string;
branch: string | null;
@@ -56,17 +58,19 @@ export function createGoalPr(input: {
title: string;
branch?: string | null;
action_id?: string | null;
+ tick_number?: number | 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, next_sync_at, last_activity_at, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT OR IGNORE INTO goal_prs (id, goal_id, action_id, tick_number, url, title, branch, next_sync_at, last_activity_at, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
id,
input.goal_id,
input.action_id ?? null,
+ input.tick_number ?? null,
input.url,
input.title,
input.branch ?? null,
diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.ts
index 47161b67..2334b7ce 100644
--- a/notfair/src/server/db/goals.ts
+++ b/notfair/src/server/db/goals.ts
@@ -726,29 +726,29 @@ export function createGoalTick(input: {
goal_id: string;
tick_number: number;
trigger_kind: GoalTickTrigger;
- metric_value?: number | null;
- metric_error?: string | null;
}): GoalTick {
const db = getDb();
const id = randomUUID();
const ts = now();
db.prepare(
`INSERT INTO goal_ticks
- (id, goal_id, tick_number, trigger_kind, metric_value, metric_error,
- status, started_at)
- VALUES (?, ?, ?, ?, ?, ?, 'running', ?)`,
- ).run(
- id,
- input.goal_id,
- input.tick_number,
- input.trigger_kind,
- input.metric_value ?? null,
- input.metric_error ?? null,
- ts,
- );
+ (id, goal_id, tick_number, trigger_kind, status, started_at)
+ VALUES (?, ?, ?, ?, 'running', ?)`,
+ ).run(id, input.goal_id, input.tick_number, input.trigger_kind, ts);
return getGoalTick(id)!;
}
+/** Backfill the measured metric onto a check created before measurement. */
+export function setGoalTickMetric(
+ id: string,
+ metric_value: number | null,
+ metric_error: string | null,
+): void {
+ getDb()
+ .prepare("UPDATE goal_ticks SET metric_value = ?, metric_error = ? WHERE id = ?")
+ .run(metric_value, metric_error, id);
+}
+
export function getGoalTick(id: string): GoalTick | null {
const row = getDb().prepare("SELECT * FROM goal_ticks WHERE id = ?").get(id);
return (row as GoalTick) ?? null;
@@ -770,7 +770,19 @@ export function finishGoalTick(
.run(status, summary ?? null, now(), id);
}
-export function listGoalTicks(goal_id: string, limit = 30): GoalTick[] {
+export function listGoalTicks(
+ goal_id: string,
+ limit = 30,
+ /** Cursor: only ticks strictly older than this tick_number (pagination). */
+ beforeTick?: number,
+): GoalTick[] {
+ if (beforeTick !== undefined) {
+ return getDb()
+ .prepare(
+ "SELECT * FROM goal_ticks WHERE goal_id = ? AND tick_number < ? ORDER BY tick_number DESC LIMIT ?",
+ )
+ .all(goal_id, beforeTick, limit) as GoalTick[];
+ }
return getDb()
.prepare(
"SELECT * FROM goal_ticks WHERE goal_id = ? ORDER BY tick_number DESC LIMIT ?",
diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.ts
index 0963f9e2..8cfafc0d 100644
--- a/notfair/src/server/db/schema.ts
+++ b/notfair/src/server/db/schema.ts
@@ -192,6 +192,9 @@ 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,
+ -- The check (goal_ticks.tick_number) whose turn registered this PR, so
+ -- the Checks list can link a check to the PR it produced.
+ tick_number INTEGER,
url TEXT NOT NULL,
title TEXT NOT NULL,
branch TEXT,
diff --git a/notfair/src/server/goals/checks.test.ts b/notfair/src/server/goals/checks.test.ts
new file mode 100644
index 00000000..c62088c1
--- /dev/null
+++ b/notfair/src/server/goals/checks.test.ts
@@ -0,0 +1,128 @@
+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-checks-"));
+});
+
+import { CHECKS_PAGE_SIZE, listCheckRows } from "./checks";
+import { getDb } from "@/server/db/db";
+import {
+ createGoal,
+ createGoalAction,
+ createGoalTick,
+} from "@/server/db/goals";
+import { createGoalPr } from "@/server/db/goal-prs";
+
+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(() => {
+ const db = getDb();
+ db.prepare("DELETE FROM goal_ticks").run();
+ db.prepare("DELETE FROM goal_prs").run();
+ db.prepare("DELETE FROM goal_actions").run();
+});
+
+function seedTicks(count: number): void {
+ for (let n = 1; n <= count; n++) {
+ createGoalTick({ goal_id: goalId, tick_number: n, trigger_kind: "heartbeat" });
+ }
+}
+
+describe("listCheckRows paging", () => {
+ it("returns the newest page with hasMore when older checks exist", () => {
+ seedTicks(CHECKS_PAGE_SIZE + 2);
+ const { rows, hasMore } = listCheckRows(goalId);
+ expect(rows).toHaveLength(CHECKS_PAGE_SIZE);
+ expect(rows[0]!.tick_number).toBe(CHECKS_PAGE_SIZE + 2);
+ expect(rows.at(-1)!.tick_number).toBe(3);
+ expect(hasMore).toBe(true);
+ });
+
+ it("reports no more pages when everything fits", () => {
+ seedTicks(4);
+ const { rows, hasMore } = listCheckRows(goalId);
+ expect(rows.map((r) => r.tick_number)).toEqual([4, 3, 2, 1]);
+ expect(hasMore).toBe(false);
+ });
+
+ it("pages strictly older than the cursor, newest first", () => {
+ seedTicks(CHECKS_PAGE_SIZE + 2);
+ const { rows, hasMore } = listCheckRows(goalId, { beforeTick: 3 });
+ expect(rows.map((r) => r.tick_number)).toEqual([2, 1]);
+ expect(hasMore).toBe(false);
+ });
+});
+
+describe("listCheckRows PR attachment", () => {
+ it("attaches a PR to the check stamped on it at registration", () => {
+ seedTicks(3);
+ createGoalPr({
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/7",
+ title: "Fix titles",
+ tick_number: 2,
+ });
+ const { rows } = listCheckRows(goalId);
+ const byTick = new Map(rows.map((r) => [r.tick_number, r.prs]));
+ expect(byTick.get(2)).toEqual([
+ expect.objectContaining({ url: "https://github.com/acme/site/pull/7", state: "open" }),
+ ]);
+ expect(byTick.get(1)).toEqual([]);
+ expect(byTick.get(3)).toEqual([]);
+ });
+
+ it("falls back to the linked action's check for pre-stamping PRs", () => {
+ seedTicks(3);
+ const action = createGoalAction({
+ goal_id: goalId,
+ tick_number: 3,
+ kind: "mutation",
+ description: "Pause wasted keywords",
+ expected_effect: "less waste",
+ review_after: null,
+ });
+ createGoalPr({
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/8",
+ title: "Legacy PR",
+ action_id: action.id,
+ // No tick_number: registered before stamping existed.
+ });
+ const { rows } = listCheckRows(goalId);
+ expect(rows.find((r) => r.tick_number === 3)!.prs).toEqual([
+ expect.objectContaining({ url: "https://github.com/acme/site/pull/8" }),
+ ]);
+ });
+
+ it("leaves PRs with neither stamp nor action off every check", () => {
+ seedTicks(2);
+ createGoalPr({
+ goal_id: goalId,
+ url: "https://github.com/acme/site/pull/9",
+ title: "Orphan",
+ });
+ const { rows } = listCheckRows(goalId);
+ expect(rows.every((r) => r.prs.length === 0)).toBe(true);
+ });
+});
diff --git a/notfair/src/server/goals/checks.ts b/notfair/src/server/goals/checks.ts
new file mode 100644
index 00000000..a78af53e
--- /dev/null
+++ b/notfair/src/server/goals/checks.ts
@@ -0,0 +1,51 @@
+import { listGoalActions, listGoalTicks, type GoalTick } from "@/server/db/goals";
+import { listGoalPrs, type GoalPrState } from "@/server/db/goal-prs";
+
+/**
+ * Check rows for the goal screen's diary list — each tick joined with the
+ * PRs its turn registered, paged newest-first by tick_number so the list
+ * can lazy-load older checks on scroll.
+ */
+
+export type CheckPr = {
+ id: string;
+ url: string;
+ title: string;
+ state: GoalPrState;
+};
+
+export type CheckRow = GoalTick & { prs: CheckPr[] };
+
+export const CHECKS_PAGE_SIZE = 10;
+
+export function listCheckRows(
+ goal_id: string,
+ opts: { limit?: number; beforeTick?: number } = {},
+): { rows: CheckRow[]; hasMore: boolean } {
+ const limit = opts.limit ?? CHECKS_PAGE_SIZE;
+ // Fetch one extra row purely to learn whether another page exists.
+ const ticks = listGoalTicks(goal_id, limit + 1, opts.beforeTick);
+ const hasMore = ticks.length > limit;
+ const page = ticks.slice(0, limit);
+
+ // PRs registered before tick stamping existed resolve their check
+ // through the linked action instead.
+ const actionTicks = new Map(
+ listGoalActions(goal_id, 200).map((a) => [a.id, a.tick_number]),
+ );
+ const prsByTick = new Map<number, CheckPr[]>();
+ for (const pr of listGoalPrs(goal_id, 100)) {
+ const tickNo =
+ pr.tick_number ?? (pr.action_id ? (actionTicks.get(pr.action_id) ?? null) : null);
+ if (tickNo == null) continue;
+ prsByTick.set(tickNo, [
+ ...(prsByTick.get(tickNo) ?? []),
+ { id: pr.id, url: pr.url, title: pr.title, state: pr.state },
+ ]);
+ }
+
+ return {
+ rows: page.map((t) => ({ ...t, prs: prsByTick.get(t.tick_number) ?? [] })),
+ hasMore,
+ };
+}
diff --git a/notfair/src/server/goals/handlers.ts b/notfair/src/server/goals/handlers.ts
index 65d1ea05..99c26504 100644
--- a/notfair/src/server/goals/handlers.ts
+++ b/notfair/src/server/goals/handlers.ts
@@ -678,6 +678,8 @@ export async function handleRegisterPullRequest(
title: input.title.trim(),
branch: input.branch?.trim() || null,
action_id: input.action_id ?? null,
+ // Same convention as log_goal_action: the current tick claims it.
+ tick_number: goal.tick_count || null,
});
// Pull the live state right away so the UI's review callout and the
diff --git a/notfair/src/server/goals/tick-run.test.ts b/notfair/src/server/goals/tick-run.test.ts
new file mode 100644
index 00000000..92442026
--- /dev/null
+++ b/notfair/src/server/goals/tick-run.test.ts
@@ -0,0 +1,101 @@
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+// Real better-sqlite3 against a tmpdir DB, per repo test conventions.
+// MUST be hoisted: static imports evaluate before module-level statements,
+// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment
+// here would silently point the suite at the developer's live ~/.notfair.
+vi.hoisted(() => {
+ const { mkdtempSync } = require("node:fs") as typeof import("node:fs");
+ const { tmpdir } = require("node:os") as typeof import("node:os");
+ const { join } = require("node:path") as typeof import("node:path");
+ process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-tick-"));
+});
+
+const mocks = vi.hoisted(() => ({
+ measureGoalMetric: vi.fn(),
+ syncGoalPrs: vi.fn(async () => {}),
+}));
+
+vi.mock("@/server/goals/metric", () => ({
+ measureGoalMetric: mocks.measureGoalMetric,
+}));
+vi.mock("./pr-sync", () => ({
+ syncGoalPrs: mocks.syncGoalPrs,
+}));
+vi.mock("@/server/adapters/registry", () => ({
+ requireAdapter: () => ({
+ // Minimal harness: one final message, no session handshake.
+ execute: async function* () {
+ yield { kind: "final", text: "did one thing" };
+ },
+ }),
+}));
+
+import { runGoalTick } from "./tick";
+import { getDb } from "@/server/db/db";
+import {
+ createGoal,
+ getGoal,
+ listGoalTicks,
+ setGoalStatus,
+ type Goal,
+} from "@/server/db/goals";
+
+const SLUG = "proj";
+let goal: Goal;
+
+beforeAll(() => {
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",
+ )
+ .run(SLUG, new Date().toISOString());
+ const created = createGoal({
+ project_slug: SLUG,
+ agent_id: "agent-1",
+ statement: "Grow organic clicks",
+ });
+ goal = setGoalStatus(created.id, "active", "test")!;
+});
+
+describe("runGoalTick claim-first lifecycle", () => {
+ it("records the check row synchronously, before measurement resolves", async () => {
+ // Measurement that stays pending until we let it finish — the window
+ // where the diary row used to not exist yet.
+ let finishMeasurement!: (v: unknown) => void;
+ mocks.measureGoalMetric.mockReturnValueOnce(
+ new Promise((r) => (finishMeasurement = r)),
+ );
+
+ const turn = runGoalTick(goal, "manual"); // deliberately not awaited yet
+
+ // The fire-and-forget caller (runTickNowAction) returns here: the row
+ // must already be in the diary, running, tagged manual, metric pending.
+ const claimed = listGoalTicks(goal.id, 10);
+ expect(claimed).toHaveLength(1);
+ expect(claimed[0]!).toMatchObject({
+ status: "running",
+ trigger_kind: "manual",
+ metric_value: null,
+ });
+
+ finishMeasurement({ ok: true, value: 42 });
+ await turn;
+
+ const done = listGoalTicks(goal.id, 10)[0]!;
+ expect(done.status).toBe("done");
+ expect(done.metric_value).toBe(42); // backfilled by setGoalTickMetric
+ expect(done.summary).toBe("did one thing");
+ });
+
+ it("marks the claimed row failed instead of stranding it running", async () => {
+ mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 43 });
+ mocks.syncGoalPrs.mockRejectedValueOnce(new Error("gh exploded"));
+
+ await runGoalTick(getGoal(goal.id)!, "manual");
+
+ const latest = listGoalTicks(goal.id, 10)[0]!;
+ expect(latest.status).toBe("failed");
+ expect(latest.summary).toContain("gh exploded");
+ });
+});
diff --git a/notfair/src/server/goals/tick.ts b/notfair/src/server/goals/tick.ts
index 3dd77440..19c44b4c 100644
--- a/notfair/src/server/goals/tick.ts
+++ b/notfair/src/server/goals/tick.ts
@@ -1,4 +1,5 @@
import { getProject } from "@/server/db/projects";
+import type { Project } from "@/types";
import { requireAdapter } from "@/server/adapters/registry";
import { workspaceDirFor } from "@/server/agents/provisioning";
import {
@@ -22,6 +23,7 @@ import {
loggedSpendTotal,
markGoalTicked,
recordMetricSnapshot,
+ setGoalTickMetric,
type Goal,
type GoalAction,
type GoalLearning,
@@ -344,23 +346,48 @@ async function runGoalTickInner(
const tickNumber = markGoalTicked(goal.id);
const nowIso = new Date().toISOString();
+ // Record the check row BEFORE the first await: everything up to here runs
+ // synchronously inside the caller's `void runGoalTick(...)`, so a manual
+ // "Run tick now" sees its check in the diary the moment the action
+ // returns. Measurement backfills the metric below.
+ const tick = createGoalTick({
+ goal_id: goal.id,
+ tick_number: tickNumber,
+ trigger_kind: trigger,
+ });
+
+ try {
+ await runClaimedTick(project, goal, tick, trigger, nowIso, opts);
+ } catch (err) {
+ // The row is already live in the diary — never strand it "running".
+ finishGoalTick(tick.id, "failed", err instanceof Error ? err.message : String(err));
+ }
+}
+
+async function runClaimedTick(
+ project: Project,
+ goal: Goal,
+ tick: GoalTick,
+ trigger: GoalTickTrigger,
+ nowIso: string,
+ opts: { extraContext?: string },
+): Promise<void> {
+ const tickNumber = tick.tick_number;
+
// 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");
}
+ setGoalTickMetric(
+ tick.id,
+ measurement.ok ? measurement.value : null,
+ measurement.ok ? null : measurement.error,
+ );
await syncGoalPrs(goal.id);
const freshGoal = getGoal(goal.id)!;
- const tick = createGoalTick({
- goal_id: goal.id,
- tick_number: tickNumber,
- trigger_kind: trigger,
- metric_value: measurement.ok ? measurement.value : null,
- metric_error: measurement.ok ? null : measurement.error,
- });
-
const actionsDueForReview = listActionsDueForReview(goal.id, nowIso);
const gatedActions = listGatedActions(goal.id, nowIso);
const pullRequests = listGoalPrs(goal.id, 10);