Skip to content

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

feat(goals): write badges on check diary rows

Yuting Zhongcd995244a3f3
diff --git a/notfair/next-env.d.ts b/notfair/next-env.d.ts
index c4b7818f..9edff1c7 100644
--- a/notfair/next-env.d.ts
+++ b/notfair/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/dev/types/routes.d.ts";
+import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/notfair/src/components/goal-checks-list.test.tsx b/notfair/src/components/goal-checks-list.test.tsx
index 5f82d162..ebacd651 100644
--- a/notfair/src/components/goal-checks-list.test.tsx
+++ b/notfair/src/components/goal-checks-list.test.tsx
@@ -44,7 +44,7 @@ function row(tick_number: number, over: Partial<CheckRow> = {}): CheckRow {
started_at: "2026-07-15T00:00:00.000Z",
finished_at: "2026-07-15T00:01:00.000Z",
prs: [],
- actions_count: 0,
+ writes: [],
...over,
} as CheckRow;
}
@@ -134,9 +134,9 @@ describe("GoalChecksList", () => {
expect(screen.getByText("summary 1")).toBeInTheDocument(); // history kept
});
- it("Action taken hides observe-only checks and fetches the filtered page", async () => {
+ it("Action taken hides read-only checks and fetches the filtered page", async () => {
loadMore.mockResolvedValueOnce({
- rows: [row(1, { actions_count: 2 })],
+ rows: [row(1, { writes: [{ label: "Goal updated", count: 1 }] })],
hasMore: false,
});
render(
@@ -144,7 +144,7 @@ describe("GoalChecksList", () => {
{...baseProps}
initialRows={[
row(4),
- row(3, { actions_count: 1 }),
+ row(3, { writes: [{ label: "Keyword paused", count: 12 }] }),
row(2, {
prs: [
{
@@ -166,7 +166,7 @@ describe("GoalChecksList", () => {
// First toggle fetches the newest filtered page from the server.
expect(loadMore).toHaveBeenCalledWith("g1", undefined, "action");
- // Observe-only check 4 is hidden; action check 3, PR check 2, and the
+ // Read-only check 4 is hidden; write check 3, PR check 2, and the
// server-fetched check 1 remain.
expect(screen.queryByText("summary 4")).not.toBeInTheDocument();
expect(screen.getByText("summary 3")).toBeInTheDocument();
@@ -179,6 +179,26 @@ describe("GoalChecksList", () => {
expect(loadMore).toHaveBeenCalledTimes(1);
});
+ it("badges each kind of modification a check made, with counts", () => {
+ render(
+ <GoalChecksList
+ {...baseProps}
+ initialRows={[
+ row(2, {
+ writes: [
+ { label: "Campaign budget updated", count: 1 },
+ { label: "Keyword paused", count: 3 },
+ ],
+ }),
+ row(1),
+ ]}
+ initialHasMore={false}
+ />,
+ );
+ expect(screen.getByText("Campaign budget updated")).toBeInTheDocument();
+ expect(screen.getByText("Keyword paused ×3")).toBeInTheDocument();
+ });
+
it("shows an empty message when no check took action", async () => {
loadMore.mockResolvedValueOnce({ rows: [], hasMore: false });
render(
diff --git a/notfair/src/components/goal-checks-list.tsx b/notfair/src/components/goal-checks-list.tsx
index 1a53669b..0d279fc2 100644
--- a/notfair/src/components/goal-checks-list.tsx
+++ b/notfair/src/components/goal-checks-list.tsx
@@ -4,7 +4,7 @@ import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { loadMoreGoalChecksAction } from "@/server/actions/goals";
-import type { CheckFilter, CheckPr, CheckRow } from "@/server/goals/checks";
+import type { CheckFilter, CheckPr, CheckRow, CheckWrite } from "@/server/goals/checks";
import { projectHref } from "@/lib/project-href";
import { formatMetric } from "@/lib/format-metric";
import { timeAgo } from "@/lib/time-ago";
@@ -17,8 +17,8 @@ import { Markdown } from "@/components/markdown";
* 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.
*
- * The "Action taken" filter hides observe-only checks (no action recorded,
- * no PR). Rows are kept in one merged store and filtered at render time,
+ * The "Action taken" filter hides read-only checks (nothing modified, no
+ * PR). Rows are kept in one merged store and filtered at render time,
* so the auto-refresh merge stays filter-agnostic; pagination re-queries
* the server with the filter so skipped checks don't count against pages.
*/
@@ -136,9 +136,9 @@ export function GoalChecksList({
);
}
-/** A check "took action" when it recorded an action or registered a PR. */
+/** A check "took action" when it modified something or registered a PR. */
function tookAction(row: CheckRow): boolean {
- return row.actions_count > 0 || row.prs.length > 0;
+ return row.writes.length > 0 || row.prs.length > 0;
}
function FilterButton({
@@ -217,7 +217,10 @@ function CheckItem({
{/* 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) && (
+ {(tick.session_id ||
+ tick.status === "running" ||
+ tick.prs.length > 0 ||
+ tick.writes.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
@@ -227,6 +230,9 @@ function CheckItem({
{tick.status === "running" ? "watch live ›" : "details ›"}
</Link>
)}
+ {tick.writes.map((write) => (
+ <CheckWriteBadge key={write.label} write={write} />
+ ))}
{tick.prs.map((pr) => (
<CheckPrButton key={pr.id} pr={pr} />
))}
@@ -236,6 +242,17 @@ function CheckItem({
);
}
+/** Compact accent pill naming one kind of modification the check made
+ * ("Campaign budget updated", "Keyword paused ×3"). */
+function CheckWriteBadge({ write }: { write: CheckWrite }) {
+ return (
+ <span className="ns-tag-accent inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium">
+ {write.label}
+ {write.count > 1 && ` ×${write.count}`}
+ </span>
+ );
+}
+
/** 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];
diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.ts
index 72f62c19..c3e338cd 100644
--- a/notfair/src/server/db/goals.ts
+++ b/notfair/src/server/db/goals.ts
@@ -620,6 +620,8 @@ export type CreateGoalActionInput = {
expected_effect: string;
review_after?: string | null;
spend_usd?: number | null;
+ /** Agent-written check-diary badge, e.g. "Budget updated". */
+ badge?: string | null;
};
export function createGoalAction(input: CreateGoalActionInput): GoalAction {
@@ -643,9 +645,30 @@ export function createGoalAction(input: CreateGoalActionInput): GoalAction {
input.spend_usd ?? null,
ts,
);
+ const badge = input.badge?.trim().slice(0, 60);
+ if (badge) {
+ db.prepare(
+ "INSERT INTO goal_action_badges (action_id, badge, created_at) VALUES (?, ?, ?)",
+ ).run(id, badge, ts);
+ }
return getGoalAction(id)!;
}
+/** Agent-written badges across a goal's actions, oldest first per tick. */
+export function listGoalActionBadges(
+ goal_id: string,
+): Array<{ tick_number: number | null; badge: string }> {
+ return getDb()
+ .prepare(
+ `SELECT a.tick_number AS tick_number, b.badge AS badge
+ FROM goal_action_badges b
+ JOIN goal_actions a ON a.id = b.action_id
+ WHERE a.goal_id = ?
+ ORDER BY a.created_at ASC, a.rowid ASC`,
+ )
+ .all(goal_id) as Array<{ tick_number: number | null; badge: string }>;
+}
+
export function getGoalAction(id: string): GoalAction | null {
const row = getDb().prepare("SELECT * FROM goal_actions WHERE id = ?").get(id);
return (row as GoalAction) ?? null;
@@ -881,6 +904,24 @@ export function listGoalTicks(
.all(goal_id, limit) as GoalTick[];
}
+/** Every MCP/tool call started across a goal's tick sessions, in event
+ * order — the checks list classifies these into write badges. */
+export function listTickToolCalls(
+ goal_id: string,
+): Array<{ tick_number: number; name: string }> {
+ return getDb()
+ .prepare(
+ `SELECT t.tick_number AS tick_number,
+ json_extract(e.payload_json, '$.name') AS name
+ FROM goal_ticks t
+ JOIN transcript_events e ON e.session_id = t.session_id
+ WHERE t.goal_id = ? AND e.kind = 'tool'
+ AND json_extract(e.payload_json, '$.phase') = 'start'
+ ORDER BY t.tick_number ASC, e.seq ASC`,
+ )
+ .all(goal_id) as Array<{ tick_number: number; name: string }>;
+}
+
/** Specific ticks by number, newest first — backs the filtered checks list. */
export function listGoalTicksByNumbers(
goal_id: string,
diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.ts
index 08126a5b..8cc0e582 100644
--- a/notfair/src/server/db/schema.ts
+++ b/notfair/src/server/db/schema.ts
@@ -161,6 +161,15 @@ CREATE TABLE IF NOT EXISTS goal_actions (
);
CREATE INDEX IF NOT EXISTS idx_goal_actions_goal ON goal_actions(goal_id, status);
+-- Agent-written check-diary badges ("Budget updated"), one per logged
+-- action. Kept in a separate table so existing CREATE-IF-NOT-EXISTS
+-- databases gain badges without altering goal_actions.
+CREATE TABLE IF NOT EXISTS goal_action_badges (
+ action_id TEXT PRIMARY KEY REFERENCES goal_actions(id) ON DELETE CASCADE,
+ badge TEXT NOT NULL,
+ created_at TEXT NOT NULL
+);
+
CREATE TABLE IF NOT EXISTS goal_metric_snapshots (
id TEXT PRIMARY KEY,
goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,
diff --git a/notfair/src/server/goals/checks.test.ts b/notfair/src/server/goals/checks.test.ts
index 2066dec7..8f9ae91d 100644
--- a/notfair/src/server/goals/checks.test.ts
+++ b/notfair/src/server/goals/checks.test.ts
@@ -11,9 +11,10 @@ vi.hoisted(() => {
process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-checks-"));
});
-import { CHECKS_PAGE_SIZE, listCheckRows } from "./checks";
+import { CHECKS_PAGE_SIZE, listCheckRows, writeBadgeForTool } from "./checks";
import { getDb } from "@/server/db/db";
import {
+ attachTickSession,
createGoal,
createGoalAction,
createGoalTick,
@@ -41,6 +42,8 @@ beforeEach(() => {
db.prepare("DELETE FROM goal_ticks").run();
db.prepare("DELETE FROM goal_prs").run();
db.prepare("DELETE FROM goal_actions").run();
+ db.prepare("DELETE FROM transcript_events").run();
+ db.prepare("DELETE FROM sessions").run();
});
function seedTicks(count: number): void {
@@ -49,6 +52,33 @@ function seedTicks(count: number): void {
}
}
+/** Attach a session to a tick and record tool-call start events in it. */
+function seedTickToolCalls(tick_number: number, toolNames: string[]): void {
+ const db = getDb();
+ const ts = new Date().toISOString();
+ const sessionId = `s-tick-${tick_number}`;
+ db.prepare(
+ `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)
+ VALUES (?, ?, 'agent-1', ?, 'codex-local', ?, ?)`,
+ ).run(sessionId, SLUG, `tick-${tick_number}`, ts, ts);
+ const tickId = db
+ .prepare("SELECT id FROM goal_ticks WHERE goal_id = ? AND tick_number = ?")
+ .get(goalId, tick_number) as { id: string };
+ attachTickSession(tickId.id, sessionId);
+ toolNames.forEach((name, i) => {
+ db.prepare(
+ `INSERT INTO transcript_events (id, session_id, seq, kind, payload_json, created_at)
+ VALUES (?, ?, ?, 'tool', ?, ?)`,
+ ).run(
+ `${sessionId}-e${i}`,
+ sessionId,
+ i + 1,
+ JSON.stringify({ kind: "tool", phase: "start", toolCallId: `item_${i}`, name }),
+ ts,
+ );
+ });
+}
+
describe("listCheckRows paging", () => {
it("returns the newest page with hasMore when older checks exist", () => {
seedTicks(CHECKS_PAGE_SIZE + 2);
@@ -74,51 +104,115 @@ describe("listCheckRows paging", () => {
});
});
-describe("listCheckRows action filter", () => {
- it("annotates every row with its action count", () => {
+describe("writeBadgeForTool", () => {
+ it("maps write tool calls to short badge labels", () => {
+ expect(
+ writeBadgeForTool("notfair_x__notfair_googleads.updateCampaignBudget"),
+ ).toBe("Campaign budget updated");
+ expect(writeBadgeForTool("mcp__NotFair-GoogleAds__pauseKeyword")).toBe(
+ "Keyword paused",
+ );
+ expect(writeBadgeForTool("notfair_x__notfair_goals.amend_goal")).toBe(
+ "Goal updated",
+ );
+ expect(writeBadgeForTool("notfair_x__notfair_goals.add_supporting_metric")).toBe(
+ "Supporting metric added",
+ );
+ expect(writeBadgeForTool("mcp__NotFair-GoogleAds__bulkAddKeywords")).toBe(
+ "Keywords added",
+ );
+ expect(writeBadgeForTool("mcp__NotFair-GoogleAds__runMutationScript")).toBe(
+ "Mutation script ran",
+ );
+ // Bare-verb and prepositional third-party tools stay grammatical.
+ expect(writeBadgeForTool("mcp__NotFair-GoogleAds__mutate")).toBe("Mutated");
+ expect(writeBadgeForTool("mcp__vercel__deploy_to_vercel")).toBe(
+ "Deployed to vercel",
+ );
+ expect(writeBadgeForTool("mcp__slack__send_message")).toBe("Message sent");
+ });
+
+ it("ignores reads, diary bookkeeping, harness built-ins, and PR tools", () => {
+ expect(writeBadgeForTool("shell")).toBeNull();
+ expect(writeBadgeForTool("Write")).toBeNull(); // workspace file, not a platform write
+ expect(writeBadgeForTool("Edit")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__posthog.exec")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__notfair_googleads.listKeywords")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__notfair_goals.get_goal")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__notfair_goals.log_goal_action")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__notfair_goals.log_learning")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__notfair_goals.review_goal_action")).toBeNull();
+ expect(
+ writeBadgeForTool("notfair_x__notfair_goals.register_pull_request"),
+ ).toBeNull();
+ expect(writeBadgeForTool("codex_apps.github.create_pull_request")).toBeNull();
+ expect(writeBadgeForTool("notfair_x__notfair_xads.runScript")).toBeNull();
+ });
+});
+
+describe("listCheckRows write badges + action filter", () => {
+ it("dedupes a check's write calls into counted badges; read-only checks get none", () => {
seedTicks(3);
+ seedTickToolCalls(2, [
+ "notfair_x__notfair_googleads.updateCampaignBudget",
+ "notfair_x__notfair_googleads.pauseKeyword",
+ "notfair_x__notfair_googleads.pauseKeyword",
+ "notfair_x__posthog.exec", // read — no badge
+ "shell",
+ ]);
+ seedTickToolCalls(3, ["notfair_x__posthog.exec", "shell"]);
+
+ const { rows } = listCheckRows(goalId);
+ const byTick = new Map(rows.map((r) => [r.tick_number, r.writes]));
+ expect(byTick.get(2)).toEqual([
+ { label: "Campaign budget updated", count: 1 },
+ { label: "Keyword paused", count: 2 },
+ ]);
+ expect(byTick.get(3)).toEqual([]);
+ expect(byTick.get(1)).toEqual([]);
+ });
+
+ it("prefers agent-written action badges over name-derived ones for that check", () => {
+ seedTicks(2);
+ seedTickToolCalls(2, ["notfair_x__notfair_googleads.updateCampaignBudget"]);
createGoalAction({
goal_id: goalId,
tick_number: 2,
kind: "mutation",
- description: "Pause wasted keywords",
- expected_effect: "less waste",
- review_after: null,
- });
- createGoalAction({
- goal_id: goalId,
- tick_number: 2,
- kind: "research",
- description: "Read search terms",
- expected_effect: "context",
+ description: "Raised campaign 123 daily budget $20 → $40",
+ expected_effect: "more clicks",
review_after: null,
+ badge: "Budget raised",
});
+
const { rows } = listCheckRows(goalId);
- expect(rows.map((r) => [r.tick_number, r.actions_count])).toEqual([
- [3, 0],
- [2, 2],
- [1, 0],
+ expect(rows.find((r) => r.tick_number === 2)!.writes).toEqual([
+ { label: "Budget raised", count: 1 },
]);
});
- it("filter=action keeps only checks with actions or PRs, cursor-paged", () => {
- seedTicks(6);
+ it("drops PR-ish agent badges and falls back to the classifier", () => {
+ seedTicks(1);
+ seedTickToolCalls(1, ["notfair_x__notfair_goals.amend_goal"]);
createGoalAction({
goal_id: goalId,
- tick_number: 5,
+ tick_number: 1,
kind: "mutation",
- description: "Raise budget",
- expected_effect: "more clicks",
- review_after: null,
- });
- createGoalAction({
- goal_id: goalId,
- tick_number: 2,
- kind: "decision",
- description: "Hold steady",
- expected_effect: "n/a",
+ description: "Opened a code PR",
+ expected_effect: "fix lands",
review_after: null,
+ badge: "PR opened", // redundant with the PR pill
});
+
+ const { rows } = listCheckRows(goalId);
+ expect(rows[0]!.writes).toEqual([{ label: "Goal updated", count: 1 }]);
+ });
+
+ it("filter=action keeps only checks that wrote or opened a PR, cursor-paged", () => {
+ seedTicks(6);
+ seedTickToolCalls(5, ["notfair_x__notfair_googleads.updateCampaignBudget"]);
+ seedTickToolCalls(3, ["notfair_x__posthog.exec"]); // read-only — excluded
+ seedTickToolCalls(2, ["notfair_x__notfair_goals.amend_goal"]);
createGoalPr({
goal_id: goalId,
url: "https://github.com/acme/site/pull/7",
diff --git a/notfair/src/server/goals/checks.ts b/notfair/src/server/goals/checks.ts
index e2f49666..3177c795 100644
--- a/notfair/src/server/goals/checks.ts
+++ b/notfair/src/server/goals/checks.ts
@@ -1,15 +1,18 @@
import {
+ listGoalActionBadges,
listGoalActions,
listGoalTicks,
listGoalTicksByNumbers,
+ listTickToolCalls,
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.
+ * PRs its turn registered and the writes its session performed, paged
+ * newest-first by tick_number so the list can lazy-load older checks on
+ * scroll.
*/
export type CheckPr = {
@@ -19,30 +22,177 @@ export type CheckPr = {
state: GoalPrState;
};
-export type CheckRow = GoalTick & { prs: CheckPr[]; actions_count: number };
+/** One kind of modification a check made, e.g. "Campaign budget updated". */
+export type CheckWrite = { label: string; count: number };
-/** "action" keeps only checks that did something: recorded an action
- * (MCP mutation, research note, decision) or registered a PR. */
+export type CheckRow = GoalTick & { prs: CheckPr[]; writes: CheckWrite[] };
+
+/** "action" keeps only checks that modified something: performed a
+ * platform/goal write or registered a PR. Read-only checks are hidden. */
export type CheckFilter = "all" | "action";
export const CHECKS_PAGE_SIZE = 10;
+/**
+ * Verb-first tool-name conventions across the MCP catalog and the goal
+ * tools (`updateCampaignBudget`, `pause_keyword`, `amend_goal`) let the
+ * leading token classify writes. Only these verbs badge; read verbs
+ * (get/list/run/search…) and diary bookkeeping (log/review/propose/
+ * register…) fall through to null.
+ */
+const WRITE_VERB_PAST: Record<string, string> = {
+ // NotFair catalog conventions (Google Ads, Meta Ads, goal tools).
+ create: "created",
+ add: "added",
+ update: "updated",
+ set: "set",
+ amend: "updated",
+ manage: "updated",
+ delete: "deleted",
+ remove: "removed",
+ pause: "paused",
+ enable: "enabled",
+ resume: "resumed",
+ rename: "renamed",
+ upload: "uploaded",
+ move: "moved",
+ link: "linked",
+ unlink: "unlinked",
+ exclude: "excluded",
+ include: "included",
+ graduate: "graduated",
+ promote: "promoted",
+ end: "ended",
+ schedule: "scheduled",
+ replace: "replaced",
+ mutate: "mutated",
+ // Common write verbs across third-party MCP servers.
+ send: "sent",
+ post: "posted",
+ publish: "published",
+ submit: "submitted",
+ approve: "approved",
+ reject: "rejected",
+ archive: "archived",
+ cancel: "canceled",
+ close: "closed",
+ merge: "merged",
+ apply: "applied",
+ insert: "inserted",
+ write: "written",
+ patch: "patched",
+ toggle: "toggled",
+ assign: "assigned",
+ revoke: "revoked",
+ grant: "granted",
+ attach: "attached",
+ detach: "detached",
+ sync: "synced",
+ import: "imported",
+ deploy: "deployed",
+ save: "saved",
+ restore: "restored",
+ invite: "invited",
+ register: "registered",
+};
+
+/**
+ * Map a raw harness tool name to a short "what changed" badge label, or
+ * null when the call isn't a write worth badging. PR creation and
+ * registration return null — the PR pill already covers those.
+ *
+ * `notfair_x__notfair_googleads.updateCampaignBudget` → "Campaign budget updated"
+ * `mcp__NotFair-GoogleAds__pauseKeyword` → "Keyword paused"
+ * `notfair_x__notfair_goals.amend_goal` → "Goal updated"
+ * `...listKeywords` / `...log_goal_action` / `shell` → null
+ */
+export function writeBadgeForTool(name: string): string | null {
+ if (!name) return null;
+ // Only namespaced MCP tools qualify. Bare harness built-ins (`shell`,
+ // `Write`, `Edit`) are workspace file/command work, not platform writes —
+ // code changes surface through the PR pill instead.
+ if (!/__|\./.test(name)) return null;
+ // Strip both namespace conventions, keeping only the action name.
+ let action = name;
+ for (const sep of ["__", "."]) {
+ const idx = action.lastIndexOf(sep);
+ if (idx >= 0 && action.slice(idx + sep.length)) action = action.slice(idx + sep.length);
+ }
+ if (/pull_?request/i.test(action)) return null;
+ // camelCase / snake_case → lowercase tokens.
+ let tokens = action
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .replace(/[_-]+/g, " ")
+ .toLowerCase()
+ .split(" ")
+ .filter(Boolean);
+ if (tokens[0] === "bulk") tokens = tokens.slice(1);
+ if (tokens[0] === "run" && tokens[1] === "mutation") return "Mutation script ran";
+ const past = WRITE_VERB_PAST[tokens[0] ?? ""];
+ if (!past) return null;
+ const obj = tokens.slice(1).join(" ");
+ const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+ // Bare-verb tools (`mutate`, `deploy`) badge as just the past tense;
+ // prepositional names (`deploy_to_vercel`) keep verb-first order.
+ if (!obj) return cap(past);
+ if (/^(to|from|into|in|for|with) /.test(obj)) return `${cap(past)} ${obj}`;
+ return `${cap(obj)} ${past}`;
+}
+
+/**
+ * tick_number → deduped write badges (first-seen order, with counts).
+ *
+ * Two sources, agent-first: badges the agent wrote via log_goal_action's
+ * `action_badge` are authoritative for their check — the agent knows what
+ * it changed regardless of tool naming. Checks with no agent badge fall
+ * back to classifying the session's tool calls by name, so history and
+ * forgetful turns still badge. PR-ish agent badges are dropped — the PR
+ * pill already covers those.
+ */
+function collectWritesByTick(goal_id: string): Map<number, CheckWrite[]> {
+ const agent = new Map<number, Map<string, CheckWrite>>();
+ for (const { tick_number, badge } of listGoalActionBadges(goal_id)) {
+ if (tick_number == null || /pull.?request|\bpr\b/i.test(badge)) continue;
+ tally(agent, tick_number, badge);
+ }
+
+ const derived = new Map<number, Map<string, CheckWrite>>();
+ for (const call of listTickToolCalls(goal_id)) {
+ if (agent.has(call.tick_number)) continue;
+ const label = writeBadgeForTool(call.name);
+ if (label) tally(derived, call.tick_number, label);
+ }
+
+ return new Map(
+ [...agent, ...derived].map(([tick, labels]) => [tick, [...labels.values()]]),
+ );
+}
+
+function tally(
+ acc: Map<number, Map<string, CheckWrite>>,
+ tick: number,
+ label: string,
+): void {
+ const labels = acc.get(tick) ?? new Map<string, CheckWrite>();
+ const entry = labels.get(label);
+ if (entry) entry.count += 1;
+ else labels.set(label, { label, count: 1 });
+ acc.set(tick, labels);
+}
+
export function listCheckRows(
goal_id: string,
opts: { limit?: number; beforeTick?: number; filter?: CheckFilter } = {},
): { rows: CheckRow[]; hasMore: boolean } {
const limit = opts.limit ?? CHECKS_PAGE_SIZE;
- const actions = listGoalActions(goal_id, 200);
- const actionCountByTick = new Map<number, number>();
- for (const a of actions) {
- if (a.tick_number == null) continue;
- actionCountByTick.set(a.tick_number, (actionCountByTick.get(a.tick_number) ?? 0) + 1);
- }
+ const writesByTick = collectWritesByTick(goal_id);
// PRs registered before tick stamping existed resolve their check
// through the linked action instead.
- const actionTicks = new Map(actions.map((a) => [a.id, a.tick_number]));
+ 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 =
@@ -57,11 +207,9 @@ export function listCheckRows(
let page: GoalTick[];
let hasMore: boolean;
if (opts.filter === "action") {
- // The eligible set is small and known upfront (bounded by the action/PR
- // fetch limits above), so page over its tick numbers directly.
- const eligible = [
- ...new Set([...actionCountByTick.keys(), ...prsByTick.keys()]),
- ]
+ // The eligible set is small and known upfront, so page over its tick
+ // numbers directly.
+ const eligible = [...new Set([...writesByTick.keys(), ...prsByTick.keys()])]
.filter((n) => opts.beforeTick === undefined || n < opts.beforeTick)
.sort((a, b) => b - a);
hasMore = eligible.length > limit;
@@ -77,7 +225,7 @@ export function listCheckRows(
rows: page.map((t) => ({
...t,
prs: prsByTick.get(t.tick_number) ?? [],
- actions_count: actionCountByTick.get(t.tick_number) ?? 0,
+ writes: writesByTick.get(t.tick_number) ?? [],
})),
hasMore,
};
diff --git a/notfair/src/server/goals/handlers.ts b/notfair/src/server/goals/handlers.ts
index 12a97a1b..b6561bbd 100644
--- a/notfair/src/server/goals/handlers.ts
+++ b/notfair/src/server/goals/handlers.ts
@@ -551,6 +551,7 @@ export type LogGoalActionInput = {
expected_effect: string;
review_after_hours?: number;
spend_usd?: number;
+ action_badge?: string;
};
export function handleLogGoalAction(
@@ -582,6 +583,7 @@ export function handleLogGoalAction(
expected_effect: input.expected_effect,
review_after,
spend_usd: input.spend_usd ?? null,
+ badge: input.action_badge ?? null,
});
return { ok: true, data: { action_id: action.id, review_after: action.review_after } };
}
diff --git a/notfair/src/server/mcp-server/tools.ts b/notfair/src/server/mcp-server/tools.ts
index 32d44f87..73ca8f26 100644
--- a/notfair/src/server/mcp-server/tools.ts
+++ b/notfair/src/server/mcp-server/tools.ts
@@ -346,6 +346,13 @@ const logGoalActionInput = z.object({
.describe(
"Estimated INCREMENTAL spend this action commits (e.g. a budget raise's expected extra cost until review). The platform sums these against the envelope and shows the total in every tick brief. Omit for spend-neutral actions.",
),
+ action_badge: z
+ .string()
+ .max(60)
+ .optional()
+ .describe(
+ "2–4 word past-tense badge naming what changed, shown on this check's diary row (e.g. 'Budget updated', 'Keywords paused', 'Ad label updated'). REQUIRED for mutations, except pull-request changes — the PR badge is automatic, omit it there. Omit for research/decision actions.",
+ ),
});
async function handleLogGoalActionTool(input: unknown): Promise<ToolResult> {