Skip to content

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

test: comprehensive unit suite — 196→810 tests, coverage 23→58% (checkpoint)

Yuting Zhong951c56e63758
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/package.json b/notfair/package.json
index 533b40f4..83f3d095 100644
--- a/notfair/package.json
+++ b/notfair/package.json
@@ -19,7 +19,8 @@
"cli": "node bin/cli.mjs",
"typecheck": "tsc --noEmit",
"test": "vitest run",
- "test:watch": "vitest"
+ "test:watch": "vitest",
+ "test:coverage": "vitest run --coverage"
},
"dependencies": {
"@next/env": "16.2.6",
@@ -58,6 +59,7 @@
"@types/react-dom": "^19.0.0",
"@types/ws": "^8.18.1",
"@vitejs/plugin-react": "^6.0.2",
+ "@vitest/coverage-v8": "4.1.10",
"eslint": "^9.0.0",
"eslint-config-next": "^16.2.6",
"jsdom": "^29.1.1",
diff --git a/notfair/pnpm-lock.yaml b/notfair/pnpm-lock.yaml
index d4ab89f2..9f92d78d 100644
--- a/notfair/pnpm-lock.yaml
+++ b/notfair/pnpm-lock.yaml
@@ -111,6 +111,9 @@ importers:
'@vitejs/plugin-react':
specifier: ^6.0.2
+ '@vitest/coverage-v8':
+ specifier: 4.1.10
+ version: 4.1.10([email protected])
eslint:
specifier: ^9.0.0
version: 9.39.4([email protected])
@@ -134,7 +137,7 @@ importers:
version: 5.9.3
vitest:
specifier: ^4.1.10
packages:
@@ -231,6 +234,10 @@ packages:
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
engines: {node: '>=6.9.0'}
+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
+ engines: {node: '>=18'}
+
'@bramus/[email protected]':
resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}
hasBin: true
@@ -1938,6 +1945,15 @@ packages:
babel-plugin-react-compiler:
optional: true
+ '@vitest/[email protected]':
+ resolution: {integrity: sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g==}
+ peerDependencies:
+ '@vitest/browser': 4.1.10
+ vitest: 4.1.10
+ peerDependenciesMeta:
+ '@vitest/browser':
+ optional: true
+
'@vitest/[email protected]':
resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==}
@@ -2045,6 +2061,9 @@ packages:
resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==}
+ resolution: {integrity: sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA==}
+
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
@@ -2684,6 +2703,9 @@ packages:
resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}
+
resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}
@@ -2865,6 +2887,18 @@ packages:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
+ engines: {node: '>=8'}
+
+ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}
+ engines: {node: '>=10'}
+
+ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}
+ engines: {node: '>=8'}
+
resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}
engines: {node: '>= 0.4'}
@@ -2873,6 +2907,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
+ resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}
+
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -3044,6 +3081,13 @@ packages:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
+ resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==}
+
+ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}
@@ -4209,6 +4253,8 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
+ '@bcoe/[email protected]': {}
+
'@bramus/[email protected]':
dependencies:
css-tree: 3.2.1
@@ -5726,6 +5772,20 @@ snapshots:
'@rolldown/pluginutils': 1.0.1
+ dependencies:
+ '@bcoe/v8-coverage': 1.0.2
+ '@vitest/utils': 4.1.10
+ ast-v8-to-istanbul: 1.0.5
+ istanbul-lib-coverage: 3.2.2
+ istanbul-lib-report: 3.0.1
+ istanbul-reports: 3.2.0
+ magicast: 0.5.3
+ obug: 2.1.3
+ std-env: 4.2.0
+ tinyrainbow: 3.1.0
+
'@vitest/[email protected]':
dependencies:
'@standard-schema/spec': 1.1.0
@@ -5871,6 +5931,12 @@ snapshots:
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ estree-walker: 3.0.3
+ js-tokens: 10.0.0
+
@@ -6666,6 +6732,8 @@ snapshots:
transitivePeerDependencies:
- '@noble/hashes'
+
@@ -6836,6 +6904,19 @@ snapshots:
+
+ dependencies:
+ istanbul-lib-coverage: 3.2.2
+ make-dir: 4.0.0
+ supports-color: 7.2.0
+
+ dependencies:
+ html-escaper: 2.0.2
+ istanbul-lib-report: 3.0.1
+
dependencies:
define-data-property: 1.1.4
@@ -6847,6 +6928,8 @@ snapshots:
+
@@ -6999,6 +7082,16 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
+ dependencies:
+ '@babel/parser': 7.29.3
+ '@babel/types': 7.29.0
+ source-map-js: 1.2.1
+
+ dependencies:
+ semver: 7.8.0
+
@@ -8319,7 +8412,7 @@ snapshots:
jiti: 2.7.0
tsx: 4.22.1
dependencies:
'@vitest/expect': 4.1.10
@@ -8344,6 +8437,7 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.0
'@types/node': 22.19.19
+ '@vitest/coverage-v8': 4.1.10([email protected])
jsdom: 29.1.1
transitivePeerDependencies:
- msw
diff --git a/notfair/src/components/add-mcp-server-card.test.tsx b/notfair/src/components/add-mcp-server-card.test.tsx
new file mode 100644
index 00000000..af9a3981
--- /dev/null
+++ b/notfair/src/components/add-mcp-server-card.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { AddMcpServerMenu } from "@/components/add-mcp-server-card";
+
+// Mock at the server-action boundary, per repo test conventions.
+const addServer = vi.hoisted(() => vi.fn());
+const startConnect = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/mcp", () => ({
+ addUserMcpServerAction: addServer,
+ startMcpConnect: startConnect,
+}));
+
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),
+}));
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({
+ toast: { success: toastSuccess, error: toastError },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+function openMenu() {
+ fireEvent.keyDown(screen.getByRole("button", { name: /add server/i }), {
+ key: "Enter",
+ });
+}
+
+describe("AddMcpServerMenu", () => {
+ it("offers Browse and Custom paths from the default trigger", () => {
+ render(<AddMcpServerMenu />);
+ openMenu();
+ expect(
+ screen.getByRole("menuitem", { name: /browse connectors/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("menuitem", { name: /add custom connector/i }),
+ ).toBeInTheDocument();
+ });
+
+ it("renders a custom trigger node instead of the default pill", () => {
+ render(
+ <AddMcpServerMenu
+ trigger={<button type="button">More tools</button>}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "More tools" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /add server/i })).toBeNull();
+ });
+
+ it("opens the Browse connectors grid from the menu", async () => {
+ render(<AddMcpServerMenu />);
+ openMenu();
+ fireEvent.click(screen.getByRole("menuitem", { name: /browse connectors/i }));
+ expect(
+ await screen.findByRole("heading", { name: "Browse connectors" }),
+ ).toBeInTheDocument();
+ });
+
+ it("adds a custom OAuth connector and refreshes on success", async () => {
+ addServer.mockResolvedValue({ ok: true, key: "stripe" });
+ render(<AddMcpServerMenu />);
+ openMenu();
+ fireEvent.click(
+ screen.getByRole("menuitem", { name: /add custom connector/i }),
+ );
+ fireEvent.change(await screen.findByLabelText("Name"), {
+ target: { value: "Stripe" },
+ });
+ fireEvent.change(screen.getByLabelText("Remote MCP server URL"), {
+ target: { value: "https://mcp.stripe.com/" },
+ });
+ fireEvent.submit(screen.getByRole("button", { name: /^add server$/i }));
+
+ await waitFor(() => {
+ expect(addServer).toHaveBeenCalledWith({
+ display_name: "Stripe",
+ resource_url: "https://mcp.stripe.com/",
+ });
+ expect(toastSuccess).toHaveBeenCalledWith(
+ "Added MCP server 'stripe'. Click Connect to authorize.",
+ );
+ expect(refresh).toHaveBeenCalled();
+ });
+ });
+
+ it("shows the probe failure inline and keeps the dialog open", async () => {
+ addServer.mockResolvedValue({ ok: false, error: "No OAuth discovery." });
+ render(<AddMcpServerMenu />);
+ openMenu();
+ fireEvent.click(
+ screen.getByRole("menuitem", { name: /add custom connector/i }),
+ );
+ fireEvent.change(await screen.findByLabelText("Name"), {
+ target: { value: "Broken" },
+ });
+ fireEvent.change(screen.getByLabelText("Remote MCP server URL"), {
+ target: { value: "https://broken.example.com/" },
+ });
+ fireEvent.submit(screen.getByRole("button", { name: /^add server$/i }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "No OAuth discovery.",
+ );
+ // Dialog stays open for a retry — the name field is still there.
+ expect(screen.getByLabelText("Name")).toBeInTheDocument();
+ expect(refresh).not.toHaveBeenCalled();
+ });
+});
diff --git a/notfair/src/components/browse-connectors-dialog.test.tsx b/notfair/src/components/browse-connectors-dialog.test.tsx
new file mode 100644
index 00000000..2f163d19
--- /dev/null
+++ b/notfair/src/components/browse-connectors-dialog.test.tsx
@@ -0,0 +1,121 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { BrowseConnectorsDialog } from "@/components/browse-connectors-dialog";
+import { TRUSTED_CONNECTORS } from "@/server/trusted-connectors";
+
+// Mock at the server-action boundary, per repo test conventions.
+const addServer = vi.hoisted(() => vi.fn());
+const startConnect = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/mcp", () => ({
+ addUserMcpServerAction: addServer,
+ startMcpConnect: startConnect,
+}));
+
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),
+}));
+
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: toastError },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+const ALL_IDS = TRUSTED_CONNECTORS.map((c) => c.id);
+
+describe("BrowseConnectorsDialog", () => {
+ it("lists every trusted connector that is not yet connected", () => {
+ render(<BrowseConnectorsDialog open onOpenChange={vi.fn()} />);
+ expect(screen.getByText("NotFair Google Ads")).toBeInTheDocument();
+ expect(screen.getByText("Stripe")).toBeInTheDocument();
+ });
+
+ it("hides connected connectors by key and by normalized resource URL", () => {
+ render(
+ <BrowseConnectorsDialog
+ open
+ onOpenChange={vi.fn()}
+ connectedKeys={["notfair-googleads"]}
+ // Trailing slash + uppercase host still match after normalization.
+ connectedResourceUrls={["https://mcp.stripe.com"]}
+ />,
+ );
+ expect(screen.queryByText("NotFair Google Ads")).toBeNull();
+ expect(screen.queryByText("Stripe")).toBeNull();
+ expect(screen.getByText("NotFair Meta Ads")).toBeInTheDocument();
+ });
+
+ it("shows an empty state when everything is already connected", () => {
+ render(
+ <BrowseConnectorsDialog
+ open
+ onOpenChange={vi.fn()}
+ hideKeys={ALL_IDS}
+ />,
+ );
+ expect(
+ screen.getByText("All available connectors are already connected."),
+ ).toBeInTheDocument();
+ });
+
+ it("adds with the canonical key and passes return_to into OAuth", async () => {
+ addServer.mockResolvedValue({ ok: true, key: "notfair-googleads" });
+ // Fail the connect step so the test never assigns window.location.href.
+ startConnect.mockResolvedValue({ ok: false, error: "issuer down" });
+ const onOpenChange = vi.fn();
+ render(<BrowseConnectorsDialog open onOpenChange={onOpenChange} />);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /NotFair Google Ads/ }),
+ );
+
+ await waitFor(() => {
+ expect(addServer).toHaveBeenCalledWith({
+ display_name: "NotFair Google Ads",
+ resource_url: "https://notfair.co/api/mcp/google_ads",
+ key: "notfair-googleads",
+ });
+ expect(startConnect).toHaveBeenCalledWith({
+ mcp_key: "notfair-googleads",
+ return_to: window.location.pathname + window.location.search,
+ });
+ });
+ });
+
+ it("closes and refreshes when add succeeds but OAuth cannot start", async () => {
+ addServer.mockResolvedValue({ ok: true, key: "notfair-googleads" });
+ startConnect.mockResolvedValue({ ok: false, error: "issuer down" });
+ const onOpenChange = vi.fn();
+ render(<BrowseConnectorsDialog open onOpenChange={onOpenChange} />);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: /NotFair Google Ads/ }),
+ );
+
+ await waitFor(() => {
+ expect(toastError).toHaveBeenCalledWith(
+ "Added NotFair Google Ads, but couldn't start OAuth: issuer down",
+ );
+ expect(refresh).toHaveBeenCalled();
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+
+ it("surfaces an add failure without starting OAuth", async () => {
+ addServer.mockResolvedValue({ ok: false, error: "probe failed" });
+ render(<BrowseConnectorsDialog open onOpenChange={vi.fn()} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /Stripe/ }));
+
+ await waitFor(() => {
+ expect(toastError).toHaveBeenCalledWith("probe failed");
+ });
+ expect(startConnect).not.toHaveBeenCalled();
+ });
+});
diff --git a/notfair/src/components/chat/live-working-indicator.test.tsx b/notfair/src/components/chat/live-working-indicator.test.tsx
new file mode 100644
index 00000000..8c10dc08
--- /dev/null
+++ b/notfair/src/components/chat/live-working-indicator.test.tsx
@@ -0,0 +1,123 @@
+// @vitest-environment jsdom
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { LiveWorkingIndicator } from "@/components/chat/live-working-indicator";
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
+
+const BASE = 1_800_000_000_000;
+
+const call = (id: string, ts: number, tcid: string): TranscriptEvent => ({
+ kind: "tool_call",
+ id,
+ ts,
+ tool_call_id: tcid,
+ name: "shell",
+ label: "pnpm test",
+});
+const lifecycle = (id: string, ts: number, phase: string): TranscriptEvent => ({
+ kind: "lifecycle",
+ id,
+ ts,
+ phase,
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(BASE);
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("LiveWorkingIndicator", () => {
+ it("shows the in-flight committed tool and ticks the elapsed clock", () => {
+ render(
+ <LiveWorkingIndicator
+ agentDisplayName="Growth agent"
+ events={[call("c1", BASE - 5_000, "t1")]}
+ turnStartedAt={BASE - 10_000}
+ />,
+ );
+ // Elapsed anchors on the later of turn start and last event ts.
+ // "Ran tests" shows as both the headline and the trajectory chip label.
+ expect(screen.getAllByText("Ran tests").length).toBeGreaterThan(0);
+ expect(screen.getByText("0:05")).toBeInTheDocument();
+ act(() => {
+ vi.advanceTimersByTime(2_000);
+ });
+ expect(screen.getByText("0:07")).toBeInTheDocument();
+ });
+
+ it("freezes into the completed state when the turn's done event lands", () => {
+ render(
+ <LiveWorkingIndicator
+ agentDisplayName="Growth agent"
+ events={[lifecycle("l1", BASE - 1_000, "done")]}
+ turnStartedAt={BASE - 5_000}
+ />,
+ );
+ const status = screen.getByRole("status", {
+ name: "Growth agent Turn complete",
+ });
+ expect(status).toHaveAttribute("data-run-state", "complete");
+ // Ended: no elapsed timer rendered or ticking.
+ expect(status.querySelector(".tabular-nums")).toBeNull();
+ });
+
+ it("ignores a done event from before the current turn", () => {
+ render(
+ <LiveWorkingIndicator
+ agentDisplayName="Growth agent"
+ events={[
+ lifecycle("l1", BASE - 60_000, "done"),
+ call("c1", BASE - 2_000, "t1"),
+ ]}
+ turnStartedAt={BASE - 5_000}
+ />,
+ );
+ expect(
+ screen.getByRole("status", { name: "Growth agent Ran tests" }),
+ ).toHaveAttribute("data-run-state", "running");
+ });
+
+ it("stays visibly running while pending SSE work outlives the done event", () => {
+ render(
+ <LiveWorkingIndicator
+ agentDisplayName="Growth agent"
+ events={[lifecycle("l1", BASE - 1_000, "done")]}
+ turnStartedAt={BASE - 5_000}
+ pendingTools={[
+ {
+ toolCallId: "t9",
+ name: "mcp__X__runScript",
+ label: null,
+ result: null,
+ ok: true,
+ done: false,
+ },
+ ]}
+ />,
+ );
+ expect(
+ screen.getByRole("status", { name: "Growth agent Ran script" }),
+ ).toHaveAttribute("data-run-state", "running");
+ });
+
+ it("surfaces the lifecycle phase during the pre-token wait", () => {
+ render(
+ <LiveWorkingIndicator
+ agentDisplayName="Growth agent"
+ events={[]}
+ turnStartedAt={BASE - 3_000}
+ lifecyclePhase="run.warming"
+ hasPendingAssistant={false}
+ />,
+ );
+ expect(
+ screen.getByRole("status", { name: "Growth agent Warming up" }),
+ ).toBeInTheDocument();
+ // No events at all → elapsed anchors on turnStartedAt.
+ expect(screen.getByText("0:03")).toBeInTheDocument();
+ });
+});
diff --git a/notfair/src/components/chat/tool-intent.test.ts b/notfair/src/components/chat/tool-intent.test.ts
new file mode 100644
index 00000000..e82feffc
--- /dev/null
+++ b/notfair/src/components/chat/tool-intent.test.ts
@@ -0,0 +1,275 @@
+import { Edit3, FileText, Globe, Terminal, Wrench } from "lucide-react";
+import { describe, expect, it } from "vitest";
+
+import {
+ formatToolName,
+ humanizeShellCommand,
+ humanizeTool,
+ iconForTool,
+ looksLikeShellInvocation,
+ matchMcpServerKey,
+ shortenPathish,
+} from "./tool-intent";
+
+describe("formatToolName", () => {
+ it("keeps only the action after nested namespace separators", () => {
+ expect(formatToolName("mcp__NotFair-GoogleAds__createCampaign")).toBe(
+ "createCampaign",
+ );
+ expect(formatToolName("notfair_demo__notfair_goals.propose_target")).toBe(
+ "propose_target",
+ );
+ expect(formatToolName("runScript")).toBe("runScript");
+ expect(formatToolName("")).toBe("");
+ });
+});
+
+describe("looksLikeShellInvocation", () => {
+ it("recognizes wrapper prefixes, binary paths, and metacharacters", () => {
+ expect(looksLikeShellInvocation('bash -lc "ls -la"')).toBe(true);
+ expect(looksLikeShellInvocation("/usr/bin/find . -name x")).toBe(true);
+ expect(looksLikeShellInvocation("cat a.txt | grep foo")).toBe(true);
+ });
+
+ it("leaves tool identifiers and short tokens alone", () => {
+ expect(looksLikeShellInvocation("runScript")).toBe(false);
+ expect(looksLikeShellInvocation("ls")).toBe(false);
+ expect(looksLikeShellInvocation("")).toBe(false);
+ });
+});
+
+describe("humanizeShellCommand", () => {
+ it("unwraps the bash -lc wrapper before mapping the verb", () => {
+ expect(humanizeShellCommand(`/bin/zsh -lc 'git status --short'`)).toEqual({
+ verb: "Ran git status",
+ });
+ });
+
+ it("maps common leading binaries to verb phrases", () => {
+ expect(humanizeShellCommand("pwd")).toEqual({ verb: "Checked working directory" });
+ expect(humanizeShellCommand("ls src/lib")).toEqual({
+ verb: "Listed files",
+ target: "src/lib",
+ });
+ expect(humanizeShellCommand("find . -name '*.ts'")).toMatchObject({
+ verb: "Searched the filesystem",
+ });
+ expect(humanizeShellCommand(`rg -n "needle" src`)).toEqual({
+ verb: "Searched files",
+ target: `"needle"`,
+ });
+ expect(humanizeShellCommand("cat package.json")).toEqual({
+ verb: "Read file",
+ target: "package.json",
+ });
+ expect(humanizeShellCommand("git")).toMatchObject({ verb: "Ran git" });
+ });
+
+ it("understands package-manager subcommands", () => {
+ expect(humanizeShellCommand("pnpm test")).toEqual({ verb: "Ran tests" });
+ expect(humanizeShellCommand("npm install left-pad")).toEqual({
+ verb: "Installed packages",
+ });
+ expect(humanizeShellCommand("pnpm run build")).toEqual({ verb: "Ran pnpm build" });
+ expect(humanizeShellCommand("pnpm run")).toEqual({ verb: "Ran pnpm" });
+ expect(humanizeShellCommand("yarn why react")).toEqual({ verb: "Ran yarn why" });
+ expect(humanizeShellCommand("bun")).toEqual({ verb: "Ran bun" });
+ });
+
+ it("covers scripts, network fetches, and file mutations", () => {
+ expect(humanizeShellCommand("node scripts/seed.ts")).toEqual({
+ verb: "Ran script",
+ target: "scripts/seed.ts",
+ });
+ expect(humanizeShellCommand("curl -s https://example.com/api")).toEqual({
+ verb: "Fetched URL",
+ target: "https://example.com/api",
+ });
+ expect(humanizeShellCommand("mkdir -p out/dir")).toEqual({
+ verb: "Created directory",
+ target: "out/dir",
+ });
+ expect(humanizeShellCommand("touch a.txt")).toEqual({
+ verb: "Created file",
+ target: "a.txt",
+ });
+ expect(humanizeShellCommand("rm -rf build")).toEqual({
+ verb: "Removed file(s)",
+ target: "build",
+ });
+ expect(humanizeShellCommand("mv a b")).toEqual({ verb: "Moved file" });
+ expect(humanizeShellCommand("cp a b")).toEqual({ verb: "Copied file" });
+ expect(humanizeShellCommand("sed -i '' 's/a/b/' file.txt")).toMatchObject({
+ verb: "Edited text",
+ });
+ expect(humanizeShellCommand("which node")).toEqual({
+ verb: "Located binary",
+ target: "node",
+ });
+ expect(humanizeShellCommand("echo hi")).toEqual({ verb: "Printed text" });
+ expect(humanizeShellCommand("make build")).toEqual({ verb: "Ran make build" });
+ expect(humanizeShellCommand("make")).toEqual({ verb: "Ran make" });
+ expect(humanizeShellCommand("docker ps")).toEqual({ verb: "Ran docker ps" });
+ expect(humanizeShellCommand("kubectl get pods")).toEqual({
+ verb: "Ran kubectl get",
+ });
+ expect(humanizeShellCommand("gh pr list")).toEqual({ verb: "Ran gh pr" });
+ });
+
+ it("only reads the leading command of a pipeline", () => {
+ expect(humanizeShellCommand("cat log.txt | tail -20")).toEqual({
+ verb: "Read file",
+ target: "log.txt",
+ });
+ });
+
+ it("falls back to Ran <bin> with a truncated first line", () => {
+ const long = `weirdtool ${"x".repeat(100)}`;
+ const intent = humanizeShellCommand(long);
+ expect(intent.verb).toBe("Ran weirdtool");
+ expect(intent.target!.length).toBe(80);
+ expect(intent.target!.endsWith("…")).toBe(true);
+ });
+
+ it("handles an empty command", () => {
+ expect(humanizeShellCommand("")).toEqual({ verb: "Ran shell command" });
+ });
+});
+
+describe("humanizeTool", () => {
+ it("routes shell-flavored names through the shell humanizer", () => {
+ expect(humanizeTool("Bash", "git diff --stat")).toEqual({ verb: "Ran git diff" });
+ // Legacy rows: the command line stored as the NAME, label empty.
+ expect(humanizeTool(`bash -lc "ls src"`, null)).toEqual({
+ verb: "Listed files",
+ target: "src",
+ });
+ });
+
+ it("maps the built-in coding tools with pathish targets", () => {
+ expect(humanizeTool("Read", "/Users/x/repo/src/lib/slug.ts")).toEqual({
+ verb: "Read file",
+ target: "…/lib/slug.ts",
+ });
+ expect(humanizeTool("write", "notes.md")).toEqual({
+ verb: "Wrote file",
+ target: "notes.md",
+ });
+ expect(humanizeTool("edit", null)).toEqual({ verb: "Edited file", target: undefined });
+ expect(humanizeTool("patch", "a/b/c/d.ts")).toEqual({
+ verb: "Edited file",
+ target: "…/c/d.ts",
+ });
+ expect(humanizeTool("webfetch", "https://example.com")).toEqual({
+ verb: "Fetched URL",
+ target: "https://example.com",
+ });
+ expect(humanizeTool("websearch", "notfair pricing")).toEqual({
+ verb: "Searched the web",
+ target: "notfair pricing",
+ });
+ });
+
+ it("speaks MCP verb-first action names in natural language", () => {
+ expect(humanizeTool("mcp__X__getInsights", null).verb).toBe("Fetched insights");
+ expect(humanizeTool("mcp__X__searchGeoTargets", null).verb).toBe(
+ "Searched geo targets",
+ );
+ expect(humanizeTool("mcp__X__addKeyword", null).verb).toBe("Created keyword");
+ expect(humanizeTool("mcp__X__deleteThing", null).verb).toBe("Removed thing");
+ expect(humanizeTool("mcp__X__enableCampaign", null).verb).toBe("Enabled campaign");
+ expect(humanizeTool("mcp__X__pauseAdGroup", null).verb).toBe("Paused ad group");
+ expect(humanizeTool("mcp__X__resumeAd", null).verb).toBe("Resumed ad");
+ expect(humanizeTool("mcp__X__renameCampaign", null).verb).toBe("Renamed campaign");
+ expect(humanizeTool("mcp__X__proposeTarget", null).verb).toBe("Proposed target");
+ expect(humanizeTool("mcp__X__logLearning", null).verb).toBe("Logged learning");
+ expect(humanizeTool("mcp__X__reviewChangeImpact", null).verb).toBe(
+ "Reviewed change impact",
+ );
+ expect(humanizeTool("mcp__X__registerMetric", null).verb).toBe("Registered metric");
+ expect(humanizeTool("mcp__X__backfillHistory", null).verb).toBe(
+ "Backfilled history",
+ );
+ expect(humanizeTool("mcp__X__verifyDefinition", null).verb).toBe(
+ "Verified definition",
+ );
+ expect(humanizeTool("mcp__X__uploadClickConversions", null).verb).toBe(
+ "Uploaded click conversions",
+ );
+ expect(humanizeTool("mcp__X__sendReport", null).verb).toBe("Sent report");
+ expect(humanizeTool("mcp__X__list", null).verb).toBe("Listed records");
+ expect(humanizeTool("mcp__X__get", null).verb).toBe("Fetched data");
+ expect(humanizeTool("mcp__X__create", null).verb).toBe("Created a record");
+ expect(humanizeTool("mcp__X__set", null).verb).toBe("Updated a record");
+ });
+
+ it("detects SQL-looking labels for exec-style tools", () => {
+ expect(humanizeTool("mcp__X__exec", "SELECT 1")).toEqual({
+ verb: "Ran a query",
+ target: "SELECT 1",
+ });
+ // exec with a non-SQL label reads as a generic command.
+ expect(humanizeTool("mcp__X__execute", "do the thing")).toEqual({
+ verb: "Ran a command",
+ target: "do the thing",
+ });
+ expect(humanizeTool("mcp__X__runScript", null).verb).toBe("Ran script");
+ });
+
+ it("falls back to Called <action> for unknown verbs", () => {
+ expect(humanizeTool("mcp__X__frobnicateWidget", null).verb).toBe(
+ "Called frobnicate widget",
+ );
+ });
+});
+
+describe("shortenPathish", () => {
+ it("keeps short paths and URLs intact, compresses deep paths", () => {
+ expect(shortenPathish("a/b")).toBe("a/b");
+ expect(shortenPathish("https://example.com/a/b/c")).toBe(
+ "https://example.com/a/b/c",
+ );
+ expect(shortenPathish("/very/deep/nested/file.ts")).toBe("…/nested/file.ts");
+ expect(shortenPathish("")).toBe("");
+ });
+});
+
+describe("matchMcpServerKey", () => {
+ const catalog = [
+ {
+ key: "NotFair-GoogleAds",
+ display_name: "Google Ads",
+ resource_url: "https://notfair.co",
+ },
+ ];
+
+ it("matches the Codex dotted shape with a namespaced server key", () => {
+ expect(
+ matchMcpServerKey("notfair_demo__notfair_googleads.runScript", catalog)
+ ?.display_name,
+ ).toBe("Google Ads");
+ // Bare dotted server key too.
+ expect(
+ matchMcpServerKey("notfair-googleads.runScript", catalog)?.display_name,
+ ).toBe("Google Ads");
+ });
+
+ it("returns null without a recognizable prefix or catalog", () => {
+ expect(matchMcpServerKey("mcp__Unknown__tool", catalog)).toBeNull();
+ expect(matchMcpServerKey("plainTool", catalog)).toBeNull();
+ expect(matchMcpServerKey("", catalog)).toBeNull();
+ expect(matchMcpServerKey("mcp__NotFair-GoogleAds__x", [])).toBeNull();
+ expect(matchMcpServerKey("mcp__NotFair-GoogleAds__x", undefined)).toBeNull();
+ });
+});
+
+describe("iconForTool", () => {
+ it("picks the icon family by tool name", () => {
+ expect(iconForTool("shell")).toBe(Terminal);
+ expect(iconForTool("Bash")).toBe(Terminal);
+ expect(iconForTool("read")).toBe(FileText);
+ expect(iconForTool("edit")).toBe(Edit3);
+ expect(iconForTool("webfetch")).toBe(Globe);
+ expect(iconForTool("runScript")).toBe(Wrench);
+ });
+});
diff --git a/notfair/src/components/chat/transcript-model.more.test.ts b/notfair/src/components/chat/transcript-model.more.test.ts
new file mode 100644
index 00000000..378609a6
--- /dev/null
+++ b/notfair/src/components/chat/transcript-model.more.test.ts
@@ -0,0 +1,221 @@
+import { describe, expect, it, vi } from "vitest";
+
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
+import {
+ collapseEvents,
+ eventSignature,
+ handleSseEvent,
+ upsertToolEntry,
+ type SseToolEvent,
+} from "./transcript-model";
+
+const t = 1_800_000_000_000;
+
+function handlers() {
+ return {
+ onText: vi.fn(),
+ onTool: vi.fn(),
+ onError: vi.fn(),
+ onLifecycle: vi.fn(),
+ onMeta: vi.fn(),
+ onPerf: vi.fn(),
+ };
+}
+
+const frame = (evt: string, data: unknown) =>
+ `event: ${evt}\ndata: ${JSON.stringify(data)}`;
+
+describe("handleSseEvent", () => {
+ it("dispatches text chunks", () => {
+ const h = handlers();
+ handleSseEvent(frame("text", { chunk: "Hello" }), h);
+ expect(h.onText).toHaveBeenCalledWith("Hello");
+ });
+
+ it("ignores text frames without a string chunk", () => {
+ const h = handlers();
+ handleSseEvent(frame("text", { chunk: 42 }), h);
+ expect(h.onText).not.toHaveBeenCalled();
+ });
+
+ it("dispatches tool events verbatim", () => {
+ const h = handlers();
+ const evt: SseToolEvent = {
+ phase: "start",
+ tool_call_id: "t1",
+ name: "shell",
+ label: "ls",
+ };
+ handleSseEvent(frame("tool", evt), h);
+ expect(h.onTool).toHaveBeenCalledWith(evt);
+ });
+
+ it("dispatches lifecycle phases only when a handler is wired", () => {
+ const h = handlers();
+ handleSseEvent(frame("lifecycle", { phase: "run.warming" }), h);
+ expect(h.onLifecycle).toHaveBeenCalledWith("run.warming");
+ // Non-string phase is dropped.
+ handleSseEvent(frame("lifecycle", { phase: 3 }), h);
+ expect(h.onLifecycle).toHaveBeenCalledTimes(1);
+ // No handler — must not throw.
+ expect(() =>
+ handleSseEvent(frame("lifecycle", { phase: "x" }), {
+ onText: vi.fn(),
+ onTool: vi.fn(),
+ onError: vi.fn(),
+ }),
+ ).not.toThrow();
+ });
+
+ it("dispatches meta and perf frames", () => {
+ const h = handlers();
+ handleSseEvent(frame("meta", { agent: "a1", message_chars: 5 }), h);
+ expect(h.onMeta).toHaveBeenCalledWith({ agent: "a1", message_chars: 5 });
+ const marks = [{ name: "first_token", at: 12.4, delta: 12.4 }];
+ handleSseEvent(frame("perf", { marks }), h);
+ expect(h.onPerf).toHaveBeenCalledWith(marks);
+ // Non-array marks are dropped.
+ handleSseEvent(frame("perf", { marks: "nope" }), h);
+ expect(h.onPerf).toHaveBeenCalledTimes(1);
+ });
+
+ it("dispatches errors with a fallback message", () => {
+ const h = handlers();
+ handleSseEvent(frame("error", { message: "boom" }), h);
+ expect(h.onError).toHaveBeenCalledWith("boom");
+ handleSseEvent(frame("error", {}), h);
+ expect(h.onError).toHaveBeenCalledWith("unknown error");
+ });
+
+ it("ignores malformed frames", () => {
+ const h = handlers();
+ handleSseEvent("data: {}", h); // no event line
+ handleSseEvent("event: text", h); // no data line
+ handleSseEvent("event: text\ndata: {not json", h); // bad JSON
+ handleSseEvent(frame("mystery", { x: 1 }), h); // unknown event type
+ expect(h.onText).not.toHaveBeenCalled();
+ expect(h.onTool).not.toHaveBeenCalled();
+ expect(h.onError).not.toHaveBeenCalled();
+ });
+});
+
+describe("upsertToolEntry (top-up)", () => {
+ it("inserts a result-phase event for an unseen tool as already done", () => {
+ const entries = upsertToolEntry([], {
+ phase: "result",
+ tool_call_id: "t1",
+ name: "shell",
+ });
+ expect(entries[0]).toMatchObject({ toolCallId: "t1", done: true, label: null });
+ });
+
+ it("keeps the existing label when an update omits it", () => {
+ let entries = upsertToolEntry([], {
+ phase: "start",
+ tool_call_id: "t1",
+ name: "shell",
+ label: "ls -la",
+ });
+ entries = upsertToolEntry(entries, {
+ phase: "update",
+ tool_call_id: "t1",
+ name: "shell",
+ });
+ expect(entries[0]).toMatchObject({ label: "ls -la", done: false });
+ });
+});
+
+describe("collapseEvents (top-up)", () => {
+ const user = (id: string, body: string, system?: boolean): TranscriptEvent => ({
+ kind: "user_message",
+ id,
+ ts: t,
+ body,
+ ...(system ? { system } : {}),
+ });
+
+ it("carries the system flag through to the rendered user message", () => {
+ const items = collapseEvents([user("u1", "[TICK] go", true)]);
+ expect(items[0]).toMatchObject({
+ kind: "user_message",
+ body: "[TICK] go",
+ system: true,
+ });
+ });
+
+ it("renders unknown events as system_unknown rows", () => {
+ const items = collapseEvents([
+ { kind: "unknown", id: "x1", ts: t, raw_type: "telemetry" },
+ ]);
+ expect(items).toEqual([
+ { kind: "system_unknown", key: "x1", raw_type: "telemetry" },
+ ]);
+ });
+
+ it("skips lifecycle events entirely", () => {
+ const items = collapseEvents([
+ { kind: "lifecycle", id: "l1", ts: t, phase: "start" },
+ { kind: "lifecycle", id: "l2", ts: t, phase: "done" },
+ ]);
+ expect(items).toEqual([]);
+ });
+
+ it("completes an earlier call even when the result arrives after a message", () => {
+ const items = collapseEvents([
+ {
+ kind: "tool_call",
+ id: "c1",
+ ts: t,
+ tool_call_id: "t1",
+ name: "shell",
+ label: "ls",
+ },
+ { kind: "assistant_text", id: "a1", ts: t, body: "narrating" },
+ {
+ kind: "tool_result",
+ id: "r1",
+ ts: t,
+ tool_call_id: "t1",
+ name: "shell",
+ summary: "3 files",
+ ok: true,
+ },
+ ]);
+ expect(items.map((i) => i.kind)).toEqual(["tool_group", "assistant_text"]);
+ const group = items[0] as Extract<
+ ReturnType<typeof collapseEvents>[number],
+ { kind: "tool_group" }
+ >;
+ expect(group.tools[0]).toMatchObject({
+ toolCallId: "t1",
+ done: true,
+ ok: true,
+ result: "3 files",
+ });
+ });
+});
+
+describe("eventSignature (top-up)", () => {
+ it("keys lifecycle/unknown events by kind and id", () => {
+ expect(
+ eventSignature({ kind: "lifecycle", id: "l1", ts: t, phase: "start" }),
+ ).toBe("lifecycle|l1");
+ expect(
+ eventSignature({ kind: "unknown", id: "u9", ts: t, raw_type: "x" }),
+ ).toBe("unknown|u9");
+ });
+
+ it("keys tool_results by call id so shadow and DB copies collide", () => {
+ expect(
+ eventSignature({
+ kind: "tool_result",
+ id: "shadow-1",
+ ts: t,
+ tool_call_id: "t1",
+ name: "shell",
+ summary: null,
+ ok: true,
+ }),
+ ).toBe("tool_result|t1");
+ });
+});
diff --git a/notfair/src/components/chat/working-view.test.ts b/notfair/src/components/chat/working-view.test.ts
new file mode 100644
index 00000000..596af3c9
--- /dev/null
+++ b/notfair/src/components/chat/working-view.test.ts
@@ -0,0 +1,246 @@
+import { describe, expect, it } from "vitest";
+
+import type { TranscriptEvent } from "@/server/sessions/transcript-tail";
+import type { ToolEntry } from "./transcript-model";
+import {
+ WRAPPING_STALE_MS,
+ buildPhases,
+ deriveWorkingView,
+ humanLifecyclePhase,
+} from "./working-view";
+
+const NOW = 1_800_000_000_000;
+
+const text = (id: string, ts: number, body = "hello"): TranscriptEvent => ({
+ kind: "assistant_text",
+ id,
+ ts,
+ body,
+});
+const userMsg = (id: string, ts: number): TranscriptEvent => ({
+ kind: "user_message",
+ id,
+ ts,
+ body: "hi",
+});
+const call = (
+ id: string,
+ ts: number,
+ tcid: string,
+ name = "shell",
+ label: string | null = "ls src",
+): TranscriptEvent => ({ kind: "tool_call", id, ts, tool_call_id: tcid, name, label });
+const result = (
+ id: string,
+ ts: number,
+ tcid: string,
+ ok = true,
+ name = "shell",
+): TranscriptEvent => ({
+ kind: "tool_result",
+ id,
+ ts,
+ tool_call_id: tcid,
+ name,
+ summary: null,
+ ok,
+});
+const lifecycle = (id: string, ts: number, phase: string): TranscriptEvent => ({
+ kind: "lifecycle",
+ id,
+ ts,
+ phase,
+});
+
+const pendingTool = (over: Partial<ToolEntry> = {}): ToolEntry => ({
+ toolCallId: "p1",
+ name: "mcp__X__runScript",
+ label: null,
+ result: null,
+ ok: true,
+ done: false,
+ ...over,
+});
+
+function derive(over: Partial<Parameters<typeof deriveWorkingView>[0]> = {}) {
+ return deriveWorkingView({
+ agentDisplayName: "Agent",
+ events: [],
+ lifecyclePhase: null,
+ pendingTools: [],
+ hasPendingAssistant: false,
+ turnStartedAt: null,
+ now: NOW,
+ ...over,
+ });
+}
+
+describe("deriveWorkingView", () => {
+ it("reports Turn complete once the lifecycle done event lands", () => {
+ const view = derive({ events: [lifecycle("l1", NOW - 1000, "done")] });
+ expect(view).toMatchObject({ headline: "Turn complete", mood: "ended" });
+ });
+
+ it("keeps working while a pending tool is still in flight past done", () => {
+ const view = derive({
+ events: [lifecycle("l1", NOW - 1000, "done")],
+ pendingTools: [pendingTool()],
+ });
+ expect(view.mood).toBe("tool");
+ });
+
+ it("puts an in-flight SSE tool front and center", () => {
+ const view = derive({
+ pendingTools: [pendingTool({ name: "shell", label: "git status" })],
+ });
+ expect(view).toMatchObject({ headline: "Ran git status", mood: "tool" });
+ });
+
+ it("shows Writing the response while assistant text streams, with last tool subtitle", () => {
+ const view = derive({
+ hasPendingAssistant: true,
+ pendingTools: [pendingTool({ done: true, ok: true, label: "pnpm test", name: "shell" })],
+ });
+ expect(view.headline).toBe("Writing the response");
+ expect(view.mood).toBe("writing");
+ expect(view.subtitle).toBe("Ran tests ✓");
+ });
+
+ it("bridges the between-tools gap as Thinking with the last outcome", () => {
+ const ok = derive({
+ pendingTools: [pendingTool({ done: true, ok: true, name: "mcp__X__runScript" })],
+ });
+ expect(ok).toMatchObject({ headline: "Thinking", mood: "waiting" });
+ expect(ok.subtitle).toBe("Ran script ✓ — picking next step");
+
+ const failed = derive({
+ pendingTools: [pendingTool({ done: true, ok: false, name: "mcp__X__runScript" })],
+ });
+ expect(failed.subtitle).toBe("Ran script failed — picking next step");
+ });
+
+ it("promotes the lifecycle phase to the headline before any events", () => {
+ expect(derive({}).headline).toBe("Starting");
+ expect(derive({ lifecyclePhase: "run.start" }).headline).toBe(
+ "Calling the model",
+ );
+ expect(
+ derive({ events: [userMsg("u1", NOW - 500)], lifecyclePhase: "run.warming" })
+ .headline,
+ ).toBe("Warming up");
+ });
+
+ it("treats a committed unanswered tool_call as the active phase", () => {
+ const view = derive({
+ events: [userMsg("u1", NOW - 3000), call("c1", NOW - 1000, "t1")],
+ });
+ expect(view).toMatchObject({ headline: "Listed files", mood: "tool" });
+ expect(view.subtitle).toBe("src");
+ });
+
+ it("does not treat an answered tool_call as in flight", () => {
+ // result precedes the call in the log (out-of-order write) — the call is
+ // still the last event but it already has its result.
+ const view = derive({
+ events: [result("r1", NOW - 2000, "t1"), call("c1", NOW - 1000, "t1")],
+ });
+ expect(view.mood).not.toBe("tool");
+ });
+
+ it("shows Thinking after a committed tool_result", () => {
+ const ok = derive({
+ events: [call("c1", NOW - 2000, "t1"), result("r1", NOW - 1000, "t1", true)],
+ });
+ expect(ok.headline).toBe("Thinking");
+ expect(ok.subtitle).toBe("Ran shell ✓ — picking next step");
+
+ const failed = derive({
+ events: [call("c1", NOW - 2000, "t1"), result("r1", NOW - 1000, "t1", false)],
+ });
+ expect(failed.subtitle).toBe("Ran shell failed — retrying");
+ });
+
+ it("wraps up on a fresh trailing assistant message", () => {
+ const view = derive({
+ events: [
+ call("c1", NOW - 5000, "t1"),
+ result("r1", NOW - 4000, "t1"),
+ text("a1", NOW - 1000),
+ ],
+ });
+ expect(view).toMatchObject({ headline: "Wrapping up", mood: "wrapping" });
+ // Subtitle falls back to the committed tool result.
+ expect(view.subtitle).toBe("Ran shell ✓");
+ });
+
+ it("goes honest once the trailing message is stale", () => {
+ const view = derive({
+ events: [text("a1", NOW - WRAPPING_STALE_MS - 5_000)],
+ });
+ expect(view.headline).toBe("Still working");
+ expect(view.subtitle).toContain("quiet for 35s");
+
+ const minutes = derive({ events: [text("a1", NOW - 240_000)] });
+ expect(minutes.subtitle).toContain("quiet for 4m");
+ });
+
+ it("scopes events to the current turn via turnStartedAt", () => {
+ const view = derive({
+ // Old turn had a tool; the new turn hasn't produced events yet.
+ events: [call("c1", NOW - 100_000, "t1"), result("r1", NOW - 99_000, "t1")],
+ turnStartedAt: NOW - 1_000,
+ });
+ expect(view.headline).toBe("Starting");
+ expect(view.phases).toHaveLength(0);
+ });
+});
+
+describe("buildPhases", () => {
+ it("orders committed tools first and appends unseen pending tools", () => {
+ const phases = buildPhases(
+ [call("c1", NOW - 3000, "t1", "shell", "git status"), result("r1", NOW - 2000, "t1", true)],
+ [
+ pendingTool({ toolCallId: "t1" }), // already committed — skipped
+ pendingTool({ toolCallId: "t2", name: "mcp__X__runScript", label: "audit" }),
+ ],
+ );
+ expect(phases).toHaveLength(2);
+ expect(phases[0]).toMatchObject({ id: "t1", label: "Ran git status", state: "done" });
+ expect(phases[1]).toMatchObject({
+ id: "t2",
+ label: "Ran script",
+ state: "active",
+ detail: "audit",
+ });
+ });
+
+ it("keeps an orphan committed result as a done phase and marks failures", () => {
+ const phases = buildPhases([result("r1", NOW, "t9", false, "shell")], []);
+ expect(phases).toEqual([
+ { id: "t9", label: "Ran shell", state: "failed" },
+ ]);
+ });
+
+ it("demotes every active phase except the last", () => {
+ const phases = buildPhases(
+ [],
+ [
+ pendingTool({ toolCallId: "t1", done: false }),
+ pendingTool({ toolCallId: "t2", done: false }),
+ ],
+ );
+ expect(phases.map((p) => p.state)).toEqual(["done", "active"]);
+ });
+});
+
+describe("humanLifecyclePhase", () => {
+ it("maps known phases and falls back generically", () => {
+ expect(humanLifecyclePhase("run.warming")).toBe("Warming up");
+ expect(humanLifecyclePhase("context.compact")).toBe("Compacting context");
+ expect(humanLifecyclePhase("start")).toBe("Calling the model");
+ expect(humanLifecyclePhase("turn.start")).toBe("Calling the model");
+ expect(humanLifecyclePhase("run.end")).toBe("Finishing up");
+ expect(humanLifecyclePhase("turn.complete")).toBe("Finishing up");
+ expect(humanLifecyclePhase("v2.mystery")).toBe("Starting up");
+ });
+});
diff --git a/notfair/src/components/markdown.test.tsx b/notfair/src/components/markdown.test.tsx
new file mode 100644
index 00000000..437701bd
--- /dev/null
+++ b/notfair/src/components/markdown.test.tsx
@@ -0,0 +1,73 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+
+import { Markdown } from "@/components/markdown";
+
+describe("Markdown", () => {
+ it("renders headings, lists, and emphasis", () => {
+ render(
+ <Markdown>
+ {"# Title\n## Section\n### Sub\n#### Deep\n\n- one\n- two\n\n1. first\n2. second\n\n**bold** and *italic*"}
+ </Markdown>,
+ );
+ expect(screen.getByRole("heading", { level: 1, name: "Title" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 2, name: "Section" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 3, name: "Sub" })).toBeInTheDocument();
+ expect(screen.getByRole("heading", { level: 4, name: "Deep" })).toBeInTheDocument();
+ expect(screen.getAllByRole("list")).toHaveLength(2);
+ expect(screen.getAllByRole("listitem")).toHaveLength(4);
+ expect(screen.getByText("bold").tagName).toBe("STRONG");
+ expect(screen.getByText("italic").tagName).toBe("EM");
+ });
+
+ it("opens links in a new tab with safe rel", () => {
+ render(<Markdown>{"[NotFair](https://notfair.co)"}</Markdown>);
+ const link = screen.getByRole("link", { name: "NotFair" });
+ expect(link).toHaveAttribute("href", "https://notfair.co");
+ expect(link).toHaveAttribute("target", "_blank");
+ expect(link).toHaveAttribute("rel", "noopener noreferrer");
+ });
+
+ it("distinguishes inline code from fenced blocks", () => {
+ const { container } = render(
+ <Markdown>{"Use `pnpm test` here.\n\n```json\n{\"ok\":true}\n```"}</Markdown>,
+ );
+ const inline = screen.getByText("pnpm test");
+ expect(inline.tagName).toBe("CODE");
+ expect(inline.className).toContain("bg-muted");
+
+ const pre = container.querySelector("pre");
+ expect(pre).not.toBeNull();
+ const fenced = pre!.querySelector("code")!;
+ expect(fenced.className).toContain("language-json");
+ expect(fenced.textContent).toContain('{"ok":true}');
+ });
+
+ it("renders GFM tables inside a horizontal scroll container", () => {
+ const { container } = render(
+ <Markdown>{"| Col A | Col B |\n| --- | --- |\n| a1 | b1 |"}</Markdown>,
+ );
+ expect(screen.getByRole("table")).toBeInTheDocument();
+ expect(screen.getByRole("columnheader", { name: "Col A" })).toBeInTheDocument();
+ expect(screen.getByRole("cell", { name: "b1" })).toBeInTheDocument();
+ expect(container.querySelector(".overflow-x-auto table")).not.toBeNull();
+ });
+
+ it("renders blockquotes and horizontal rules", () => {
+ const { container } = render(
+ <Markdown>{"> quoted advice\n\n---\n\nafter the rule"}</Markdown>,
+ );
+ expect(container.querySelector("blockquote")).toHaveTextContent(
+ "quoted advice",
+ );
+ expect(container.querySelector("hr")).not.toBeNull();
+ expect(screen.getByText("after the rule")).toBeInTheDocument();
+ });
+
+ it("does not render raw HTML", () => {
+ render(<Markdown>{'<script>alert("x")</script> plain text'}</Markdown>);
+ expect(document.querySelector("script")).toBeNull();
+ expect(screen.getByText(/plain text/)).toBeInTheDocument();
+ });
+});
diff --git a/notfair/src/components/mcp-card.more.test.tsx b/notfair/src/components/mcp-card.more.test.tsx
new file mode 100644
index 00000000..04d0845a
--- /dev/null
+++ b/notfair/src/components/mcp-card.more.test.tsx
@@ -0,0 +1,216 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { McpCard } from "@/components/mcp-card";
+import type { McpSpec } from "@/server/mcp-catalog";
+import type { McpRuntimeStatus } from "@/server/mcp/state";
+
+// Mock at the server-action boundary, per repo test conventions.
+const startConnect = vi.hoisted(() => vi.fn());
+const disconnect = vi.hoisted(() => vi.fn());
+const listTools = vi.hoisted(() => vi.fn());
+const removeServer = vi.hoisted(() => vi.fn());
+vi.mock("@/server/actions/mcp", () => ({
+ startMcpConnect: startConnect,
+ disconnectMcpAction: disconnect,
+ listMcpToolsAction: listTools,
+ removeUserMcpServerAction: removeServer,
+}));
+vi.mock("@/server/onboarding/accounts", () => ({
+ listGoogleAdsAccounts: vi.fn(),
+ setOnboardingAccountAction: vi.fn(),
+ listMetaAdsAccounts: vi.fn(),
+ setOnboardingMetaAdsAccountAction: vi.fn(),
+ listGscProperties: vi.fn(),
+ setOnboardingGscPropertyAction: vi.fn(),
+}));
+
+const refresh = vi.hoisted(() => vi.fn());
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),
+}));
+
+const toastSuccess = vi.hoisted(() => vi.fn());
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({
+ toast: { success: toastSuccess, error: toastError },
+}));
+
+const xadsSpec: McpSpec = {
+ key: "notfair-xads",
+ display_name: "NotFair X Ads",
+ description: "X Ads campaigns.",
+ resource_url: "https://notfair.co/api/mcp/x_ads",
+ discovery_url:
+ "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/x_ads",
+ source: "preset",
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+function openOverflowMenu() {
+ fireEvent.keyDown(screen.getByRole("button", { name: /More options/ }), {
+ key: "Enter",
+ });
+}
+
+describe("McpCard status rendering", () => {
+ it("labels an expired token and offers Reconnect", () => {
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "stale_token", http_status: 401 } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ expect(screen.getByText("token expired")).toBeInTheDocument();
+ expect(screen.getByText(/token rejected \(HTTP 401\)/)).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Reconnect" })).toBeInTheDocument();
+ });
+
+ it("labels an unreachable server with its error detail", () => {
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "unreachable", error: "ECONNREFUSED" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ expect(screen.getByText("unreachable")).toBeInTheDocument();
+ expect(screen.getByText("ECONNREFUSED")).toBeInTheDocument();
+ });
+
+ it("labels a configured server that is awaiting its bearer", () => {
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "configured_no_token" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ expect(screen.getByText("no token")).toBeInTheDocument();
+ expect(screen.getByText("config saved, awaiting bearer")).toBeInTheDocument();
+ });
+
+ it("shows just host + connected state once connected", () => {
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "connected" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ expect(screen.getByRole("status")).toHaveTextContent("connected");
+ expect(screen.getByText("notfair.co")).toBeInTheDocument();
+ // No detail after the host for a healthy connection.
+ expect(screen.queryByText(/·/)).toBeNull();
+ });
+
+ it("falls back to the raw resource URL when it cannot be parsed", () => {
+ render(
+ <McpCard
+ spec={{ ...xadsSpec, resource_url: "not a url" }}
+ status={{ state: "not_configured" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ expect(screen.getByText("not a url")).toBeInTheDocument();
+ expect(screen.getByText("not connected")).toBeInTheDocument();
+ });
+});
+
+describe("McpCard actions", () => {
+ it("surfaces a Connect failure as a toast and re-enables the button", async () => {
+ startConnect.mockResolvedValue({ ok: false, error: "no discovery" });
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "not_configured" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));
+ await waitFor(() => {
+ expect(startConnect).toHaveBeenCalledWith({
+ mcp_key: "notfair-xads",
+ return_to: window.location.pathname + window.location.search,
+ });
+ expect(toastError).toHaveBeenCalledWith("no discovery");
+ });
+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();
+ });
+
+ it("disconnects from the overflow menu and notifies the host", async () => {
+ disconnect.mockResolvedValue({ ok: true });
+ const onMutated = vi.fn();
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "connected" } as McpRuntimeStatus}
+ projectSlug="proj"
+ onMutated={onMutated}
+ />,
+ );
+ openOverflowMenu();
+ fireEvent.click(screen.getByRole("menuitem", { name: /disconnect/i }));
+ await waitFor(() => {
+ expect(disconnect).toHaveBeenCalledWith({ mcp_key: "notfair-xads" });
+ expect(toastSuccess).toHaveBeenCalledWith("NotFair X Ads disconnected");
+ expect(refresh).toHaveBeenCalled();
+ expect(onMutated).toHaveBeenCalled();
+ });
+ });
+
+ it("keeps the row when disconnect fails, with an error toast", async () => {
+ disconnect.mockResolvedValue({ ok: false, error: "still in use" });
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "connected" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ openOverflowMenu();
+ fireEvent.click(screen.getByRole("menuitem", { name: /disconnect/i }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith("still in use"));
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
+ it("removes the server from the overflow menu", async () => {
+ removeServer.mockResolvedValue({ ok: true });
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "not_configured" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ openOverflowMenu();
+ fireEvent.click(screen.getByRole("menuitem", { name: /remove server/i }));
+ await waitFor(() => {
+ expect(removeServer).toHaveBeenCalledWith({ mcp_key: "notfair-xads" });
+ expect(toastSuccess).toHaveBeenCalledWith("NotFair X Ads removed");
+ });
+ });
+
+ it("opens the tools dialog from View tools, fetching via the server action", async () => {
+ listTools.mockResolvedValue({
+ ok: true,
+ tools: [{ name: "createAd", description: "Make an ad.", args: [] }],
+ });
+ render(
+ <McpCard
+ spec={xadsSpec}
+ status={{ state: "connected" } as McpRuntimeStatus}
+ projectSlug="proj"
+ />,
+ );
+ openOverflowMenu();
+ fireEvent.click(screen.getByRole("menuitem", { name: /view tools/i }));
+ expect(await screen.findByText("createAd")).toBeInTheDocument();
+ expect(listTools).toHaveBeenCalledWith({ mcp_key: "notfair-xads" });
+ });
+});
diff --git a/notfair/src/components/mcp-tools-dialog.test.tsx b/notfair/src/components/mcp-tools-dialog.test.tsx
new file mode 100644
index 00000000..948f090b
--- /dev/null
+++ b/notfair/src/components/mcp-tools-dialog.test.tsx
@@ -0,0 +1,167 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { McpToolsDialog } from "@/components/mcp-tools-dialog";
+import type { ToolSummary } from "@/server/mcp-server/tool-summaries";
+
+const TOOLS: ToolSummary[] = [
+ {
+ name: "createCampaign",
+ description: "Create a Google Ads campaign.",
+ args: [
+ {
+ name: "name",
+ type: "string",
+ required: true,
+ description: "Campaign name.",
+ },
+ {
+ name: "status",
+ type: "enum: ENABLED | PAUSED",
+ required: false,
+ description: "",
+ },
+ ],
+ },
+ {
+ name: "listKeywords",
+ description: "List keywords in an ad group.",
+ args: [],
+ },
+];
+
+describe("McpToolsDialog with eager tools", () => {
+ it("renders the tool count, arg grid, and required markers", () => {
+ render(
+ <McpToolsDialog
+ open
+ onOpenChange={vi.fn()}
+ mcpName="NotFair Google Ads"
+ mcpDescription="Campaigns, bids, keywords."
+ tools={TOOLS}
+ />,
+ );
+ expect(screen.getByText("NotFair Google Ads")).toBeInTheDocument();
+ expect(screen.getByText("2 tools")).toBeInTheDocument();
+ expect(screen.getByText("Campaigns, bids, keywords.")).toBeInTheDocument();
+ expect(screen.getByText("createCampaign")).toBeInTheDocument();
+ expect(screen.getByText("1/2 required")).toBeInTheDocument();
+ expect(screen.getByLabelText("required")).toBeInTheDocument();
+ expect(screen.getByText("enum: ENABLED | PAUSED")).toBeInTheDocument();
+ // Empty arg description falls back to the italic placeholder.
+ expect(screen.getByText("no description")).toBeInTheDocument();
+ });
+
+ it("filters tools by name, description, and arg names", () => {
+ render(
+ <McpToolsDialog
+ open
+ onOpenChange={vi.fn()}
+ mcpName="Ads"
+ tools={TOOLS}
+ />,
+ );
+ const search = screen.getByLabelText("Search tools");
+
+ fireEvent.change(search, { target: { value: "keyword" } });
+ expect(screen.getByText("listKeywords")).toBeInTheDocument();
+ expect(screen.queryByText("createCampaign")).toBeNull();
+
+ // Matches createCampaign via its `status` arg name.
+ fireEvent.change(search, { target: { value: "status" } });
+ expect(screen.getByText("createCampaign")).toBeInTheDocument();
+ expect(screen.queryByText("listKeywords")).toBeNull();
+
+ fireEvent.change(search, { target: { value: "zzz-no-match" } });
+ expect(screen.getByText(/No tools match/)).toBeInTheDocument();
+ expect(screen.getByText("zzz-no-match")).toBeInTheDocument();
+ });
+
+ it("says so when the MCP exposes no tools", () => {
+ render(
+ <McpToolsDialog open onOpenChange={vi.fn()} mcpName="Empty" tools={[]} />,
+ );
+ expect(screen.getByText("This MCP exposes no tools.")).toBeInTheDocument();
+ expect(screen.getByText("0 tools")).toBeInTheDocument();
+ });
+});
+
+describe("McpToolsDialog lazy loading", () => {
+ it("loads once on first open and caches the result", async () => {
+ const loadTools = vi
+ .fn()
+ .mockResolvedValue({ ok: true, tools: [TOOLS[1]] });
+ const { rerender } = render(
+ <McpToolsDialog
+ open={false}
+ onOpenChange={vi.fn()}
+ mcpName="Ext"
+ loadTools={loadTools}
+ />,
+ );
+ expect(loadTools).not.toHaveBeenCalled();
+
+ rerender(
+ <McpToolsDialog
+ open
+ onOpenChange={vi.fn()}
+ mcpName="Ext"
+ loadTools={loadTools}
+ />,
+ );
+ expect(await screen.findByText("listKeywords")).toBeInTheDocument();
+ expect(loadTools).toHaveBeenCalledTimes(1);
+
+ // Close and reopen — the cached list is reused, no second fetch.
+ rerender(
+ <McpToolsDialog
+ open={false}
+ onOpenChange={vi.fn()}
+ mcpName="Ext"
+ loadTools={loadTools}
+ />,
+ );
+ rerender(
+ <McpToolsDialog
+ open
+ onOpenChange={vi.fn()}
+ mcpName="Ext"
+ loadTools={loadTools}
+ />,
+ );
+ expect(screen.getByText("listKeywords")).toBeInTheDocument();
+ expect(loadTools).toHaveBeenCalledTimes(1);
+ });
+
+ it("shows the loader error", async () => {
+ const loadTools = vi
+ .fn()
+ .mockResolvedValue({ ok: false, error: "MCP unreachable" });
+ render(
+ <McpToolsDialog
+ open
+ onOpenChange={vi.fn()}
+ mcpName="Ext"
+ loadTools={loadTools}
+ />,
+ );
+ expect(await screen.findByText("MCP unreachable")).toBeInTheDocument();
+ });
+
+ it("shows a thrown loader failure as an error message", async () => {
+ const loadTools = vi.fn().mockRejectedValue(new Error("network down"));
+ render(
+ <McpToolsDialog
+ open
+ onOpenChange={vi.fn()}
+ mcpName="Ext"
+ loadTools={loadTools}
+ />,
+ );
+ expect(await screen.findByText("network down")).toBeInTheDocument();
+ await waitFor(() =>
+ expect(screen.queryByText(/Fetching tool list/)).toBeNull(),
+ );
+ });
+});
diff --git a/notfair/src/components/working-indicator.more.test.tsx b/notfair/src/components/working-indicator.more.test.tsx
new file mode 100644
index 00000000..10329971
--- /dev/null
+++ b/notfair/src/components/working-indicator.more.test.tsx
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+
+import { WorkingIndicator, type WorkingPhase } from "@/components/working-indicator";
+
+const phase = (id: string, state: WorkingPhase["state"]): WorkingPhase => ({
+ id,
+ label: `phase ${id}`,
+ state,
+});
+
+describe("WorkingIndicator (top-up)", () => {
+ it("shows only the last three phases with per-state icons", () => {
+ const { container } = render(
+ <WorkingIndicator
+ agentDisplayName="Agent"
+ headline="Thinking"
+ subtitle="Ran tests ✓"
+ phases={[
+ phase("p1", "done"),
+ phase("p2", "done"),
+ phase("p3", "failed"),
+ phase("p4", "done"),
+ phase("p5", "active"),
+ ]}
+ elapsedMs={5_000}
+ mood="waiting"
+ />,
+ );
+ // Sliced to the trailing three.
+ expect(screen.queryByText("phase p1")).toBeNull();
+ expect(screen.queryByText("phase p2")).toBeNull();
+ expect(screen.getByText("phase p3")).toBeInTheDocument();
+ expect(screen.getByText("phase p5")).toBeInTheDocument();
+ // One list item per visible phase.
+ expect(container.querySelectorAll("li")).toHaveLength(3);
+ // Subtitle renders below the headline.
+ expect(screen.getByText("Ran tests ✓")).toBeInTheDocument();
+ // Sub-minute elapsed formatting.
+ expect(screen.getByText("0:05")).toBeInTheDocument();
+ });
+
+ it("omits the timer when elapsed is null and the phase list when empty", () => {
+ const { container } = render(
+ <WorkingIndicator
+ agentDisplayName="Agent"
+ headline="Starting"
+ subtitle={null}
+ phases={[]}
+ elapsedMs={null}
+ mood="waiting"
+ />,
+ );
+ expect(container.querySelector("ol")).toBeNull();
+ expect(container.querySelector(".tabular-nums")).toBeNull();
+ expect(screen.getByRole("status", { name: "Agent Starting" })).toHaveAttribute(
+ "data-run-state",
+ "running",
+ );
+ });
+});
diff --git a/notfair/src/lib/project-href.test.ts b/notfair/src/lib/project-href.test.ts
new file mode 100644
index 00000000..421505a7
--- /dev/null
+++ b/notfair/src/lib/project-href.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+
+import { projectHref, subPathFromPathname } from "./project-href";
+
+describe("projectHref", () => {
+ it("returns the project root for an empty or slash path", () => {
+ expect(projectHref("demo")).toBe("/demo");
+ expect(projectHref("demo", "")).toBe("/demo");
+ expect(projectHref("demo", "/")).toBe("/demo");
+ });
+
+ it("prefixes the slug regardless of leading-slash style", () => {
+ expect(projectHref("demo", "goals/goal-1")).toBe("/demo/goals/goal-1");
+ expect(projectHref("demo", "/goals/goal-1")).toBe("/demo/goals/goal-1");
+ });
+
+ it("throws when the slug is missing", () => {
+ expect(() => projectHref("", "goals")).toThrow("slug is required");
+ });
+});
+
+describe("subPathFromPathname", () => {
+ it("returns empty for the project home", () => {
+ expect(subPathFromPathname("/demo", "demo")).toBe("");
+ });
+
+ it("strips the current slug and keeps the leading slash", () => {
+ expect(subPathFromPathname("/demo/connections", "demo")).toBe("/connections");
+ expect(subPathFromPathname("/demo/goals/goal-1", "demo")).toBe("/goals/goal-1");
+ });
+
+ it("returns empty when the pathname belongs to a different project", () => {
+ expect(subPathFromPathname("/other/connections", "demo")).toBe("");
+ // Prefix must be a full segment — "/demofoo" is not project "demo".
+ expect(subPathFromPathname("/demofoo/x", "demo")).toBe("");
+ });
+
+ it("returns empty on missing inputs", () => {
+ expect(subPathFromPathname(null, "demo")).toBe("");
+ expect(subPathFromPathname("/demo/x", undefined)).toBe("");
+ });
+});
diff --git a/notfair/src/lib/slash-commands.test.ts b/notfair/src/lib/slash-commands.test.ts
new file mode 100644
index 00000000..86e9a48d
--- /dev/null
+++ b/notfair/src/lib/slash-commands.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ SLASH_COMMANDS,
+ executeLocalSlashCommand,
+ filterSlashCommands,
+ findCommand,
+ parseSlashMessage,
+} from "./slash-commands";
+
+describe("filterSlashCommands", () => {
+ it("returns the full catalog for an empty or bare-slash query", () => {
+ expect(filterSlashCommands("")).toEqual(SLASH_COMMANDS);
+ expect(filterSlashCommands("/")).toEqual(SLASH_COMMANDS);
+ });
+
+ it("prefix-matches first, with or without the leading slash", () => {
+ expect(filterSlashCommands("/cl").map((c) => c.name)).toEqual(["clear"]);
+ expect(filterSlashCommands("mo").map((c) => c.name)).toEqual(["model"]);
+ });
+
+ it("falls back to substring match when no prefix hits", () => {
+ // "od" is not a prefix of anything but appears inside "model".
+ expect(filterSlashCommands("/od").map((c) => c.name)).toEqual(["model"]);
+ });
+
+ it("returns nothing for a query matching no command", () => {
+ expect(filterSlashCommands("/zzz")).toEqual([]);
+ });
+});
+
+describe("parseSlashMessage", () => {
+ it("returns null for plain messages", () => {
+ expect(parseSlashMessage("hello")).toBeNull();
+ expect(parseSlashMessage(" not / a command")).toBeNull();
+ });
+
+ it("splits command and args, trimming both ends", () => {
+ expect(parseSlashMessage("/stop")).toEqual({ command: "stop", args: "" });
+ expect(parseSlashMessage(" /model opus fast ")).toEqual({
+ command: "model",
+ args: "opus fast",
+ });
+ });
+});
+
+describe("findCommand", () => {
+ it("finds catalog commands by name and misses unknowns", () => {
+ expect(findCommand("help")?.key).toBe("help");
+ expect(findCommand("nope")).toBeUndefined();
+ });
+});
+
+describe("executeLocalSlashCommand", () => {
+ it("maps each catalog command to its local action", () => {
+ expect(executeLocalSlashCommand("clear")).toEqual({ kind: "clear" });
+ expect(executeLocalSlashCommand("stop")).toEqual({ kind: "stop" });
+ expect(executeLocalSlashCommand("model", " opus ")).toEqual({
+ kind: "set-model",
+ value: "opus",
+ });
+ });
+
+ it("renders a help listing that names every command", () => {
+ const action = executeLocalSlashCommand("help");
+ expect(action?.kind).toBe("help");
+ const content = (action as { kind: "help"; content: string }).content;
+ for (const c of SLASH_COMMANDS) {
+ expect(content).toContain(`/${c.name}`);
+ expect(content).toContain(c.description);
+ }
+ });
+
+ it("returns null for unknown commands so they pass through to the agent", () => {
+ expect(executeLocalSlashCommand("compact")).toBeNull();
+ });
+});
diff --git a/notfair/src/lib/slug.test.ts b/notfair/src/lib/slug.test.ts
new file mode 100644
index 00000000..57c3ab8b
--- /dev/null
+++ b/notfair/src/lib/slug.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+
+import { isValidSlug, slugify } from "./slug";
+
+describe("slugify", () => {
+ it("lowercases, hyphenates whitespace, and strips punctuation", () => {
+ expect(slugify("My Cool Project!")).toEqual({ ok: true, slug: "my-cool-project" });
+ expect(slugify(" spaced out ")).toEqual({ ok: true, slug: "spaced-out" });
+ });
+
+ it("normalizes accented characters to ASCII", () => {
+ expect(slugify("Café Über")).toEqual({ ok: true, slug: "cafe-uber" });
+ });
+
+ it("collapses runs of separators and trims leading/trailing dashes", () => {
+ expect(slugify("--a---b--")).toEqual({ ok: true, slug: "a-b" });
+ });
+
+ it("rejects empty input", () => {
+ expect(slugify(" ")).toEqual({ ok: false, reason: "input is empty" });
+ });
+
+ it("rejects input with no usable characters", () => {
+ expect(slugify("!!! ??? ***")).toEqual({
+ ok: false,
+ reason: "no valid characters",
+ });
+ });
+
+ it("caps length and strips a dash left dangling by the cut", () => {
+ const result = slugify("abcde fghij", 6);
+ // "abcde-fghij" cut at 6 is "abcde-" → trailing dash removed.
+ expect(result).toEqual({ ok: true, slug: "abcde" });
+ });
+
+ it("rejects reserved system names with a suggested variation", () => {
+ const result = slugify("NotFair");
+ expect(result.ok).toBe(false);
+ if (!result.ok) {
+ expect(result.reason).toContain("reserved system name");
+ expect(result.reason).toContain("notfair-team");
+ }
+ });
+});
+
+describe("isValidSlug", () => {
+ it("accepts well-formed non-reserved slugs", () => {
+ expect(isValidSlug("my-project-2")).toBe(true);
+ });
+
+ it("rejects malformed and reserved slugs", () => {
+ expect(isValidSlug("Has Spaces")).toBe(false);
+ expect(isValidSlug("-leading")).toBe(false);
+ expect(isValidSlug("api")).toBe(false);
+ expect(isValidSlug("agents")).toBe(false);
+ });
+});
diff --git a/notfair/src/lib/utils.test.ts b/notfair/src/lib/utils.test.ts
new file mode 100644
index 00000000..2e82e903
--- /dev/null
+++ b/notfair/src/lib/utils.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+
+import { cn } from "./utils";
+
+describe("cn", () => {
+ it("joins classes and drops falsy conditionals", () => {
+ expect(cn("a", false && "b", undefined, "c")).toBe("a c");
+ });
+
+ it("lets later tailwind utilities win over earlier conflicting ones", () => {
+ expect(cn("px-2 text-sm", "px-4")).toBe("text-sm px-4");
+ });
+});
diff --git a/notfair/src/server/actions/mcp.test.ts b/notfair/src/server/actions/mcp.test.ts
new file mode 100644
index 00000000..89a934b4
--- /dev/null
+++ b/notfair/src/server/actions/mcp.test.ts
@@ -0,0 +1,575 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { createHash } from "node:crypto";
+
+// 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-actions-mcp-"));
+});
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ getActiveProject: vi.fn(),
+ setPending: vi.fn(),
+ disconnectMcp: vi.fn(async () => {}),
+ getMcpConfig: vi.fn(),
+ mcpRpcAutoRefresh: vi.fn(),
+ listProjectAgents: vi.fn(async () => [] as Array<{ agent_id: string }>),
+ unregisterMcp: vi.fn(async () => {}),
+ headerMap: new Map<string, string>(),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("next/headers", () => ({
+ headers: async () => ({
+ get: (name: string) => mocks.headerMap.get(name.toLowerCase()) ?? null,
+ }),
+}));
+vi.mock("@/server/active-project", () => ({
+ getActiveProject: mocks.getActiveProject,
+}));
+vi.mock("@/server/mcp-pending", () => ({ setPending: mocks.setPending }));
+vi.mock("@/server/mcp/state", () => ({ disconnectMcp: mocks.disconnectMcp }));
+vi.mock("@/server/mcp/rpc", () => ({
+ getMcpConfig: mocks.getMcpConfig,
+ mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh,
+}));
+vi.mock("@/server/agent-meta", () => ({
+ listProjectAgents: mocks.listProjectAgents,
+}));
+vi.mock("@/server/adapters/registry", () => ({
+ requireAdapter: () => ({ unregisterMcp: mocks.unregisterMcp }),
+}));
+
+import { getDb } from "@/server/db/db";
+import { getProject } from "@/server/db/projects";
+import {
+ addHiddenMcpPresetKey,
+ getHiddenMcpPresetKeys,
+} from "@/server/db/projects";
+import {
+ findUserMcpServer,
+ insertUserMcpServer,
+} from "@/server/db/user-mcp-servers";
+import {
+ addUserMcpServerAction,
+ disconnectMcpAction,
+ listMcpToolsAction,
+ probeMcpDiscovery,
+ removeUserMcpServerAction,
+ startMcpConnect,
+} from "./mcp";
+
+const SLUG = "proj";
+
+// ── fetch fixture: a routable fake OAuth ecosystem ───────────────────
+const RESOURCE_URL = "https://mcp.acme.dev/sse";
+const DISCOVERY_URL =
+ "https://mcp.acme.dev/.well-known/oauth-protected-resource/sse";
+const ISSUER = "https://auth.acme.dev";
+const AS_METADATA_URL = `${ISSUER}/.well-known/oauth-authorization-server`;
+const REGISTRATION_URL = `${ISSUER}/register`;
+
+type Route = (init?: RequestInit) => Response | Promise<Response>;
+let routes: Map<string, Route>;
+const fetchCalls: Array<{ url: string; init?: RequestInit }> = [];
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+function installDefaultRoutes(opts: { authMethods?: string[] } = {}) {
+ routes = new Map<string, Route>([
+ [DISCOVERY_URL, () => json({ authorization_servers: [`${ISSUER}/`] })],
+ [
+ AS_METADATA_URL,
+ () =>
+ json({
+ issuer: ISSUER,
+ authorization_endpoint: `${ISSUER}/authorize`,
+ token_endpoint: `${ISSUER}/token`,
+ registration_endpoint: REGISTRATION_URL,
+ token_endpoint_auth_methods_supported: opts.authMethods ?? ["none"],
+ }),
+ ],
+ [REGISTRATION_URL, () => json({ client_id: "cid-1", client_secret: "sec-1" })],
+ ]);
+}
+
+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());
+ insertUserMcpServer({
+ project_slug: SLUG,
+ key: "acme",
+ display_name: "Acme MCP",
+ resource_url: RESOURCE_URL,
+ discovery_url: DISCOVERY_URL,
+ });
+ vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ fetchCalls.push({ url, init });
+ const route = routes.get(url);
+ if (!route) return new Response("not found", { status: 404 });
+ return route(init);
+ });
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ fetchCalls.length = 0;
+ installDefaultRoutes();
+ mocks.getActiveProject.mockResolvedValue(getProject(SLUG));
+ mocks.headerMap.clear();
+ mocks.headerMap.set("host", "localhost:3326");
+});
+
+// ── startMcpConnect ──────────────────────────────────────────────────
+
+describe("startMcpConnect", () => {
+ it("fails without an active project", async () => {
+ mocks.getActiveProject.mockResolvedValue(null);
+ const r = await startMcpConnect({ mcp_key: "acme" });
+ expect(r).toMatchObject({ ok: false });
+ if (r.ok) return;
+ expect(r.error).toContain("No active project");
+ });
+
+ it("fails on an unknown catalog key", async () => {
+ const r = await startMcpConnect({ mcp_key: "does-not-exist" });
+ expect(r).toMatchObject({ ok: false, error: "Unknown MCP key: does-not-exist" });
+ });
+
+ it("surfaces discovery failures", async () => {
+ routes.delete(DISCOVERY_URL); // 404s now
+ const r = await startMcpConnect({ mcp_key: "acme" });
+ expect(r).toMatchObject({ ok: false });
+ if (r.ok) return;
+ expect(r.error).toMatch(/^Discovery failed: /);
+ });
+
+ it("surfaces DCR failures", async () => {
+ routes.set(REGISTRATION_URL, () => new Response("denied", { status: 400 }));
+ const r = await startMcpConnect({ mcp_key: "acme" });
+ expect(r).toMatchObject({ ok: false });
+ if (r.ok) return;
+ expect(r.error).toContain("Registration failed: DCR 400");
+ });
+
+ it("builds the authorize URL and stashes the pending flow", async () => {
+ const r = await startMcpConnect({ mcp_key: "acme", return_to: "/goals/1" });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+
+ const u = new URL(r.authorize_url);
+ expect(u.origin + u.pathname).toBe(`${ISSUER}/authorize`);
+ expect(u.searchParams.get("response_type")).toBe("code");
+ expect(u.searchParams.get("client_id")).toBe("cid-1");
+ // localhost normalized to the RFC 8252 loopback IP.
+ expect(u.searchParams.get("redirect_uri")).toBe(
+ "http://127.0.0.1:3326/api/mcp-oauth/callback",
+ );
+ expect(u.searchParams.get("code_challenge_method")).toBe("S256");
+ expect(u.searchParams.get("resource")).toBe(RESOURCE_URL);
+
+ expect(mocks.setPending).toHaveBeenCalledTimes(1);
+ const [state, flow] = mocks.setPending.mock.calls[0]! as [
+ string,
+ Record<string, unknown>,
+ ];
+ expect(state).toBe(u.searchParams.get("state"));
+ expect(flow).toMatchObject({
+ catalog_key: "acme",
+ display_name: "Acme MCP",
+ resource_url: RESOURCE_URL,
+ issuer: ISSUER, // trailing slash stripped
+ token_endpoint: `${ISSUER}/token`,
+ client_id: "cid-1",
+ client_secret: "sec-1",
+ redirect_uri: "http://127.0.0.1:3326/api/mcp-oauth/callback",
+ project_slug: SLUG,
+ return_to: "/goals/1",
+ });
+ // The challenge in the URL is the S256 hash of the stashed verifier.
+ const expected = createHash("sha256")
+ .update(String(flow.code_verifier))
+ .digest("base64")
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+ expect(u.searchParams.get("code_challenge")).toBe(expected);
+
+ // DCR registered a public client (AS advertised `none`).
+ const dcr = fetchCalls.find((c) => c.url === REGISTRATION_URL)!;
+ const body = JSON.parse(String(dcr.init?.body));
+ expect(body.token_endpoint_auth_method).toBe("none");
+ expect(body.grant_types).toEqual(["authorization_code", "refresh_token"]);
+ });
+
+ it("drops off-site and protocol-relative return_to values", async () => {
+ for (const bad of ["https://evil.example", "//evil.example/x"]) {
+ await startMcpConnect({ mcp_key: "acme", return_to: bad });
+ const flow = mocks.setPending.mock.calls.at(-1)![1] as Record<string, unknown>;
+ expect(flow.return_to).toBeUndefined();
+ }
+ });
+
+ it("falls back to client_secret_post when the AS doesn't allow public clients", async () => {
+ installDefaultRoutes({ authMethods: ["client_secret_post", "client_secret_basic"] });
+ const r = await startMcpConnect({ mcp_key: "acme" });
+ expect(r.ok).toBe(true);
+ const dcr = fetchCalls.find((c) => c.url === REGISTRATION_URL)!;
+ expect(JSON.parse(String(dcr.init?.body)).token_endpoint_auth_method).toBe(
+ "client_secret_post",
+ );
+ });
+
+ it("respects forwarded proto/host headers", async () => {
+ mocks.headerMap.set("x-forwarded-proto", "https");
+ mocks.headerMap.set("x-forwarded-host", "notfair.example");
+ const r = await startMcpConnect({ mcp_key: "acme" });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(new URL(r.authorize_url).searchParams.get("redirect_uri")).toBe(
+ "https://notfair.example/api/mcp-oauth/callback",
+ );
+ });
+});
+
+// ── probeMcpDiscovery ────────────────────────────────────────────────
+
+describe("probeMcpDiscovery", () => {
+ it("rejects non-URL and non-http(s) resource URLs", async () => {
+ for (const bad of ["not a url", "ftp://mcp.acme.dev"]) {
+ const r = await probeMcpDiscovery({ resource_url: bad });
+ expect(r).toMatchObject({ ok: false, kind: "bad_url" });
+ }
+ });
+
+ it("classifies a missing discovery doc", async () => {
+ routes.delete(DISCOVERY_URL);
+ const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });
+ expect(r).toMatchObject({ ok: false, kind: "no_discovery_doc" });
+ });
+
+ it("classifies a doc without authorization_servers", async () => {
+ routes.set(DISCOVERY_URL, () => json({ resource: RESOURCE_URL }));
+ const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });
+ expect(r).toMatchObject({ ok: false, kind: "no_authorization_servers" });
+ routes.set(DISCOVERY_URL, () => json({ authorization_servers: [] }));
+ expect(await probeMcpDiscovery({ resource_url: RESOURCE_URL })).toMatchObject({
+ ok: false,
+ kind: "no_authorization_servers",
+ });
+ });
+
+ it("classifies unreachable AS metadata, listing every attempted URL", async () => {
+ routes.delete(AS_METADATA_URL);
+ const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });
+ expect(r).toMatchObject({ ok: false, kind: "as_metadata_missing_endpoints" });
+ if (r.ok) return;
+ expect(r.error).toContain("Couldn't fetch AS metadata");
+ expect(r.error).toContain(AS_METADATA_URL);
+ expect(r.error).toContain(`${ISSUER}/.well-known/openid-configuration`);
+ });
+
+ it("classifies metadata missing endpoints and missing DCR", async () => {
+ routes.set(AS_METADATA_URL, () => json({ issuer: ISSUER }));
+ expect(await probeMcpDiscovery({ resource_url: RESOURCE_URL })).toMatchObject({
+ ok: false,
+ kind: "as_metadata_missing_endpoints",
+ });
+ routes.set(AS_METADATA_URL, () =>
+ json({
+ authorization_endpoint: `${ISSUER}/authorize`,
+ token_endpoint: `${ISSUER}/token`,
+ }),
+ );
+ expect(await probeMcpDiscovery({ resource_url: RESOURCE_URL })).toMatchObject({
+ ok: false,
+ kind: "dcr_unsupported",
+ });
+ });
+
+ it("resolves happy-path metadata", async () => {
+ const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });
+ expect(r).toEqual({
+ ok: true,
+ discovery_url: DISCOVERY_URL,
+ issuer: ISSUER,
+ registration_endpoint: REGISTRATION_URL,
+ });
+ });
+
+ it("falls back to appended-form metadata URLs for path-bearing issuers", async () => {
+ const pathIssuer = `${ISSUER}/tenant`;
+ routes.set(DISCOVERY_URL, () => json({ authorization_servers: [pathIssuer] }));
+ // Inserted forms 404; only the appended form resolves.
+ routes.set(`${pathIssuer}/.well-known/oauth-authorization-server`, () =>
+ json({
+ authorization_endpoint: `${pathIssuer}/authorize`,
+ token_endpoint: `${pathIssuer}/token`,
+ registration_endpoint: `${pathIssuer}/register`,
+ }),
+ );
+ const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });
+ expect(r).toMatchObject({ ok: true, issuer: pathIssuer });
+ const attempted = fetchCalls.map((c) => c.url);
+ // Spec-correct inserted forms were tried first.
+ expect(attempted).toContain(
+ `${ISSUER}/.well-known/oauth-authorization-server/tenant`,
+ );
+ expect(attempted).toContain(`${ISSUER}/.well-known/openid-configuration/tenant`);
+ });
+});
+
+// ── disconnectMcpAction ──────────────────────────────────────────────
+
+describe("disconnectMcpAction", () => {
+ it("fails without an active project", async () => {
+ mocks.getActiveProject.mockResolvedValue(null);
+ const r = await disconnectMcpAction({ mcp_key: "acme" });
+ expect(r).toMatchObject({ ok: false });
+ });
+
+ it("surfaces disconnect errors (including non-Error throws)", async () => {
+ mocks.disconnectMcp.mockRejectedValueOnce(new Error("token vault sealed"));
+ expect(await disconnectMcpAction({ mcp_key: "acme" })).toEqual({
+ ok: false,
+ error: "token vault sealed",
+ });
+ mocks.disconnectMcp.mockRejectedValueOnce("plain string");
+ expect(await disconnectMcpAction({ mcp_key: "acme" })).toEqual({
+ ok: false,
+ error: "plain string",
+ });
+ expect(mocks.revalidatePath).not.toHaveBeenCalled();
+ });
+
+ it("disconnects and revalidates", async () => {
+ const r = await disconnectMcpAction({ mcp_key: "acme" });
+ expect(r).toEqual({ ok: true });
+ expect(mocks.disconnectMcp).toHaveBeenCalledWith(SLUG, "acme");
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+ });
+});
+
+// ── listMcpToolsAction ───────────────────────────────────────────────
+
+describe("listMcpToolsAction", () => {
+ it("fails without an active project or config", async () => {
+ mocks.getActiveProject.mockResolvedValueOnce(null);
+ expect(await listMcpToolsAction({ mcp_key: "acme" })).toMatchObject({ ok: false });
+
+ mocks.getMcpConfig.mockReturnValueOnce(null);
+ expect(await listMcpToolsAction({ mcp_key: "acme" })).toEqual({
+ ok: false,
+ error: "MCP is not configured for this project.",
+ });
+ });
+
+ it.each([
+ [{ ok: false, kind: "http_error", status: 503 }, "HTTP 503"],
+ [{ ok: false, kind: "rpc_error", code: -32000, message: "nope" }, "RPC -32000: nope"],
+ [{ ok: false, kind: "timeout" }, "MCP call timed out"],
+ [{ ok: false, kind: "aborted" }, "MCP call aborted"],
+ [{ ok: false, kind: "malformed_response", message: "not json" }, "not json"],
+ [{ ok: false, kind: "network_error", message: "ECONNREFUSED" }, "ECONNREFUSED"],
+ ])("maps rpc failure %o to a human message", async (rpcResult, expected) => {
+ mocks.getMcpConfig.mockReturnValue({ bearer: "b" });
+ mocks.mcpRpcAutoRefresh.mockResolvedValueOnce(rpcResult);
+ expect(await listMcpToolsAction({ mcp_key: "acme" })).toEqual({
+ ok: false,
+ error: expected,
+ });
+ });
+
+ it("normalizes the tools list into ToolSummary shape", async () => {
+ mocks.getMcpConfig.mockReturnValue({ bearer: "b" });
+ mocks.mcpRpcAutoRefresh.mockResolvedValueOnce({
+ ok: true,
+ result: {
+ tools: [
+ {
+ name: "search",
+ description: "Search things",
+ inputSchema: {
+ type: "object",
+ properties: { q: { type: "string", description: "query" } },
+ required: ["q"],
+ },
+ },
+ { name: "bare" }, // no description, no schema
+ { name: 42 }, // dropped: non-string name
+ ],
+ },
+ });
+ const r = await listMcpToolsAction({ mcp_key: "acme" });
+ expect(r).toEqual({
+ ok: true,
+ tools: [
+ {
+ name: "search",
+ description: "Search things",
+ args: [{ name: "q", type: "string", description: "query", required: true }],
+ },
+ { name: "bare", description: "", args: [] },
+ ],
+ });
+ });
+
+ it("returns an empty list when the server sends no tools array", async () => {
+ mocks.getMcpConfig.mockReturnValue({ bearer: "b" });
+ mocks.mcpRpcAutoRefresh.mockResolvedValueOnce({ ok: true, result: {} });
+ expect(await listMcpToolsAction({ mcp_key: "acme" })).toEqual({
+ ok: true,
+ tools: [],
+ });
+ });
+});
+
+// ── addUserMcpServerAction ───────────────────────────────────────────
+
+describe("addUserMcpServerAction", () => {
+ it("fails without an active project", async () => {
+ mocks.getActiveProject.mockResolvedValue(null);
+ const r = await addUserMcpServerAction({
+ display_name: "X",
+ resource_url: RESOURCE_URL,
+ });
+ expect(r).toMatchObject({ ok: false, kind: "no_project" });
+ });
+
+ it("rejects a name that can't slugify", async () => {
+ const r = await addUserMcpServerAction({
+ display_name: "###",
+ resource_url: RESOURCE_URL,
+ });
+ expect(r).toMatchObject({ ok: false, kind: "name_unusable" });
+ });
+
+ it("un-hides a preset key instead of writing a row", async () => {
+ addHiddenMcpPresetKey(SLUG, "notfair-googleads");
+ const r = await addUserMcpServerAction({
+ display_name: "NotFair Google Ads",
+ resource_url: "https://notfair.co/api/mcp/google_ads",
+ key: "notfair-googleads",
+ });
+ expect(r).toEqual({ ok: true, key: "notfair-googleads" });
+ expect(getHiddenMcpPresetKeys(SLUG)).toEqual([]);
+ expect(findUserMcpServer(SLUG, "notfair-googleads")).toBeNull();
+ expect(fetchCalls).toEqual([]); // no discovery probe
+ });
+
+ it("is a no-op success when the key already exists", async () => {
+ const r = await addUserMcpServerAction({
+ display_name: "Acme MCP",
+ resource_url: RESOURCE_URL,
+ key: "acme",
+ });
+ expect(r).toEqual({ ok: true, key: "acme" });
+ expect(fetchCalls).toEqual([]);
+ });
+
+ it("re-uses the stored key when the same URL exists under another key", async () => {
+ const r = await addUserMcpServerAction({
+ display_name: "Acme Renamed",
+ resource_url: "https://mcp.acme.dev/sse/", // trailing slash: normalized match
+ });
+ expect(r).toEqual({ ok: true, key: "acme" });
+ expect(fetchCalls).toEqual([]);
+ });
+
+ it("propagates probe failures", async () => {
+ routes.delete(DISCOVERY_URL);
+ const r = await addUserMcpServerAction({
+ display_name: "Broken",
+ resource_url: RESOURCE_URL.replace("/sse", "/other"),
+ });
+ expect(r).toMatchObject({ ok: false, kind: "no_discovery_doc" });
+ expect(findUserMcpServer(SLUG, "broken")).toBeNull();
+ });
+
+ it("probes discovery and inserts a trimmed row (ignoring an invalid key override)", async () => {
+ const resource = "https://mcp.acme.dev/v2";
+ const discovery =
+ "https://mcp.acme.dev/.well-known/oauth-protected-resource/v2";
+ routes.set(discovery, () => json({ authorization_servers: [ISSUER] }));
+ const r = await addUserMcpServerAction({
+ display_name: " Acme V2 ",
+ description: " second gen ",
+ resource_url: resource,
+ key: "Not_A_Valid_Key",
+ });
+ expect(r).toEqual({ ok: true, key: "acme-v2" });
+ expect(findUserMcpServer(SLUG, "acme-v2")).toMatchObject({
+ display_name: "Acme V2",
+ description: "second gen",
+ resource_url: resource,
+ discovery_url: discovery,
+ });
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+ });
+});
+
+// ── removeUserMcpServerAction ────────────────────────────────────────
+
+describe("removeUserMcpServerAction", () => {
+ it("fails without an active project or on an unknown user key", async () => {
+ mocks.getActiveProject.mockResolvedValueOnce(null);
+ expect(await removeUserMcpServerAction({ mcp_key: "acme" })).toMatchObject({
+ ok: false,
+ });
+ expect(await removeUserMcpServerAction({ mcp_key: "ghost" })).toEqual({
+ ok: false,
+ error: "Unknown MCP key: ghost.",
+ });
+ });
+
+ it("surfaces disconnect failures", async () => {
+ mocks.disconnectMcp.mockRejectedValueOnce(new Error("db locked"));
+ expect(await removeUserMcpServerAction({ mcp_key: "acme" })).toEqual({
+ ok: false,
+ error: "db locked",
+ });
+ expect(findUserMcpServer(SLUG, "acme")).not.toBeNull();
+ });
+
+ it("hides a preset and unregisters it from every agent (best-effort)", async () => {
+ mocks.listProjectAgents.mockResolvedValueOnce([
+ { agent_id: "proj-goal-1" },
+ { agent_id: "proj-goal-2" },
+ ]);
+ mocks.unregisterMcp.mockRejectedValueOnce(new Error("harness config missing"));
+ const r = await removeUserMcpServerAction({ mcp_key: "notfair-metaads" });
+ expect(r).toEqual({ ok: true });
+ expect(getHiddenMcpPresetKeys(SLUG)).toContain("notfair-metaads");
+ expect(mocks.disconnectMcp).toHaveBeenCalledWith(SLUG, "notfair-metaads");
+ expect(
+ mocks.unregisterMcp.mock.calls.map(
+ (c) => ((c as unknown[])[0] as { agentId: string }).agentId,
+ ),
+ ).toEqual([
+ "proj-goal-1",
+ "proj-goal-2",
+ ]);
+ });
+
+ it("deletes a user row", async () => {
+ const r = await removeUserMcpServerAction({ mcp_key: "acme" });
+ expect(r).toEqual({ ok: true });
+ expect(findUserMcpServer(SLUG, "acme")).toBeNull();
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+ });
+});
diff --git a/notfair/src/server/actions/projects.test.ts b/notfair/src/server/actions/projects.test.ts
new file mode 100644
index 00000000..ba55df0a
--- /dev/null
+++ b/notfair/src/server/actions/projects.test.ts
@@ -0,0 +1,412 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+// 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.
+const h = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-actions-projects-"));
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir };
+});
+
+const mocks = vi.hoisted(() => ({
+ revalidatePath: vi.fn(),
+ redirect: vi.fn(),
+ cookieJar: new Map<string, string>(),
+ listProjectAgents: vi.fn(async () => [] as unknown[]),
+ readAgentMeta: vi.fn(() => null as unknown),
+ relocateAgent: vi.fn(async () => ({ new_agent_id: "x", new_slug: "y" })),
+ cascadeDeleteProjectArtifacts: vi.fn(async () => {}),
+ getProjectDeletionSummary: vi.fn(async () => ({ agents: [], mcps: [] })),
+ listProjectMcpTokens: vi.fn(() => [] as unknown[]),
+ renameProjectBriefDir: vi.fn(async () => {}),
+ deleteProjectBriefDir: vi.fn(async () => {}),
+ syncProjectAgents: vi.fn(async () => 0),
+}));
+
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));
+vi.mock("next/headers", () => ({
+ cookies: async () => ({
+ get: (name: string) =>
+ mocks.cookieJar.has(name) ? { name, value: mocks.cookieJar.get(name)! } : undefined,
+ set: (name: string, value: string) => void mocks.cookieJar.set(name, value),
+ delete: (name: string) => void mocks.cookieJar.delete(name),
+ }),
+}));
+vi.mock("@/server/agent-meta", () => ({
+ listProjectAgents: mocks.listProjectAgents,
+ readAgentMeta: mocks.readAgentMeta,
+}));
+vi.mock("@/server/actions/agents", () => ({
+ relocateAgent: mocks.relocateAgent,
+}));
+vi.mock("@/server/agents/cascade-delete", () => ({
+ cascadeDeleteProjectArtifacts: mocks.cascadeDeleteProjectArtifacts,
+ getProjectDeletionSummary: mocks.getProjectDeletionSummary,
+}));
+vi.mock("@/server/mcp/tokens", () => ({
+ listProjectMcpTokens: mocks.listProjectMcpTokens,
+}));
+vi.mock("@/server/onboarding/project-brief", () => ({
+ renameProjectBriefDir: mocks.renameProjectBriefDir,
+ deleteProjectBriefDir: mocks.deleteProjectBriefDir,
+}));
+vi.mock("@/server/goals/provision", () => ({
+ syncProjectAgents: mocks.syncProjectAgents,
+}));
+
+import { getDb } from "@/server/db/db";
+import { createProject, getProject } from "@/server/db/projects";
+import {
+ archiveProjectAction,
+ createProjectAction,
+ createProjectForOnboardingAction,
+ deleteProjectAction,
+ getProjectDeletionSummaryAction,
+ renameProjectAction,
+ renameProjectFullAction,
+ setProjectCodebasePathAction,
+ switchProjectAction,
+} from "./projects";
+
+const COOKIE = "notfair_active_project";
+
+function form(fields: Record<string, string>): FormData {
+ const fd = new FormData();
+ for (const [k, v] of Object.entries(fields)) fd.set(k, v);
+ return fd;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.cookieJar.clear();
+ mocks.listProjectAgents.mockResolvedValue([]);
+});
+
+describe("createProjectAction", () => {
+ it("throws on a missing name", async () => {
+ await expect(createProjectAction(form({}))).rejects.toThrow(
+ "Please enter a workspace name.",
+ );
+ });
+
+ it("throws with the createProject reason on failure", async () => {
+ createProject({ display_name: "Taken" });
+ await expect(
+ createProjectAction(form({ display_name: "Taken" })),
+ ).rejects.toThrow("already exists");
+ });
+
+ it("creates, activates, and redirects home", async () => {
+ await createProjectAction(form({ display_name: "Fresh One" }));
+ expect(getProject("fresh-one")).not.toBeNull();
+ expect(mocks.cookieJar.get(COOKIE)).toBe("fresh-one");
+ expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");
+ expect(mocks.redirect).toHaveBeenCalledWith("/");
+ });
+});
+
+describe("createProjectForOnboardingAction", () => {
+ it("returns errors instead of throwing", async () => {
+ expect(await createProjectForOnboardingAction(form({}))).toEqual({
+ ok: false,
+ error: "Please enter a workspace name.",
+ });
+ const dup = await createProjectForOnboardingAction(
+ form({ display_name: "Fresh One" }),
+ );
+ expect(dup.ok).toBe(false);
+ });
+
+ it("persists onboarding hints and falls back on an unknown harness", async () => {
+ const r = await createProjectForOnboardingAction(
+ form({
+ display_name: "Onboard Co",
+ website_url: " https://onboard.co ",
+ codebase_path: "",
+ harness_adapter: "not-a-harness",
+ }),
+ );
+ expect(r).toEqual({
+ ok: true,
+ data: { slug: "onboard-co", display_name: "Onboard Co" },
+ });
+ expect(getProject("onboard-co")).toMatchObject({
+ website_url: "https://onboard.co",
+ codebase_path: null,
+ harness_adapter: "claude-code-local",
+ });
+ expect(mocks.cookieJar.get(COOKIE)).toBe("onboard-co");
+ });
+
+ it("honors a valid harness choice", async () => {
+ await createProjectForOnboardingAction(
+ form({ display_name: "Codex Shop", harness_adapter: "codex-local" }),
+ );
+ expect(getProject("codex-shop")?.harness_adapter).toBe("codex-local");
+ });
+});
+
+describe("switch / archive / rename actions", () => {
+ it("switchProjectAction repoints the cookie", async () => {
+ expect(await switchProjectAction("fresh-one")).toEqual({ ok: true, data: undefined });
+ expect(mocks.cookieJar.get(COOKIE)).toBe("fresh-one");
+ });
+
+ it("archiveProjectAction handles missing and existing projects", async () => {
+ expect(await archiveProjectAction("no-such")).toEqual({
+ ok: false,
+ error: "Project not found.",
+ });
+ createProject({ display_name: "Archive Target" });
+ expect(await archiveProjectAction("archive-target")).toEqual({
+ ok: true,
+ data: undefined,
+ });
+ expect(getProject("archive-target")?.archived_at).toBeTruthy();
+ });
+
+ it("renameProjectAction handles missing and existing projects", async () => {
+ expect(await renameProjectAction("no-such", "New")).toEqual({
+ ok: false,
+ error: "Project not found or name invalid.",
+ });
+ createProject({ display_name: "Rename Target" });
+ expect(await renameProjectAction("rename-target", "Renamed Target")).toEqual({
+ ok: true,
+ data: undefined,
+ });
+ expect(getProject("rename-target")?.display_name).toBe("Renamed Target");
+ });
+});
+
+describe("renameProjectFullAction", () => {
+ it("validates the project, name, and slug", async () => {
+ expect(
+ await renameProjectFullAction({ current_slug: "ghost", new_display_name: "X" }),
+ ).toEqual({ ok: false, error: "Project 'ghost' not found." });
+
+ createProject({ display_name: "Full Rename" });
+ expect(
+ await renameProjectFullAction({ current_slug: "full-rename", new_display_name: " " }),
+ ).toEqual({ ok: false, error: "Name cannot be empty." });
+ expect(
+ await renameProjectFullAction({ current_slug: "full-rename", new_display_name: "###" }),
+ ).toMatchObject({ ok: false });
+ });
+
+ it("no-ops when nothing changed and takes the cheap path for display-only", async () => {
+ const same = await renameProjectFullAction({
+ current_slug: "full-rename",
+ new_display_name: "Full Rename",
+ });
+ expect(same).toEqual({
+ ok: true,
+ data: {
+ slug: "full-rename",
+ display_name: "Full Rename",
+ full_rename: false,
+ agents_relocated: [],
+ agents_failed: [],
+ },
+ });
+
+ const display = await renameProjectFullAction({
+ current_slug: "full-rename",
+ new_display_name: "FULL rename", // same slug, new display name
+ });
+ expect(display).toMatchObject({
+ ok: true,
+ data: { slug: "full-rename", display_name: "FULL rename", full_rename: false },
+ });
+ expect(getProject("full-rename")?.display_name).toBe("FULL rename");
+ expect(mocks.relocateAgent).not.toHaveBeenCalled();
+ });
+
+ it("refuses to rename onto an existing slug", async () => {
+ createProject({ display_name: "Slug Squatter" });
+ expect(
+ await renameProjectFullAction({
+ current_slug: "full-rename",
+ new_display_name: "Slug Squatter",
+ }),
+ ).toEqual({ ok: false, error: "A project with slug 'slug-squatter' already exists." });
+ });
+
+ it("cascades: relocates agents, migrates rows, moves the brief, repoints the cookie", async () => {
+ mocks.cookieJar.set(COOKIE, "full-rename");
+ mocks.listProjectAgents.mockResolvedValue([
+ { agent_id: "full-rename-goal-1", slug: "goal-1", name: "Goal 1" },
+ { agent_id: "full-rename-goal-2", slug: "goal-2", name: "Goal 2" },
+ ]);
+ mocks.readAgentMeta.mockReturnValue({
+ source_agent_id: "origin-agent",
+ created_at: "2026-01-01T00:00:00.000Z",
+ });
+ mocks.relocateAgent
+ .mockResolvedValueOnce({ new_agent_id: "renamed-co-goal-1", new_slug: "goal-1" })
+ .mockRejectedValueOnce(new Error("workspace busy"));
+
+ const r = await renameProjectFullAction({
+ current_slug: "full-rename",
+ new_display_name: "Renamed Co",
+ });
+ expect(r).toEqual({
+ ok: true,
+ data: {
+ slug: "renamed-co",
+ display_name: "Renamed Co",
+ full_rename: true,
+ agents_relocated: ["full-rename-goal-1"],
+ agents_failed: [
+ { agent_id: "full-rename-goal-2", error: "workspace busy" },
+ ],
+ },
+ });
+ expect(mocks.relocateAgent).toHaveBeenCalledWith({
+ old_agent_id: "full-rename-goal-1",
+ source_project_slug: "full-rename",
+ new_project_slug: "renamed-co",
+ new_slug: "goal-1",
+ new_display_name: "Goal 1",
+ preserve_source_agent_id: "origin-agent",
+ preserve_created_at: "2026-01-01T00:00:00.000Z",
+ });
+ expect(getProject("full-rename")).toBeNull();
+ expect(getProject("renamed-co")?.display_name).toBe("Renamed Co");
+ expect(mocks.renameProjectBriefDir).toHaveBeenCalledWith("full-rename", "renamed-co");
+ expect(mocks.cookieJar.get(COOKIE)).toBe("renamed-co");
+ });
+});
+
+describe("getProjectDeletionSummaryAction", () => {
+ it("handles missing project, success, and summary failure", async () => {
+ expect(await getProjectDeletionSummaryAction("ghost")).toEqual({
+ ok: false,
+ error: "Project 'ghost' not found.",
+ });
+ createProject({ display_name: "Summary Me" });
+ expect(await getProjectDeletionSummaryAction("summary-me")).toEqual({
+ ok: true,
+ data: { agents: [], mcps: [] },
+ });
+ mocks.getProjectDeletionSummary.mockRejectedValueOnce(new Error("scan failed"));
+ expect(await getProjectDeletionSummaryAction("summary-me")).toEqual({
+ ok: false,
+ error: "scan failed",
+ });
+ });
+});
+
+describe("deleteProjectAction", () => {
+ it("requires a matching confirmation slug and an existing project", async () => {
+ expect(await deleteProjectAction("a", "b")).toEqual({
+ ok: false,
+ error: "Confirmation slug does not match.",
+ });
+ expect(await deleteProjectAction("ghost", "ghost")).toEqual({
+ ok: false,
+ error: "Project 'ghost' not found.",
+ });
+ });
+
+ it("cascades everything and clears the active-project cookie", async () => {
+ createProject({ display_name: "Doomed" });
+ const now = new Date().toISOString();
+ getDb()
+ .prepare(
+ `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)
+ VALUES ('doom-s1', 'doomed', 'doomed-goal-1', 'main', 'claude-code-local', ?, ?)`,
+ )
+ .run(now, now);
+ mocks.cookieJar.set(COOKIE, "doomed");
+ mocks.listProjectAgents.mockResolvedValue([{ agent_id: "doomed-goal-1" }]);
+ mocks.listProjectMcpTokens.mockReturnValue([{}, {}]);
+
+ const r = await deleteProjectAction("doomed", "doomed");
+ expect(r).toEqual({
+ ok: true,
+ data: { agents: ["doomed-goal-1"], agentsFailed: [], mcps: 2, mcpsFailed: 0 },
+ });
+ expect(mocks.cascadeDeleteProjectArtifacts).toHaveBeenCalledWith("doomed");
+ expect(mocks.deleteProjectBriefDir).toHaveBeenCalledWith("doomed");
+ expect(getProject("doomed")).toBeNull();
+ expect(mocks.cookieJar.has(COOKIE)).toBe(false);
+ });
+
+ it("records a cascade failure but still deletes the DB rows", async () => {
+ createProject({ display_name: "Doomed Two" });
+ mocks.cascadeDeleteProjectArtifacts.mockRejectedValueOnce(new Error("rm failed"));
+ const err = vi.spyOn(console, "error").mockImplementation(() => {});
+ try {
+ const r = await deleteProjectAction("doomed-two", "doomed-two");
+ expect(r).toMatchObject({
+ ok: true,
+ data: { agentsFailed: [{ agentId: "(project)", error: "rm failed" }] },
+ });
+ expect(getProject("doomed-two")).toBeNull();
+ } finally {
+ err.mockRestore();
+ }
+ });
+});
+
+describe("setProjectCodebasePathAction", () => {
+ it("validates slug, path existence, and directory-ness", async () => {
+ expect(
+ await setProjectCodebasePathAction({ project_slug: " ", codebase_path: "/x" }),
+ ).toEqual({ ok: false, error: "Missing project slug." });
+
+ const missing = join(h.dataDir, "does-not-exist");
+ expect(
+ await setProjectCodebasePathAction({ project_slug: "s", codebase_path: missing }),
+ ).toEqual({ ok: false, error: `Folder not found: ${missing}` });
+
+ const file = join(h.dataDir, "a-file.txt");
+ writeFileSync(file, "hi");
+ expect(
+ await setProjectCodebasePathAction({ project_slug: "s", codebase_path: file }),
+ ).toEqual({ ok: false, error: `Not a folder: ${file}` });
+ });
+
+ it("fails when the project row is missing", async () => {
+ const dir = join(h.dataDir, "repo");
+ mkdirSync(dir, { recursive: true });
+ expect(
+ await setProjectCodebasePathAction({ project_slug: "ghost", codebase_path: dir }),
+ ).toEqual({ ok: false, error: "Project not found." });
+ });
+
+ it("persists the folder and re-syncs agent identities", async () => {
+ createProject({ display_name: "Codebase Co" });
+ const dir = join(h.dataDir, "repo");
+ const r = await setProjectCodebasePathAction({
+ project_slug: "codebase-co",
+ codebase_path: ` ${dir} `,
+ });
+ expect(r).toEqual({ ok: true, codebase_path: dir });
+ expect(mocks.syncProjectAgents).toHaveBeenCalledWith("codebase-co");
+ expect(getProject("codebase-co")?.codebase_path).toBe(dir);
+ });
+
+ it("clears the path and tolerates a failing identity sync", async () => {
+ mocks.syncProjectAgents.mockRejectedValueOnce(new Error("render broke"));
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const r = await setProjectCodebasePathAction({
+ project_slug: "codebase-co",
+ codebase_path: " ",
+ });
+ expect(r).toEqual({ ok: true, codebase_path: null });
+ } finally {
+ warn.mockRestore();
+ }
+ });
+});
diff --git a/notfair/src/server/active-project.test.ts b/notfair/src/server/active-project.test.ts
new file mode 100644
index 00000000..9bb12820
--- /dev/null
+++ b/notfair/src/server/active-project.test.ts
@@ -0,0 +1,111 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Project } from "@/types";
+
+// Mock at the framework / db-module boundary per repo conventions: this
+// module is pure cookie orchestration around the projects db module.
+const mocks = vi.hoisted(() => ({
+ cookieGet: vi.fn<(name: string) => { value: string } | undefined>(),
+ cookieSet: vi.fn(),
+ cookieDelete: vi.fn(),
+ getProject: vi.fn<(slug: string) => Project | null>(),
+ listProjects: vi.fn<() => Project[]>(),
+}));
+
+vi.mock("next/headers", () => ({
+ cookies: async () => ({
+ get: mocks.cookieGet,
+ set: mocks.cookieSet,
+ delete: mocks.cookieDelete,
+ }),
+}));
+vi.mock("./db/projects", () => ({
+ getProject: mocks.getProject,
+ listProjects: mocks.listProjects,
+}));
+
+import {
+ clearActiveProject,
+ getActiveProject,
+ setActiveProject,
+} from "./active-project";
+
+function project(slug: string, archived_at: string | null = null): Project {
+ return {
+ id: `id-${slug}`,
+ slug,
+ display_name: slug,
+ created_at: "2026-01-01T00:00:00.000Z",
+ archived_at,
+ google_ads_account_id: null,
+ meta_ads_account_id: null,
+ gsc_property_id: null,
+ website_url: null,
+ codebase_path: null,
+ harness_adapter: "claude-code-local",
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("getActiveProject", () => {
+ it("returns the cookie's project when it exists and isn't archived", async () => {
+ mocks.cookieGet.mockReturnValue({ value: "acme" });
+ mocks.getProject.mockReturnValue(project("acme"));
+
+ await expect(getActiveProject()).resolves.toMatchObject({ slug: "acme" });
+ expect(mocks.getProject).toHaveBeenCalledWith("acme");
+ expect(mocks.listProjects).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the first listed project when the cookie project is archived", async () => {
+ mocks.cookieGet.mockReturnValue({ value: "old" });
+ mocks.getProject.mockReturnValue(project("old", "2026-01-02T00:00:00.000Z"));
+ mocks.listProjects.mockReturnValue([project("fresh")]);
+
+ await expect(getActiveProject()).resolves.toMatchObject({ slug: "fresh" });
+ });
+
+ it("falls back when the cookie names a deleted project", async () => {
+ mocks.cookieGet.mockReturnValue({ value: "ghost" });
+ mocks.getProject.mockReturnValue(null);
+ mocks.listProjects.mockReturnValue([project("fresh")]);
+
+ await expect(getActiveProject()).resolves.toMatchObject({ slug: "fresh" });
+ });
+
+ it("falls back to the first project when no cookie is set", async () => {
+ mocks.cookieGet.mockReturnValue(undefined);
+ mocks.listProjects.mockReturnValue([project("a"), project("b")]);
+
+ await expect(getActiveProject()).resolves.toMatchObject({ slug: "a" });
+ expect(mocks.getProject).not.toHaveBeenCalled();
+ });
+
+ it("returns null when there are no projects at all", async () => {
+ mocks.cookieGet.mockReturnValue(undefined);
+ mocks.listProjects.mockReturnValue([]);
+
+ await expect(getActiveProject()).resolves.toBeNull();
+ });
+});
+
+describe("setActiveProject", () => {
+ it("writes a year-long httpOnly cookie", async () => {
+ await setActiveProject("acme");
+ expect(mocks.cookieSet).toHaveBeenCalledWith("notfair_active_project", "acme", {
+ httpOnly: true,
+ sameSite: "lax",
+ path: "/",
+ maxAge: 60 * 60 * 24 * 365,
+ });
+ });
+});
+
+describe("clearActiveProject", () => {
+ it("deletes the cookie", async () => {
+ await clearActiveProject();
+ expect(mocks.cookieDelete).toHaveBeenCalledWith("notfair_active_project");
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/execute.test.ts b/notfair/src/server/adapters/claude-code-local/execute.test.ts
new file mode 100644
index 00000000..6094629e
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/execute.test.ts
@@ -0,0 +1,202 @@
+import { EventEmitter } from "node:events";
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { HarnessEvent, HarnessExecuteContext } from "../types";
+
+const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+
+import { executeClaudeCodeLocal } from "./execute";
+
+class FakeChild extends EventEmitter {
+ stdin = { write: vi.fn(), end: vi.fn() };
+ stdout = new PassThrough();
+ stderr = new PassThrough();
+ kill = vi.fn();
+}
+
+interface Script {
+ stdout?: string;
+ stderr?: string;
+ exitCode?: number;
+ spawnError?: Error;
+}
+
+/** Mock spawn to return a scripted child; returns the child for inspection. */
+function scriptSpawn(script: Script): FakeChild {
+ const child = new FakeChild();
+ mocks.spawn.mockImplementationOnce(() => {
+ setImmediate(async () => {
+ if (script.spawnError) {
+ child.emit("error", script.spawnError);
+ return;
+ }
+ if (script.stdout) child.stdout.write(script.stdout);
+ if (script.stderr) child.stderr.write(script.stderr);
+ // Let PassThrough flush data events before the close lands.
+ await new Promise((r) => setTimeout(r, 15));
+ child.emit("close", script.exitCode ?? 0);
+ });
+ return child;
+ });
+ return child;
+}
+
+async function collect(ctx: HarnessExecuteContext): Promise<HarnessEvent[]> {
+ const events: HarnessEvent[] = [];
+ for await (const evt of executeClaudeCodeLocal(ctx)) events.push(evt);
+ return events;
+}
+
+let workspaceDir: string;
+
+function ctx(overrides: Partial<HarnessExecuteContext> = {}): HarnessExecuteContext {
+ return {
+ projectSlug: "proj",
+ agentId: "agent-1",
+ workspaceDir,
+ message: "hi there",
+ threadId: "thread-1",
+ ...overrides,
+ };
+}
+
+beforeEach(async () => {
+ mocks.spawn.mockReset();
+ workspaceDir = await mkdtemp(join(tmpdir(), "notfair-claude-exec-"));
+});
+
+describe("executeClaudeCodeLocal — argv wiring", () => {
+ it("spawns claude in stream-json mode and pipes the message on stdin", async () => {
+ const child = scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });
+ const events = await collect(ctx());
+
+ expect(mocks.spawn).toHaveBeenCalledTimes(1);
+ const [bin, args, opts] = mocks.spawn.mock.calls[0]!;
+ expect(bin).toBe("claude");
+ expect(args).toEqual([
+ "--print",
+ "--output-format",
+ "stream-json",
+ "--input-format",
+ "text",
+ "--verbose",
+ ]);
+ expect(opts).toMatchObject({
+ cwd: workspaceDir,
+ env: expect.objectContaining({
+ NOTFAIR_PROJECT_SLUG: "proj",
+ NOTFAIR_AGENT_ID: "agent-1",
+ }),
+ });
+ expect(child.stdin.write).toHaveBeenCalledWith("hi there");
+ expect(child.stdin.end).toHaveBeenCalled();
+ expect(events).toEqual([
+ { kind: "delta", text: "ok" },
+ { kind: "final", text: "ok" },
+ ]);
+ });
+
+ it("appends IDENTITY.md as the system prompt when present", async () => {
+ await writeFile(join(workspaceDir, "IDENTITY.md"), "# You are Greg\n", "utf8");
+ scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });
+ await collect(ctx());
+
+ const args = mocks.spawn.mock.calls[0]![1] as string[];
+ const idx = args.indexOf("--append-system-prompt");
+ expect(idx).toBeGreaterThan(-1);
+ expect(args[idx + 1]).toBe("# You are Greg\n");
+ });
+
+ it("passes the model override and resumes real claude session ids", async () => {
+ scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });
+ const uuid = "123e4567-e89b-42d3-a456-426614174000";
+ await collect(ctx({ model: "opus", harnessSessionId: uuid }));
+
+ const args = mocks.spawn.mock.calls[0]![1] as string[];
+ expect(args).toContain("--model");
+ expect(args[args.indexOf("--model") + 1]).toBe("opus");
+ expect(args[args.indexOf("--resume") + 1]).toBe(uuid);
+ });
+
+ it("never passes a non-UUID session id to --resume", async () => {
+ scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });
+ await collect(ctx({ harnessSessionId: "not-a-claude-session" }));
+
+ expect(mocks.spawn.mock.calls[0]![1]).not.toContain("--resume");
+ });
+});
+
+describe("executeClaudeCodeLocal — stream handling", () => {
+ it("forwards parsed events across chunk boundaries and flushes the tail line", async () => {
+ const l1 = JSON.stringify({
+ type: "system",
+ subtype: "init",
+ session_id: "123e4567-e89b-42d3-a456-426614174000",
+ });
+ const l2 = JSON.stringify({
+ type: "assistant",
+ message: { content: [{ type: "text", text: "hello" }] },
+ });
+ // Final line has no trailing newline — must be flushed on close.
+ const l3 = JSON.stringify({ type: "result", result: "hello" });
+ scriptSpawn({ stdout: `${l1}\n${l2}\n${l3}` });
+
+ const events = await collect(ctx());
+ expect(events).toEqual([
+ { kind: "lifecycle", phase: "init" },
+ { kind: "session", harnessSessionId: "123e4567-e89b-42d3-a456-426614174000" },
+ { kind: "delta", text: "hello" },
+ { kind: "final", text: "hello" },
+ ]);
+ });
+
+ it("emits an error with the stderr tail on a non-zero exit without a final", async () => {
+ scriptSpawn({ exitCode: 1, stderr: "line1\nauth expired\n" });
+ const events = await collect(ctx());
+ expect(events).toEqual([
+ { kind: "error", message: "claude exited with code 1: line1\nauth expired" },
+ ]);
+ });
+
+ it("suppresses the exit-code error when the turn already finalized", async () => {
+ scriptSpawn({
+ stdout: `${JSON.stringify({ type: "result", result: "done" })}\n`,
+ exitCode: 1,
+ });
+ const events = await collect(ctx());
+ expect(events).toEqual([
+ { kind: "delta", text: "done" },
+ { kind: "final", text: "done" },
+ ]);
+ });
+
+ it("yields a terminal error when the binary fails to spawn", async () => {
+ scriptSpawn({ spawnError: new Error("spawn claude ENOENT") });
+ const events = await collect(ctx());
+ expect(events).toEqual([{ kind: "error", message: "spawn claude ENOENT" }]);
+ });
+
+ it("kills the subprocess when the abort signal fires", async () => {
+ const controller = new AbortController();
+ const child = new FakeChild();
+ child.kill = vi.fn(() => {
+ child.emit("close", 143);
+ return true;
+ });
+ mocks.spawn.mockImplementationOnce(() => {
+ setImmediate(() => controller.abort());
+ return child;
+ });
+
+ const events = await collect(ctx({ signal: controller.signal }));
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(events).toEqual([
+ { kind: "error", message: "claude exited with code 143" },
+ ]);
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/index.test.ts b/notfair/src/server/adapters/claude-code-local/index.test.ts
new file mode 100644
index 00000000..963cd3a8
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/index.test.ts
@@ -0,0 +1,77 @@
+import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+
+// dataDir() reads NOTFAIR_DATA_DIR at call time, but hoist anyway so no code
+// path in the import graph can ever resolve to the developer's live ~/.notfair.
+const tmpDataDir = 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");
+ const dir = mkdtempSync(join(tmpdir(), "notfair-claude-index-"));
+ process.env.NOTFAIR_DATA_DIR = dir;
+ return dir;
+});
+
+const mocks = vi.hoisted(() => ({
+ executeClaudeCodeLocal: vi.fn(),
+ listClaudeCodeModels: vi.fn(async () => []),
+ provisionClaudeCodeAgent: vi.fn(async () => {}),
+ testClaudeCodeLocalEnvironment: vi.fn(async () => ({ ok: true })),
+ registerClaudeCodeMcp: vi.fn(async () => {}),
+ unregisterClaudeCodeMcp: vi.fn(async () => {}),
+}));
+
+vi.mock("./execute", () => ({ executeClaudeCodeLocal: mocks.executeClaudeCodeLocal }));
+vi.mock("./models", () => ({ listClaudeCodeModels: mocks.listClaudeCodeModels }));
+vi.mock("./provision", () => ({ provisionClaudeCodeAgent: mocks.provisionClaudeCodeAgent }));
+vi.mock("./test", () => ({ testClaudeCodeLocalEnvironment: mocks.testClaudeCodeLocalEnvironment }));
+vi.mock("./mcp", () => ({
+ registerClaudeCodeMcp: mocks.registerClaudeCodeMcp,
+ unregisterClaudeCodeMcp: mocks.unregisterClaudeCodeMcp,
+}));
+
+import { claudeCodeLocalAdapter } from "./index";
+
+describe("claudeCodeLocalAdapter", () => {
+ it("exposes the claude-code-local id and delegates to the submodules", async () => {
+ expect(claudeCodeLocalAdapter.id).toBe("claude-code-local");
+ expect(claudeCodeLocalAdapter.testEnvironment).toBe(
+ mocks.testClaudeCodeLocalEnvironment,
+ );
+ expect(claudeCodeLocalAdapter.listModels).toBe(mocks.listClaudeCodeModels);
+
+ const ctx = { agentId: "a" } as never;
+ const gen = (async function* () {})();
+ mocks.executeClaudeCodeLocal.mockReturnValueOnce(gen);
+ expect(claudeCodeLocalAdapter.execute(ctx)).toBe(gen);
+ expect(mocks.executeClaudeCodeLocal).toHaveBeenCalledWith(ctx);
+
+ const provisionSpec = { agentId: "a" } as never;
+ await claudeCodeLocalAdapter.provisionAgent(provisionSpec);
+ expect(mocks.provisionClaudeCodeAgent).toHaveBeenCalledWith(provisionSpec);
+ });
+
+ it("registers MCP into the agent's workspace under the data dir", async () => {
+ const spec = {
+ serverName: "notfair-goals",
+ agentId: "agent-9",
+ projectSlug: "proj",
+ transport: { type: "http" as const, url: "http://x" },
+ };
+ await claudeCodeLocalAdapter.registerMcp(spec);
+ expect(mocks.registerClaudeCodeMcp).toHaveBeenCalledWith(
+ join(tmpDataDir, "agents", "agent-9"),
+ spec,
+ );
+
+ await claudeCodeLocalAdapter.unregisterMcp({
+ serverName: "notfair-goals",
+ projectSlug: "proj",
+ agentId: "agent-9",
+ });
+ expect(mocks.unregisterClaudeCodeMcp).toHaveBeenCalledWith(
+ join(tmpDataDir, "agents", "agent-9"),
+ "notfair-goals",
+ );
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/mcp.test.ts b/notfair/src/server/adapters/claude-code-local/mcp.test.ts
new file mode 100644
index 00000000..41ba6334
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/mcp.test.ts
@@ -0,0 +1,105 @@
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import type { McpRegistrationSpec } from "../types";
+import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";
+
+let workspaceDir: string;
+
+beforeEach(async () => {
+ workspaceDir = await mkdtemp(join(tmpdir(), "notfair-claude-mcp-"));
+});
+
+function spec(overrides: Partial<McpRegistrationSpec> = {}): McpRegistrationSpec {
+ return {
+ serverName: "notfair-goals",
+ agentId: "agent-1",
+ projectSlug: "proj",
+ transport: { type: "http", url: "http://127.0.0.1:3326/api/mcp/goals" },
+ ...overrides,
+ };
+}
+
+async function readMcpJson(): Promise<{ mcpServers: Record<string, unknown> }> {
+ return JSON.parse(await readFile(join(workspaceDir, ".mcp.json"), "utf8"));
+}
+
+describe("registerClaudeCodeMcp", () => {
+ it("writes an http server entry into .mcp.json", async () => {
+ await registerClaudeCodeMcp(
+ workspaceDir,
+ spec({
+ transport: {
+ type: "http",
+ url: "http://127.0.0.1:3326/api/mcp/goals",
+ headers: { Authorization: "Bearer s3cret" },
+ },
+ }),
+ );
+ expect(await readMcpJson()).toEqual({
+ mcpServers: {
+ "notfair-goals": {
+ type: "http",
+ url: "http://127.0.0.1:3326/api/mcp/goals",
+ headers: { Authorization: "Bearer s3cret" },
+ },
+ },
+ });
+ });
+
+ it("writes a stdio server entry with command, args and env", async () => {
+ await registerClaudeCodeMcp(
+ workspaceDir,
+ spec({
+ serverName: "local-tool",
+ transport: {
+ type: "stdio",
+ command: "node",
+ args: ["server.js"],
+ env: { TOKEN: "t" },
+ },
+ }),
+ );
+ expect((await readMcpJson()).mcpServers["local-tool"]).toEqual({
+ type: "stdio",
+ command: "node",
+ args: ["server.js"],
+ env: { TOKEN: "t" },
+ });
+ });
+
+ it("creates the workspace dir when it does not exist yet", async () => {
+ const fresh = join(workspaceDir, "nested", "agent");
+ await registerClaudeCodeMcp(fresh, spec());
+ const parsed = JSON.parse(await readFile(join(fresh, ".mcp.json"), "utf8"));
+ expect(Object.keys(parsed.mcpServers)).toEqual(["notfair-goals"]);
+ });
+
+ it("merges with existing servers instead of clobbering them", async () => {
+ await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "a" }));
+ await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "b" }));
+ expect(Object.keys((await readMcpJson()).mcpServers).sort()).toEqual(["a", "b"]);
+ });
+
+ it("recovers from a corrupt .mcp.json by starting fresh", async () => {
+ await writeFile(join(workspaceDir, ".mcp.json"), "{ not json", "utf8");
+ await registerClaudeCodeMcp(workspaceDir, spec());
+ expect(Object.keys((await readMcpJson()).mcpServers)).toEqual(["notfair-goals"]);
+ });
+});
+
+describe("unregisterClaudeCodeMcp", () => {
+ it("removes only the named server", async () => {
+ await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "a" }));
+ await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "b" }));
+ await unregisterClaudeCodeMcp(workspaceDir, "a");
+ expect(Object.keys((await readMcpJson()).mcpServers)).toEqual(["b"]);
+ });
+
+ it("is a no-op (but still writes a valid file) when the server is absent", async () => {
+ await unregisterClaudeCodeMcp(workspaceDir, "ghost");
+ expect(await readMcpJson()).toEqual({ mcpServers: {} });
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/models.test.ts b/notfair/src/server/adapters/claude-code-local/models.test.ts
new file mode 100644
index 00000000..1b5572bf
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/models.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+
+import { listClaudeCodeModels } from "./models";
+
+describe("listClaudeCodeModels", () => {
+ it("returns the stable CLI alias tiers with documented context windows", async () => {
+ const models = await listClaudeCodeModels();
+ expect(models.map((m) => m.value)).toEqual(["fable", "opus", "sonnet", "haiku"]);
+ for (const model of models) {
+ expect(model.label.length).toBeGreaterThan(0);
+ expect(model.context_window).toBe(200_000);
+ }
+ // No alias is marked default — omitting the flag is the CLI's own choice.
+ expect(models.some((m) => m.is_default)).toBe(false);
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/parse.test.ts b/notfair/src/server/adapters/claude-code-local/parse.test.ts
new file mode 100644
index 00000000..c2f104f5
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/parse.test.ts
@@ -0,0 +1,269 @@
+import { describe, expect, it } from "vitest";
+
+import { makeClaudeStreamState, parseClaudeLine } from "./parse";
+
+const line = (obj: unknown) => JSON.stringify(obj);
+
+describe("parseClaudeLine — noise handling", () => {
+ it("ignores blank lines and invalid JSON", () => {
+ const state = makeClaudeStreamState();
+ expect(parseClaudeLine("", state)).toEqual([]);
+ expect(parseClaudeLine(" ", state)).toEqual([]);
+ expect(parseClaudeLine("not json {", state)).toEqual([]);
+ });
+
+ it("ignores unknown message types", () => {
+ expect(
+ parseClaudeLine(line({ type: "mystery" }), makeClaudeStreamState()),
+ ).toEqual([]);
+ });
+});
+
+describe("parseClaudeLine — system events", () => {
+ it("emits lifecycle + session from the init system message", () => {
+ const state = makeClaudeStreamState();
+ const events = parseClaudeLine(
+ line({ type: "system", subtype: "init", session_id: "sess-1" }),
+ state,
+ );
+ expect(events).toEqual([
+ { kind: "lifecycle", phase: "init" },
+ { kind: "session", harnessSessionId: "sess-1" },
+ ]);
+ });
+
+ it("emits the session event at most once per turn", () => {
+ const state = makeClaudeStreamState();
+ parseClaudeLine(line({ type: "system", subtype: "init", session_id: "sess-1" }), state);
+ const events = parseClaudeLine(
+ line({ type: "system", subtype: "other", session_id: "sess-1" }),
+ state,
+ );
+ expect(events).toEqual([{ kind: "lifecycle", phase: "other" }]);
+ });
+
+ it("skips lifecycle when subtype is missing", () => {
+ const events = parseClaudeLine(
+ line({ type: "system", session_id: "sess-2" }),
+ makeClaudeStreamState(),
+ );
+ expect(events).toEqual([{ kind: "session", harnessSessionId: "sess-2" }]);
+ });
+});
+
+describe("parseClaudeLine — assistant text", () => {
+ it("forwards text blocks as deltas", () => {
+ const state = makeClaudeStreamState();
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: { content: [{ type: "text", text: "Hello " }, { type: "text", text: "world" }] },
+ }),
+ state,
+ );
+ expect(events).toEqual([
+ { kind: "delta", text: "Hello " },
+ { kind: "delta", text: "world" },
+ ]);
+ expect(state.assistantText).toBe("Hello world");
+ });
+
+ it("keeps deltas monotonic across messages", () => {
+ const state = makeClaudeStreamState();
+ parseClaudeLine(
+ line({ type: "assistant", message: { content: [{ type: "text", text: "part one" }] } }),
+ state,
+ );
+ const events = parseClaudeLine(
+ line({ type: "assistant", message: { content: [{ type: "text", text: " part two" }] } }),
+ state,
+ );
+ expect(events).toEqual([{ kind: "delta", text: " part two" }]);
+ });
+});
+
+describe("parseClaudeLine — tool events", () => {
+ it("emits a tool start with a first-line label for Bash commands", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: {
+ content: [
+ {
+ type: "tool_use",
+ id: "tu_1",
+ name: "Bash",
+ input: { command: "ls -la\ncat foo" },
+ },
+ ],
+ },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(events).toEqual([
+ { kind: "tool", phase: "start", toolCallId: "tu_1", name: "Bash", label: "ls -la" },
+ ]);
+ });
+
+ it("clips a very long Bash first line to 160 chars", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: {
+ content: [
+ { type: "tool_use", id: "tu_2", name: "Bash", input: { command: "x".repeat(200) } },
+ ],
+ },
+ }),
+ makeClaudeStreamState(),
+ );
+ const label = (events[0] as { label: string }).label;
+ expect(label).toHaveLength(160);
+ expect(label.endsWith("…")).toBe(true);
+ });
+
+ it("shortens deep file paths to the last two segments", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: {
+ content: [
+ {
+ type: "tool_use",
+ id: "tu_3",
+ name: "Read",
+ input: { file_path: "/Users/x/proj/src/foo.ts" },
+ },
+ ],
+ },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(events[0]).toMatchObject({ label: "…/src/foo.ts" });
+ });
+
+ it("keeps short paths whole", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: {
+ content: [{ type: "tool_use", id: "tu_4", name: "Read", input: { path: "foo.ts" } }],
+ },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(events[0]).toMatchObject({ label: "foo.ts" });
+ });
+
+ it("uses the URL as the label for web tools", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: {
+ content: [
+ { type: "tool_use", id: "tu_5", name: "WebFetch", input: { url: "https://x.test/a" } },
+ ],
+ },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(events[0]).toMatchObject({ label: "https://x.test/a" });
+ });
+
+ it("falls back to labelFromArgs for MCP-ish tools", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "assistant",
+ message: {
+ content: [
+ {
+ type: "tool_use",
+ id: "tu_6",
+ name: "mcp__x__updateBudget",
+ input: { campaign_id: 9, amount: 5 },
+ },
+ ],
+ },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(events[0]).toMatchObject({ label: "campaign_id=9 amount=5" });
+ });
+
+ it("defaults toolCallId and name when absent, label undefined without input", () => {
+ const events = parseClaudeLine(
+ line({ type: "assistant", message: { content: [{ type: "tool_use" }] } }),
+ makeClaudeStreamState(),
+ );
+ expect(events[0]).toMatchObject({ kind: "tool", toolCallId: "", name: "tool" });
+ expect((events[0] as { label?: string }).label).toBeUndefined();
+ });
+
+ it("surfaces tool_result blocks in user messages as result events", () => {
+ const events = parseClaudeLine(
+ line({
+ type: "user",
+ message: { content: [{ type: "tool_result", tool_use_id: "tu_1" }, { type: "text" }] },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(events).toEqual([
+ { kind: "tool", phase: "result", toolCallId: "tu_1", name: "" },
+ ]);
+ });
+});
+
+describe("parseClaudeLine — result", () => {
+ it("emits final with the result text and marks the state finalized", () => {
+ const state = makeClaudeStreamState();
+ parseClaudeLine(
+ line({ type: "assistant", message: { content: [{ type: "text", text: "done" }] } }),
+ state,
+ );
+ const events = parseClaudeLine(line({ type: "result", result: "done" }), state);
+ expect(events).toEqual([{ kind: "final", text: "done" }]);
+ expect(state.finalized).toBe(true);
+ });
+
+ it("emits a trailing delta when the result text extends past emitted deltas", () => {
+ const state = makeClaudeStreamState();
+ const events = parseClaudeLine(
+ line({ type: "result", result: "full answer" }),
+ state,
+ );
+ expect(events).toEqual([
+ { kind: "delta", text: "full answer" },
+ { kind: "final", text: "full answer" },
+ ]);
+ });
+
+ it("falls back to accumulated assistant text when result is not a string", () => {
+ const state = makeClaudeStreamState();
+ parseClaudeLine(
+ line({ type: "assistant", message: { content: [{ type: "text", text: "acc" }] } }),
+ state,
+ );
+ const events = parseClaudeLine(line({ type: "result" }), state);
+ expect(events).toEqual([{ kind: "final", text: "acc" }]);
+ });
+
+ it("maps error subtypes to error events", () => {
+ const state = makeClaudeStreamState();
+ const events = parseClaudeLine(
+ line({ type: "result", subtype: "error_max_turns" }),
+ state,
+ );
+ expect(events).toEqual([{ kind: "error", message: "error_max_turns" }]);
+ expect(state.finalized).toBe(true);
+
+ const withMessage = parseClaudeLine(
+ line({
+ type: "result",
+ subtype: "error_during_execution",
+ error: { message: "boom" },
+ }),
+ makeClaudeStreamState(),
+ );
+ expect(withMessage).toEqual([{ kind: "error", message: "boom" }]);
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/provision.test.ts b/notfair/src/server/adapters/claude-code-local/provision.test.ts
new file mode 100644
index 00000000..b380f12d
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/provision.test.ts
@@ -0,0 +1,55 @@
+import { existsSync } from "node:fs";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import type { AgentProvisionSpec } from "../types";
+import { provisionClaudeCodeAgent } from "./provision";
+
+let workspaceDir: string;
+
+beforeEach(async () => {
+ workspaceDir = await mkdtemp(join(tmpdir(), "notfair-claude-prov-"));
+});
+
+function spec(overrides: Partial<AgentProvisionSpec> = {}): AgentProvisionSpec {
+ return {
+ projectSlug: "proj",
+ agentId: "proj-goal-1",
+ displayName: "Greg",
+ templateKey: "goal",
+ workspaceDir,
+ identityMd: "# Greg identity\n",
+ ...overrides,
+ };
+}
+
+describe("provisionClaudeCodeAgent", () => {
+ it("writes IDENTITY.md and a pointer CLAUDE.md (not a mirror)", async () => {
+ await provisionClaudeCodeAgent(spec());
+ expect(await readFile(join(workspaceDir, "IDENTITY.md"), "utf8")).toBe(
+ "# Greg identity\n",
+ );
+ const claudeMd = await readFile(join(workspaceDir, "CLAUDE.md"), "utf8");
+ expect(claudeMd).toContain("IDENTITY.md");
+ expect(claudeMd).not.toContain("# Greg identity");
+ });
+
+ it("writes PROJECT.md only when a project brief exists", async () => {
+ await provisionClaudeCodeAgent(spec());
+ expect(existsSync(join(workspaceDir, "PROJECT.md"))).toBe(false);
+
+ await provisionClaudeCodeAgent(spec({ projectMd: "# Brief\n" }));
+ expect(await readFile(join(workspaceDir, "PROJECT.md"), "utf8")).toBe("# Brief\n");
+ });
+
+ it("creates the workspace dir and removes a stale SKILL.md sidecar", async () => {
+ await writeFile(join(workspaceDir, "SKILL.md"), "old skill", "utf8");
+ const nested = join(workspaceDir, "sub", "agent");
+ await provisionClaudeCodeAgent(spec());
+ await provisionClaudeCodeAgent(spec({ workspaceDir: nested }));
+ expect(existsSync(join(workspaceDir, "SKILL.md"))).toBe(false);
+ expect(existsSync(join(nested, "IDENTITY.md"))).toBe(true);
+ });
+});
diff --git a/notfair/src/server/adapters/claude-code-local/test.test.ts b/notfair/src/server/adapters/claude-code-local/test.test.ts
new file mode 100644
index 00000000..ccecb232
--- /dev/null
+++ b/notfair/src/server/adapters/claude-code-local/test.test.ts
@@ -0,0 +1,83 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+
+import { testClaudeCodeLocalEnvironment } from "./test";
+
+class FakeChild extends EventEmitter {
+ stdout = new PassThrough();
+ stderr = new PassThrough();
+ kill = vi.fn();
+}
+
+function scriptVersionCmd(script: {
+ stdout?: string;
+ exitCode?: number;
+ spawnError?: boolean;
+ hang?: boolean;
+}): FakeChild {
+ const child = new FakeChild();
+ mocks.spawn.mockImplementationOnce(() => {
+ if (!script.hang) {
+ setImmediate(() => {
+ if (script.spawnError) {
+ child.emit("error", new Error("ENOENT"));
+ return;
+ }
+ if (script.stdout) child.stdout.emit("data", Buffer.from(script.stdout));
+ child.emit("close", script.exitCode ?? 0);
+ });
+ }
+ return child;
+ });
+ return child;
+}
+
+beforeEach(() => mocks.spawn.mockReset());
+afterEach(() => vi.useRealTimers());
+
+describe("testClaudeCodeLocalEnvironment", () => {
+ it("reports ok with a parsed version label when the CLI responds", async () => {
+ scriptVersionCmd({ stdout: "1.0.42 (Claude Code)\n" });
+ const health = await testClaudeCodeLocalEnvironment();
+ expect(health).toEqual({
+ ok: true,
+ auth: "unknown",
+ versionLabel: "Claude Code 1.0.42",
+ });
+ expect(mocks.spawn).toHaveBeenCalledWith("claude", ["--version"], expect.anything());
+ });
+
+ it("falls back to a bare label when the version string is unparsable", async () => {
+ scriptVersionCmd({ stdout: "dev build\n" });
+ const health = await testClaudeCodeLocalEnvironment();
+ expect(health.versionLabel).toBe("Claude Code");
+ });
+
+ it("reports not-ok with an install hint when the binary is missing", async () => {
+ scriptVersionCmd({ spawnError: true });
+ const health = await testClaudeCodeLocalEnvironment();
+ expect(health.ok).toBe(false);
+ expect(health.auth).toBe("unknown");
+ expect(health.message).toContain("`claude` not found on PATH");
+ });
+
+ it("reports not-ok on a non-zero exit code", async () => {
+ scriptVersionCmd({ exitCode: 3 });
+ const health = await testClaudeCodeLocalEnvironment();
+ expect(health.ok).toBe(false);
+ });
+
+ it("times out a hung probe instead of waiting forever", async () => {
+ vi.useFakeTimers();
+ const child = scriptVersionCmd({ hang: true });
+ const pending = testClaudeCodeLocalEnvironment();
+ await vi.advanceTimersByTimeAsync(5_001);
+ const health = await pending;
+ expect(health.ok).toBe(false);
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/execute.test.ts b/notfair/src/server/adapters/codex-local/execute.test.ts
new file mode 100644
index 00000000..c5561b00
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/execute.test.ts
@@ -0,0 +1,198 @@
+import { EventEmitter } from "node:events";
+import { mkdtemp } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { HarnessEvent, HarnessExecuteContext } from "../types";
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ getOrCreateMcpServerSecret: vi.fn(() => "machine-secret"),
+ listProjectMcpTokens: vi.fn(() => [] as { server_name: string; access_token_enc: string }[]),
+}));
+
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+vi.mock("@/server/mcp-server/secret", () => ({
+ getOrCreateMcpServerSecret: mocks.getOrCreateMcpServerSecret,
+}));
+vi.mock("@/server/mcp/tokens", () => ({
+ listProjectMcpTokens: mocks.listProjectMcpTokens,
+}));
+
+import { executeCodexLocal } from "./execute";
+
+class FakeChild extends EventEmitter {
+ stdin = { write: vi.fn(), end: vi.fn() };
+ stdout = new PassThrough();
+ stderr = new PassThrough();
+ kill = vi.fn();
+}
+
+interface Script {
+ stdout?: string;
+ stderr?: string;
+ exitCode?: number;
+ spawnError?: Error;
+}
+
+function scriptSpawn(script: Script): FakeChild {
+ const child = new FakeChild();
+ mocks.spawn.mockImplementationOnce(() => {
+ setImmediate(async () => {
+ if (script.spawnError) {
+ child.emit("error", script.spawnError);
+ return;
+ }
+ if (script.stdout) child.stdout.write(script.stdout);
+ if (script.stderr) child.stderr.write(script.stderr);
+ await new Promise((r) => setTimeout(r, 15));
+ child.emit("close", script.exitCode ?? 0);
+ });
+ return child;
+ });
+ return child;
+}
+
+async function collect(ctx: HarnessExecuteContext): Promise<HarnessEvent[]> {
+ const events: HarnessEvent[] = [];
+ for await (const evt of executeCodexLocal(ctx)) events.push(evt);
+ return events;
+}
+
+let workspaceDir: string;
+
+function ctx(overrides: Partial<HarnessExecuteContext> = {}): HarnessExecuteContext {
+ return {
+ projectSlug: "proj",
+ agentId: "agent-1",
+ workspaceDir,
+ message: "do the thing",
+ threadId: "thread-1",
+ ...overrides,
+ };
+}
+
+const completedTurn =
+ `${JSON.stringify({ type: "item.completed", item: { type: "agent_message", text: "ok" } })}\n` +
+ `${JSON.stringify({ type: "turn.completed" })}\n`;
+
+beforeEach(async () => {
+ mocks.spawn.mockReset();
+ mocks.listProjectMcpTokens.mockReturnValue([]);
+ workspaceDir = await mkdtemp(join(tmpdir(), "notfair-codex-exec-"));
+});
+
+describe("executeCodexLocal — argv and env wiring", () => {
+ it("spawns codex exec --json unsandboxed with stdin prompt", async () => {
+ const child = scriptSpawn({ stdout: completedTurn });
+ const events = await collect(ctx());
+
+ const [bin, args, opts] = mocks.spawn.mock.calls[0]!;
+ expect(bin).toBe("codex");
+ expect(args).toEqual([
+ "exec",
+ "--json",
+ "--skip-git-repo-check",
+ "--dangerously-bypass-approvals-and-sandbox",
+ "-",
+ ]);
+ expect(opts).toMatchObject({ cwd: workspaceDir });
+ expect(child.stdin.write).toHaveBeenCalledWith("do the thing");
+ expect(child.stdin.end).toHaveBeenCalled();
+ expect(events).toEqual([
+ { kind: "delta", text: "ok" },
+ { kind: "final", text: "ok" },
+ ]);
+ });
+
+ it("injects one bearer env var per MCP server for the project", async () => {
+ mocks.listProjectMcpTokens.mockReturnValue([
+ { server_name: "notfair-googleads", access_token_enc: "oauth-token" },
+ ]);
+ scriptSpawn({ stdout: completedTurn });
+ await collect(ctx());
+
+ expect(mocks.listProjectMcpTokens).toHaveBeenCalledWith("proj");
+ const env = (mocks.spawn.mock.calls[0]![2] as { env: Record<string, string> }).env;
+ expect(env.NOTFAIR_MCP_BEARER__NOTFAIR_GOALS).toBe("machine-secret");
+ expect(env.NOTFAIR_MCP_BEARER__NOTFAIR_BROWSER).toBe("machine-secret");
+ expect(env.NOTFAIR_MCP_BEARER__NOTFAIR_GOOGLEADS).toBe("oauth-token");
+ expect(env.NOTFAIR_PROJECT_SLUG).toBe("proj");
+ expect(env.NOTFAIR_AGENT_ID).toBe("agent-1");
+ });
+
+ it("passes -m for the model override and resumes real codex thread ids", async () => {
+ scriptSpawn({ stdout: completedTurn });
+ const uuid = "123e4567-e89b-42d3-a456-426614174000";
+ await collect(ctx({ model: "gpt-5.5", harnessSessionId: uuid }));
+
+ const args = mocks.spawn.mock.calls[0]![1] as string[];
+ expect(args[args.indexOf("-m") + 1]).toBe("gpt-5.5");
+ expect(args.slice(-3)).toEqual(["resume", uuid, "-"]);
+ });
+
+ it("does not resume with a non-codex session id", async () => {
+ scriptSpawn({ stdout: completedTurn });
+ await collect(ctx({ harnessSessionId: "sess-not-uuid" }));
+ const args = mocks.spawn.mock.calls[0]![1] as string[];
+ expect(args).not.toContain("resume");
+ expect(args.at(-1)).toBe("-");
+ });
+});
+
+describe("executeCodexLocal — stream handling", () => {
+ it("forwards session + events and flushes a tail line without a newline", async () => {
+ const l1 = JSON.stringify({ type: "thread.started", thread_id: "th-9" });
+ const l2 = JSON.stringify({
+ type: "item.completed",
+ item: { type: "agent_message", text: "hey" },
+ });
+ const l3 = JSON.stringify({ type: "turn.completed" }); // no trailing \n
+ scriptSpawn({ stdout: `${l1}\n${l2}\n${l3}` });
+
+ const events = await collect(ctx());
+ expect(events).toEqual([
+ { kind: "lifecycle", phase: "start" },
+ { kind: "session", harnessSessionId: "th-9" },
+ { kind: "delta", text: "hey" },
+ { kind: "final", text: "hey" },
+ ]);
+ });
+
+ it("appends the exit-code error with stderr tail even after a finalized turn", async () => {
+ scriptSpawn({ stdout: completedTurn, stderr: "warn\nfatal: token expired\n", exitCode: 2 });
+ const events = await collect(ctx());
+ expect(events).toEqual([
+ { kind: "delta", text: "ok" },
+ { kind: "final", text: "ok" },
+ { kind: "error", message: "codex exited with code 2: warn\nfatal: token expired" },
+ ]);
+ });
+
+ it("yields a terminal error when codex fails to spawn", async () => {
+ scriptSpawn({ spawnError: new Error("spawn codex ENOENT") });
+ const events = await collect(ctx());
+ expect(events).toEqual([{ kind: "error", message: "spawn codex ENOENT" }]);
+ });
+
+ it("kills the subprocess when the abort signal fires", async () => {
+ const controller = new AbortController();
+ const child = new FakeChild();
+ child.kill = vi.fn(() => {
+ child.emit("close", 143);
+ return true;
+ });
+ mocks.spawn.mockImplementationOnce(() => {
+ setImmediate(() => controller.abort());
+ return child;
+ });
+
+ const events = await collect(ctx({ signal: controller.signal }));
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ expect(events).toEqual([
+ { kind: "error", message: "codex exited with code 143" },
+ ]);
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/index.test.ts b/notfair/src/server/adapters/codex-local/index.test.ts
new file mode 100644
index 00000000..24c05754
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/index.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ executeCodexLocal: vi.fn(),
+ listCodexModels: vi.fn(async () => []),
+ provisionCodexAgent: vi.fn(async () => {}),
+ testCodexLocalEnvironment: vi.fn(async () => ({ ok: true })),
+ registerCodexMcp: vi.fn(async () => {}),
+ unregisterCodexMcp: vi.fn(async () => {}),
+}));
+
+vi.mock("./execute", () => ({ executeCodexLocal: mocks.executeCodexLocal }));
+vi.mock("./models", () => ({ listCodexModels: mocks.listCodexModels }));
+vi.mock("./provision", () => ({ provisionCodexAgent: mocks.provisionCodexAgent }));
+vi.mock("./test", () => ({ testCodexLocalEnvironment: mocks.testCodexLocalEnvironment }));
+vi.mock("./mcp", () => ({
+ registerCodexMcp: mocks.registerCodexMcp,
+ unregisterCodexMcp: mocks.unregisterCodexMcp,
+}));
+
+import { codexLocalAdapter } from "./index";
+
+describe("codexLocalAdapter", () => {
+ it("exposes the codex-local id and delegates to the submodules", async () => {
+ expect(codexLocalAdapter.id).toBe("codex-local");
+ expect(codexLocalAdapter.testEnvironment).toBe(mocks.testCodexLocalEnvironment);
+ expect(codexLocalAdapter.listModels).toBe(mocks.listCodexModels);
+
+ const ctx = { agentId: "a" } as never;
+ const gen = (async function* () {})();
+ mocks.executeCodexLocal.mockReturnValueOnce(gen);
+ expect(codexLocalAdapter.execute(ctx)).toBe(gen);
+ expect(mocks.executeCodexLocal).toHaveBeenCalledWith(ctx);
+
+ const provisionSpec = { agentId: "a" } as never;
+ await codexLocalAdapter.provisionAgent(provisionSpec);
+ expect(mocks.provisionCodexAgent).toHaveBeenCalledWith(provisionSpec);
+ });
+
+ it("passes the full spec to registerMcp and (serverName, projectSlug) to unregisterMcp", async () => {
+ const spec = {
+ serverName: "notfair-goals",
+ agentId: "agent-9",
+ projectSlug: "proj",
+ transport: { type: "http" as const, url: "http://x" },
+ };
+ await codexLocalAdapter.registerMcp(spec);
+ expect(mocks.registerCodexMcp).toHaveBeenCalledWith(spec);
+
+ await codexLocalAdapter.unregisterMcp({
+ serverName: "notfair-goals",
+ projectSlug: "proj",
+ agentId: "agent-9",
+ });
+ expect(mocks.unregisterCodexMcp).toHaveBeenCalledWith("notfair-goals", "proj");
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/mcp.test.ts b/notfair/src/server/adapters/codex-local/mcp.test.ts
new file mode 100644
index 00000000..086ad4db
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/mcp.test.ts
@@ -0,0 +1,160 @@
+import { existsSync } from "node:fs";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeEach, describe, expect, it } from "vitest";
+
+import type { McpRegistrationSpec } from "../types";
+import {
+ bearerEnvVarForServer,
+ codexConfigDir,
+ registerCodexMcp,
+ unregisterCodexMcp,
+} from "./mcp";
+
+const originalCodexHome = process.env.CODEX_HOME;
+let codexHome: string;
+
+beforeEach(async () => {
+ codexHome = await mkdtemp(join(tmpdir(), "notfair-codex-home-"));
+ process.env.CODEX_HOME = codexHome;
+});
+
+afterAll(() => {
+ if (originalCodexHome === undefined) delete process.env.CODEX_HOME;
+ else process.env.CODEX_HOME = originalCodexHome;
+});
+
+function spec(overrides: Partial<McpRegistrationSpec> = {}): McpRegistrationSpec {
+ return {
+ serverName: "notfair-goals",
+ agentId: "agent-1",
+ projectSlug: "my-proj",
+ transport: {
+ type: "http",
+ url: "http://127.0.0.1:3326/api/mcp/goals",
+ headers: { Authorization: "Bearer s3cret" },
+ },
+ ...overrides,
+ };
+}
+
+async function readToml(): Promise<string> {
+ return readFile(join(codexHome, "config.toml"), "utf8");
+}
+
+describe("codexConfigDir", () => {
+ it("honors CODEX_HOME", () => {
+ expect(codexConfigDir()).toBe(codexHome);
+ });
+});
+
+describe("bearerEnvVarForServer", () => {
+ it("uppercases and sanitizes the server name", () => {
+ expect(bearerEnvVarForServer("notfair-goals")).toBe(
+ "NOTFAIR_MCP_BEARER__NOTFAIR_GOALS",
+ );
+ expect(bearerEnvVarForServer("gsc.v2")).toBe("NOTFAIR_MCP_BEARER__GSC_V2");
+ });
+});
+
+describe("registerCodexMcp", () => {
+ it("writes a project-namespaced http section with bearer_token_env_var, never a raw Authorization header", async () => {
+ await registerCodexMcp(spec());
+ const toml = await readToml();
+ expect(toml).toContain("[mcp_servers.notfair_my_proj__notfair_goals]");
+ expect(toml).toContain('url = "http://127.0.0.1:3326/api/mcp/goals"');
+ expect(toml).toContain(
+ 'bearer_token_env_var = "NOTFAIR_MCP_BEARER__NOTFAIR_GOALS"',
+ );
+ expect(toml).not.toContain("s3cret");
+ expect(toml).not.toContain("Authorization");
+ });
+
+ it("keeps non-auth headers as a TOML inline table", async () => {
+ await registerCodexMcp(
+ spec({
+ transport: {
+ type: "http",
+ url: "http://x",
+ headers: { authorization: "Bearer t", "X-Notfair": "yes" },
+ },
+ }),
+ );
+ const toml = await readToml();
+ expect(toml).toContain('headers = { X-Notfair = "yes" }');
+ expect(toml).toContain("bearer_token_env_var");
+ });
+
+ it("omits bearer wiring when the transport has no auth header", async () => {
+ await registerCodexMcp(
+ spec({ transport: { type: "http", url: "http://x" } }),
+ );
+ expect(await readToml()).not.toContain("bearer_token_env_var");
+ });
+
+ it("writes stdio sections with command, args and env", async () => {
+ await registerCodexMcp(
+ spec({
+ serverName: "local-tool",
+ transport: {
+ type: "stdio",
+ command: "node",
+ args: ["server.js", "--flag"],
+ env: { TOKEN: "t" },
+ },
+ }),
+ );
+ const toml = await readToml();
+ expect(toml).toContain("[mcp_servers.notfair_my_proj__local_tool]");
+ expect(toml).toContain('command = "node"');
+ expect(toml).toContain('args = ["server.js","--flag"]');
+ expect(toml).toContain('env = { TOKEN = "t" }');
+ });
+
+ it("replaces an existing section instead of duplicating it on re-register", async () => {
+ await registerCodexMcp(spec());
+ await registerCodexMcp(
+ spec({ transport: { type: "http", url: "http://new-url" } }),
+ );
+ const toml = await readToml();
+ const headers = toml.match(/\[mcp_servers\.notfair_my_proj__notfair_goals\]/g);
+ expect(headers).toHaveLength(1);
+ expect(toml).toContain('url = "http://new-url"');
+ expect(toml).not.toContain("api/mcp/goals");
+ });
+
+ it("preserves user-installed servers outside the notfair namespace", async () => {
+ await writeFile(
+ join(codexHome, "config.toml"),
+ 'model = "gpt-5.5"\n\n[mcp_servers.user_tool]\ncommand = "mine"\n',
+ "utf8",
+ );
+ await registerCodexMcp(spec());
+ const toml = await readToml();
+ expect(toml).toContain('model = "gpt-5.5"');
+ expect(toml).toContain("[mcp_servers.user_tool]");
+ expect(toml).toContain('command = "mine"');
+ expect(toml).toContain("[mcp_servers.notfair_my_proj__notfair_goals]");
+ });
+});
+
+describe("unregisterCodexMcp", () => {
+ it("removes only our namespaced section", async () => {
+ await writeFile(
+ join(codexHome, "config.toml"),
+ '[mcp_servers.user_tool]\ncommand = "mine"\n',
+ "utf8",
+ );
+ await registerCodexMcp(spec());
+ await unregisterCodexMcp("notfair-goals", "my-proj");
+ const toml = await readToml();
+ expect(toml).not.toContain("notfair_my_proj__notfair_goals");
+ expect(toml).toContain("[mcp_servers.user_tool]");
+ });
+
+ it("is a no-op when there is no config file", async () => {
+ await unregisterCodexMcp("notfair-goals", "my-proj");
+ expect(existsSync(join(codexHome, "config.toml"))).toBe(false);
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/models.more.test.ts b/notfair/src/server/adapters/codex-local/models.more.test.ts
new file mode 100644
index 00000000..21222152
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/models.more.test.ts
@@ -0,0 +1,110 @@
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { listCodexModels } from "./models";
+
+async function tmp(): Promise<string> {
+ return mkdtemp(join(tmpdir(), "notfair-codex-models-more-"));
+}
+
+describe("listCodexModels — cache handling", () => {
+ it("falls back to the static list (first marked default) when the cache is missing", async () => {
+ const dir = await tmp();
+ const models = await listCodexModels(
+ join(dir, "no-cache.json"),
+ join(dir, "no-config.toml"),
+ );
+ expect(models).toEqual([
+ { value: "gpt-5.5", label: "GPT-5.5", is_default: true },
+ { value: "gpt-5.4", label: "GPT-5.4" },
+ ]);
+ });
+
+ it("falls back when the cache holds an empty model list", async () => {
+ const dir = await tmp();
+ const cacheFile = join(dir, "models_cache.json");
+ await writeFile(cacheFile, JSON.stringify({ models: [] }), "utf8");
+ const models = await listCodexModels(cacheFile, join(dir, "no-config.toml"));
+ expect(models.map((m) => m.value)).toEqual(["gpt-5.5", "gpt-5.4"]);
+ });
+
+ it("filters hidden models, sorts by priority, and carries context windows", async () => {
+ const dir = await tmp();
+ const cacheFile = join(dir, "models_cache.json");
+ await writeFile(
+ cacheFile,
+ JSON.stringify({
+ models: [
+ { slug: "internal", display_name: "Internal", visibility: "hide", priority: 0 },
+ { slug: "no-priority", display_name: "No Priority" },
+ { slug: "second", display_name: "Second", priority: 2, context_window: 0 },
+ { slug: "first", display_name: "First", priority: 1, context_window: 272_000 },
+ { slug: "", display_name: "Empty slug", priority: 0 },
+ ],
+ }),
+ "utf8",
+ );
+
+ const models = await listCodexModels(cacheFile, join(dir, "no-config.toml"));
+ expect(models.map((m) => m.value)).toEqual(["first", "second", "no-priority"]);
+ expect(models[0]).toMatchObject({
+ label: "First",
+ context_window: 272_000,
+ is_default: true,
+ });
+ // context_window omitted when non-positive or absent.
+ expect(models[1]!.context_window).toBeUndefined();
+ });
+
+ it("labels a model by its slug when display_name is missing", async () => {
+ const dir = await tmp();
+ const cacheFile = join(dir, "models_cache.json");
+ await writeFile(
+ cacheFile,
+ JSON.stringify({ models: [{ slug: "gpt-raw", priority: 1 }] }),
+ "utf8",
+ );
+ const models = await listCodexModels(cacheFile, join(dir, "no-config.toml"));
+ expect(models[0]).toMatchObject({ value: "gpt-raw", label: "gpt-raw" });
+ });
+});
+
+describe("listCodexModels — configured default parsing", () => {
+ async function withConfig(config: string) {
+ const dir = await tmp();
+ const configFile = join(dir, "config.toml");
+ const cacheFile = join(dir, "models_cache.json");
+ await Promise.all([
+ writeFile(configFile, config, "utf8"),
+ writeFile(
+ cacheFile,
+ JSON.stringify({
+ models: [
+ { slug: "gpt-5.5", display_name: "GPT-5.5", priority: 1 },
+ { slug: "gpt-5.4", display_name: "GPT-5.4", priority: 2 },
+ ],
+ }),
+ "utf8",
+ ),
+ ]);
+ return listCodexModels(cacheFile, configFile);
+ }
+
+ it("parses a single-quoted model value", async () => {
+ const models = await withConfig("model = 'gpt-5.4'\n");
+ expect(models.find((m) => m.is_default)?.value).toBe("gpt-5.4");
+ });
+
+ it("parses a bare model value with a trailing comment", async () => {
+ const models = await withConfig("model = gpt-5.4 # pinned\n");
+ expect(models.find((m) => m.is_default)?.value).toBe("gpt-5.4");
+ });
+
+ it("ignores model keys nested under a profile table", async () => {
+ const models = await withConfig('[profiles.fast]\nmodel = "gpt-5.4"\n');
+ // No root-level model → first cache entry is the effective default.
+ expect(models.find((m) => m.is_default)?.value).toBe("gpt-5.5");
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/parse.more.test.ts b/notfair/src/server/adapters/codex-local/parse.more.test.ts
new file mode 100644
index 00000000..19dd4e89
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/parse.more.test.ts
@@ -0,0 +1,235 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ isAdvisoryCodexItemError,
+ isTransientCodexError,
+ makeCodexStreamState,
+ parseCodexLine,
+} from "./parse";
+
+const line = (obj: unknown) => JSON.stringify(obj);
+
+describe("parseCodexLine — noise handling", () => {
+ it("ignores blank lines, invalid JSON and unknown types", () => {
+ const state = makeCodexStreamState();
+ expect(parseCodexLine("", state)).toEqual([]);
+ expect(parseCodexLine("garbage {", state)).toEqual([]);
+ expect(parseCodexLine(line({ type: "mystery" }), state)).toEqual([]);
+ });
+
+ it("ignores item.completed for non-toolish, non-message item types", () => {
+ expect(
+ parseCodexLine(
+ line({ type: "item.completed", item: { type: "reasoning", text: "thinking" } }),
+ makeCodexStreamState(),
+ ),
+ ).toEqual([]);
+ });
+});
+
+describe("parseCodexLine — thread lifecycle", () => {
+ it("emits lifecycle + session on thread.started", () => {
+ const state = makeCodexStreamState();
+ const events = parseCodexLine(
+ line({ type: "thread.started", thread_id: "th-1" }),
+ state,
+ );
+ expect(events).toEqual([
+ { kind: "lifecycle", phase: "start" },
+ { kind: "session", harnessSessionId: "th-1" },
+ ]);
+ expect(state.threadId).toBe("th-1");
+ });
+
+ it("emits only lifecycle when thread.started lacks a thread id", () => {
+ const events = parseCodexLine(
+ line({ type: "thread.started" }),
+ makeCodexStreamState(),
+ );
+ expect(events).toEqual([{ kind: "lifecycle", phase: "start" }]);
+ });
+});
+
+describe("parseCodexLine — agent messages and finals", () => {
+ it("forwards agent_message text whole as one delta, then final on turn.completed", () => {
+ const state = makeCodexStreamState();
+ const deltas = parseCodexLine(
+ line({ type: "item.completed", item: { type: "agent_message", text: "answer" } }),
+ state,
+ );
+ expect(deltas).toEqual([{ kind: "delta", text: "answer" }]);
+
+ const finals = parseCodexLine(line({ type: "turn.completed", usage: {} }), state);
+ expect(finals).toEqual([{ kind: "final", text: "answer" }]);
+ expect(state.finalized).toBe(true);
+ });
+
+ it("accumulates multiple agent messages into the final text", () => {
+ const state = makeCodexStreamState();
+ parseCodexLine(
+ line({ type: "item.completed", item: { type: "agent_message", text: "one " } }),
+ state,
+ );
+ parseCodexLine(
+ line({ type: "item.completed", item: { type: "agent_message", text: "two" } }),
+ state,
+ );
+ expect(parseCodexLine(line({ type: "turn.completed" }), state)).toEqual([
+ { kind: "final", text: "one two" },
+ ]);
+ });
+});
+
+describe("parseCodexLine — tool naming", () => {
+ it("names command_execution items 'shell' and keeps the command in the label", () => {
+ const state = makeCodexStreamState();
+ const started = parseCodexLine(
+ line({
+ type: "item.started",
+ item: { type: "command_execution", id: "c1", command: "ls -la\npwd" },
+ }),
+ state,
+ );
+ expect(started).toEqual([
+ { kind: "tool", phase: "start", toolCallId: "c1", name: "shell", label: "ls -la" },
+ ]);
+
+ const completed = parseCodexLine(
+ line({
+ type: "item.completed",
+ item: { type: "command_execution", id: "c1", command: "ls -la" },
+ }),
+ state,
+ );
+ expect(completed).toEqual([
+ { kind: "tool", phase: "result", toolCallId: "c1", name: "shell" },
+ ]);
+ });
+
+ it("clips a long command label to 160 chars", () => {
+ const events = parseCodexLine(
+ line({
+ type: "item.started",
+ item: { type: "command_execution", id: "c2", command: "x".repeat(200) },
+ }),
+ makeCodexStreamState(),
+ );
+ const label = (events[0] as { label: string }).label;
+ expect(label).toHaveLength(160);
+ expect(label.endsWith("…")).toBe(true);
+ });
+
+ it("keeps declared names for function_call items", () => {
+ const events = parseCodexLine(
+ line({
+ type: "item.started",
+ item: { type: "function_call", id: "f1", name: "lookup_thing" },
+ }),
+ makeCodexStreamState(),
+ );
+ expect(events[0]).toMatchObject({ kind: "tool", name: "lookup_thing" });
+ });
+
+ it("uses tool name without a server prefix for serverless mcp_call items", () => {
+ const events = parseCodexLine(
+ line({
+ type: "item.started",
+ item: { type: "mcp_call", id: "m1", tool_name: "getInsights" },
+ }),
+ makeCodexStreamState(),
+ );
+ expect(events[0]).toMatchObject({ name: "getInsights" });
+ });
+
+ it("degrades to the 'tool' token when every naming signal is missing", () => {
+ const events = parseCodexLine(
+ line({ type: "item.started", item: { type: "tool_call", id: "t1" } }),
+ makeCodexStreamState(),
+ );
+ expect(events[0]).toMatchObject({ toolCallId: "t1", name: "tool" });
+ expect((events[0] as { label?: string }).label).toBeUndefined();
+ });
+});
+
+describe("parseCodexLine — errors", () => {
+ it("surfaces non-advisory item errors as transient errors", () => {
+ const events = parseCodexLine(
+ line({
+ type: "item.completed",
+ item: { type: "error", message: "tool exploded" },
+ }),
+ makeCodexStreamState(),
+ );
+ expect(events).toEqual([
+ { kind: "error", message: "tool exploded", transient: true },
+ ]);
+ });
+
+ it("suppresses advisory item errors that codex prints on every run", () => {
+ const events = parseCodexLine(
+ line({
+ type: "item.completed",
+ item: {
+ type: "error",
+ message: "Skill descriptions were shortened to fit the 2% skills context budget.",
+ },
+ }),
+ makeCodexStreamState(),
+ );
+ expect(events).toEqual([]);
+ });
+
+ it("marks terminal turn.failed as finalized with a non-transient error", () => {
+ const state = makeCodexStreamState();
+ const events = parseCodexLine(
+ line({ type: "turn.failed", error: { message: "quota exhausted" } }),
+ state,
+ );
+ expect(events).toEqual([
+ { kind: "error", message: "quota exhausted", transient: false },
+ ]);
+ expect(state.finalized).toBe(true);
+ });
+
+ it("keeps the turn un-finalized on transient reconnect chatter", () => {
+ const state = makeCodexStreamState();
+ const events = parseCodexLine(
+ line({ type: "turn.failed", error: { message: "Reconnecting... 2/5 (mcp)" } }),
+ state,
+ );
+ expect(events).toEqual([
+ { kind: "error", message: "Reconnecting... 2/5 (mcp)", transient: true },
+ ]);
+ expect(state.finalized).toBe(false);
+ });
+
+ it("falls back to a generic message when turn.failed carries none", () => {
+ const events = parseCodexLine(
+ line({ type: "turn.failed" }),
+ makeCodexStreamState(),
+ );
+ expect(events[0]).toMatchObject({ message: "codex turn failed" });
+ });
+
+ it("forwards top-level error events with transient tagging", () => {
+ expect(
+ parseCodexLine(line({ type: "error", message: "boom" }), makeCodexStreamState()),
+ ).toEqual([{ kind: "error", message: "boom", transient: false }]);
+ expect(
+ parseCodexLine(line({ type: "error" }), makeCodexStreamState()),
+ ).toEqual([{ kind: "error", message: "codex error", transient: false }]);
+ });
+});
+
+describe("transient / advisory classifiers", () => {
+ it("classifies only the reconnect loop as transient", () => {
+ expect(isTransientCodexError("Reconnecting... 3/5 (network)")).toBe(true);
+ expect(isTransientCodexError(" Reconnecting... 1/5")).toBe(true);
+ expect(isTransientCodexError("connection reset")).toBe(false);
+ });
+
+ it("classifies the skills-budget nudge as advisory", () => {
+ expect(isAdvisoryCodexItemError("Skill descriptions were shortened …")).toBe(true);
+ expect(isAdvisoryCodexItemError("real failure")).toBe(false);
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/provision.test.ts b/notfair/src/server/adapters/codex-local/provision.test.ts
new file mode 100644
index 00000000..3541aa5a
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/provision.test.ts
@@ -0,0 +1,55 @@
+import { existsSync } from "node:fs";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import type { AgentProvisionSpec } from "../types";
+import { provisionCodexAgent } from "./provision";
+
+let workspaceDir: string;
+
+beforeEach(async () => {
+ workspaceDir = await mkdtemp(join(tmpdir(), "notfair-codex-prov-"));
+});
+
+function spec(overrides: Partial<AgentProvisionSpec> = {}): AgentProvisionSpec {
+ return {
+ projectSlug: "proj",
+ agentId: "proj-goal-1",
+ displayName: "Greg",
+ templateKey: "goal",
+ workspaceDir,
+ identityMd: "# Greg identity\n",
+ ...overrides,
+ };
+}
+
+describe("provisionCodexAgent", () => {
+ it("mirrors the identity into AGENTS.md so codex auto-loads it", async () => {
+ await provisionCodexAgent(spec());
+ expect(await readFile(join(workspaceDir, "IDENTITY.md"), "utf8")).toBe(
+ "# Greg identity\n",
+ );
+ expect(await readFile(join(workspaceDir, "AGENTS.md"), "utf8")).toBe(
+ "# Greg identity\n",
+ );
+ });
+
+ it("writes PROJECT.md only when a project brief exists", async () => {
+ await provisionCodexAgent(spec());
+ expect(existsSync(join(workspaceDir, "PROJECT.md"))).toBe(false);
+
+ await provisionCodexAgent(spec({ projectMd: "# Brief\n" }));
+ expect(await readFile(join(workspaceDir, "PROJECT.md"), "utf8")).toBe("# Brief\n");
+ });
+
+ it("creates the workspace dir and removes a stale SKILL.md sidecar", async () => {
+ await writeFile(join(workspaceDir, "SKILL.md"), "old skill", "utf8");
+ const nested = join(workspaceDir, "sub", "agent");
+ await provisionCodexAgent(spec());
+ await provisionCodexAgent(spec({ workspaceDir: nested }));
+ expect(existsSync(join(workspaceDir, "SKILL.md"))).toBe(false);
+ expect(existsSync(join(nested, "AGENTS.md"))).toBe(true);
+ });
+});
diff --git a/notfair/src/server/adapters/codex-local/test.test.ts b/notfair/src/server/adapters/codex-local/test.test.ts
new file mode 100644
index 00000000..e3da2179
--- /dev/null
+++ b/notfair/src/server/adapters/codex-local/test.test.ts
@@ -0,0 +1,76 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
+vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));
+
+import { testCodexLocalEnvironment } from "./test";
+
+class FakeChild extends EventEmitter {
+ stdout = new PassThrough();
+ stderr = new PassThrough();
+ kill = vi.fn();
+}
+
+function scriptVersionCmd(script: {
+ stdout?: string;
+ exitCode?: number;
+ spawnError?: boolean;
+ hang?: boolean;
+}): FakeChild {
+ const child = new FakeChild();
+ mocks.spawn.mockImplementationOnce(() => {
+ if (!script.hang) {
+ setImmediate(() => {
+ if (script.spawnError) {
+ child.emit("error", new Error("ENOENT"));
+ return;
+ }
+ if (script.stdout) child.stdout.emit("data", Buffer.from(script.stdout));
+ child.emit("close", script.exitCode ?? 0);
+ });
+ }
+ return child;
+ });
+ return child;
+}
+
+beforeEach(() => mocks.spawn.mockReset());
+afterEach(() => vi.useRealTimers());
+
+describe("testCodexLocalEnvironment", () => {
+ it("reports ok with a parsed version label when the CLI responds", async () => {
+ scriptVersionCmd({ stdout: "codex-cli 0.144.2\n" });
+ const health = await testCodexLocalEnvironment();
+ expect(health).toEqual({
+ ok: true,
+ auth: "unknown",
+ versionLabel: "Codex 0.144.2",
+ });
+ expect(mocks.spawn).toHaveBeenCalledWith("codex", ["--version"], expect.anything());
+ });
+
+ it("falls back to a bare label when the version string is unparsable", async () => {
+ scriptVersionCmd({ stdout: "nightly\n" });
+ const health = await testCodexLocalEnvironment();
+ expect(health.versionLabel).toBe("Codex");
+ });
+
+ it("reports not-ok with an install hint when the binary is missing", async () => {
+ scriptVersionCmd({ spawnError: true });
+ const health = await testCodexLocalEnvironment();
+ expect(health.ok).toBe(false);
+ expect(health.message).toContain("`codex` not found on PATH");
+ });
+
+ it("times out a hung probe instead of waiting forever", async () => {
+ vi.useFakeTimers();
+ const child = scriptVersionCmd({ hang: true });
+ const pending = testCodexLocalEnvironment();
+ await vi.advanceTimersByTimeAsync(5_001);
+ const health = await pending;
+ expect(health.ok).toBe(false);
+ expect(child.kill).toHaveBeenCalledWith("SIGTERM");
+ });
+});
diff --git a/notfair/src/server/adapters/label-args.test.ts b/notfair/src/server/adapters/label-args.test.ts
new file mode 100644
index 00000000..4f9efc27
--- /dev/null
+++ b/notfair/src/server/adapters/label-args.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+
+import { labelFromArgs } from "./label-args";
+
+describe("labelFromArgs", () => {
+ it("returns undefined for absent or empty args", () => {
+ expect(labelFromArgs(undefined)).toBeUndefined();
+ expect(labelFromArgs(null)).toBeUndefined();
+ expect(labelFromArgs({})).toBeUndefined();
+ });
+
+ it("prefers a well-known string key over the k=v digest", () => {
+ expect(labelFromArgs({ campaign_id: 1, query: "SELECT 1" })).toBe("SELECT 1");
+ });
+
+ it("respects the priority order of string keys (file_path before url)", () => {
+ expect(labelFromArgs({ url: "https://x.test", file_path: "/tmp/a.txt" })).toBe(
+ "/tmp/a.txt",
+ );
+ });
+
+ it("takes only the first line of a multi-line value and trims it", () => {
+ expect(labelFromArgs({ sql: " SELECT *\nFROM t " })).toBe("SELECT *");
+ });
+
+ it("clips long values to 160 chars with an ellipsis", () => {
+ const label = labelFromArgs({ command: "x".repeat(200) })!;
+ expect(label).toHaveLength(160);
+ expect(label.endsWith("…")).toBe(true);
+ expect(label.slice(0, 159)).toBe("x".repeat(159));
+ });
+
+ it("skips whitespace-only string keys and falls through to the digest", () => {
+ expect(labelFromArgs({ query: " ", limit: 5 })).toBe("limit=5");
+ });
+
+ it("builds a k=v digest from primitive args", () => {
+ expect(
+ labelFromArgs({ campaign_id: 12345, dry_run: true, note: "hi" }),
+ ).toBe("campaign_id=12345 dry_run=true note=hi");
+ });
+
+ it("skips null/undefined and non-primitive values in the digest", () => {
+ expect(
+ labelFromArgs({ a: null, b: undefined, c: { nested: 1 }, d: [1], e: 7 }),
+ ).toBe("e=7");
+ });
+
+ it("stops the digest after four parts", () => {
+ const label = labelFromArgs({ a: 1, b: 2, c: 3, d: 4, e: 5 });
+ expect(label).toBe("a=1 b=2 c=3 d=4");
+ });
+
+ it("clips individual digest string values to 40 chars", () => {
+ const label = labelFromArgs({ note: "y".repeat(50) })!;
+ expect(label).toBe(`note=${"y".repeat(39)}…`);
+ });
+
+ it("returns undefined when args hold only non-labelable values", () => {
+ expect(labelFromArgs({ a: null, b: { x: 1 }, c: " " })).toBeUndefined();
+ });
+});
diff --git a/notfair/src/server/adapters/registry.test.ts b/notfair/src/server/adapters/registry.test.ts
new file mode 100644
index 00000000..e533c0ea
--- /dev/null
+++ b/notfair/src/server/adapters/registry.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it, vi } from "vitest";
+
+// The adapter modules pull in @/server/mcp-server/secret and @/server/db/db,
+// which capture NOTFAIR_DATA_DIR at import time — hoist the override so
+// nothing ever resolves to 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-registry-"));
+});
+
+import {
+ DEFAULT_HARNESS_ADAPTER,
+ getAdapter,
+ isHarnessAdapterId,
+ listAdapters,
+ requireAdapter,
+} from "./registry";
+
+describe("adapter registry", () => {
+ it("resolves both built-in adapters by id", () => {
+ expect(getAdapter("claude-code-local")?.id).toBe("claude-code-local");
+ expect(getAdapter("codex-local")?.id).toBe("codex-local");
+ });
+
+ it("returns null from getAdapter for an unknown id", () => {
+ expect(getAdapter("nope" as never)).toBeNull();
+ });
+
+ it("requireAdapter returns the adapter or throws with the id in the message", () => {
+ expect(requireAdapter("codex-local").id).toBe("codex-local");
+ expect(() => requireAdapter("nope" as never)).toThrow(
+ "Unknown harness adapter: nope",
+ );
+ });
+
+ it("lists exactly the built-ins", () => {
+ expect(listAdapters().map((a) => a.id).sort()).toEqual([
+ "claude-code-local",
+ "codex-local",
+ ]);
+ });
+
+ it("defaults to claude-code-local", () => {
+ expect(DEFAULT_HARNESS_ADAPTER).toBe("claude-code-local");
+ });
+
+ it("isHarnessAdapterId accepts only known ids", () => {
+ expect(isHarnessAdapterId("claude-code-local")).toBe(true);
+ expect(isHarnessAdapterId("codex-local")).toBe(true);
+ expect(isHarnessAdapterId("gemini-local")).toBe(false);
+ expect(isHarnessAdapterId(undefined)).toBe(false);
+ expect(isHarnessAdapterId(42)).toBe(false);
+ });
+});
diff --git a/notfair/src/server/agent-meta.test.ts b/notfair/src/server/agent-meta.test.ts
new file mode 100644
index 00000000..f28bc88a
--- /dev/null
+++ b/notfair/src/server/agent-meta.test.ts
@@ -0,0 +1,174 @@
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { readFileSync, writeFileSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+// Real fs against a tmpdir data dir, per repo test conventions.
+// MUST be hoisted: static imports evaluate before module-level statements,
+// so a plain assignment would point the suite at the developer's ~/.notfair.
+const h = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-meta-"));
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir };
+});
+
+import {
+ agentExistsOnDisk,
+ listProjectAgents,
+ readAgentMeta,
+ resolveAgentBySlug,
+ workspaceDirFor,
+ writeAgentMeta,
+} from "./agent-meta";
+
+describe("agent meta sidecar", () => {
+ it("round-trips write → read", async () => {
+ await writeAgentMeta({
+ agent_id: "acme-goal-alex",
+ project_slug: "acme",
+ name: "Alex",
+ slug: "goal-alex",
+ created_at: "2026-01-01T00:00:00.000Z",
+ });
+ const meta = readAgentMeta("acme-goal-alex");
+ expect(meta).toMatchObject({
+ agent_id: "acme-goal-alex",
+ project_slug: "acme",
+ name: "Alex",
+ slug: "goal-alex",
+ });
+ // Human-inspectable: pretty-printed JSON on disk.
+ const raw = readFileSync(
+ join(h.dataDir, "agents", "acme-goal-alex", "notfair-meta.json"),
+ "utf8",
+ );
+ expect(raw).toContain("\n \"agent_id\"");
+ });
+
+ it("returns null for a missing sidecar", () => {
+ expect(readAgentMeta("no-such-agent")).toBeNull();
+ });
+
+ it("returns null for a corrupt sidecar instead of throwing", async () => {
+ const dir = join(h.dataDir, "agents", "acme-goal-corrupt");
+ await mkdir(dir, { recursive: true });
+ writeFileSync(join(dir, "notfair-meta.json"), "{not json", "utf8");
+ expect(readAgentMeta("acme-goal-corrupt")).toBeNull();
+ });
+});
+
+describe("agentExistsOnDisk", () => {
+ it("is true for a provisioned workspace dir", async () => {
+ await mkdir(join(h.dataDir, "agents", "acme-goal-here"), { recursive: true });
+ await expect(agentExistsOnDisk("acme-goal-here")).resolves.toBe(true);
+ });
+
+ it("is false for a missing workspace", async () => {
+ await expect(agentExistsOnDisk("acme-goal-missing")).resolves.toBe(false);
+ });
+
+ it("is false when the path is a file, not a directory", async () => {
+ await mkdir(join(h.dataDir, "agents"), { recursive: true });
+ await writeFile(join(h.dataDir, "agents", "acme-goal-file"), "x", "utf8");
+ await expect(agentExistsOnDisk("acme-goal-file")).resolves.toBe(false);
+ });
+});
+
+describe("workspaceDirFor", () => {
+ it("points inside the data dir", () => {
+ expect(workspaceDirFor("acme-goal-alex")).toBe(
+ join(h.dataDir, "agents", "acme-goal-alex"),
+ );
+ });
+});
+
+describe("listProjectAgents", () => {
+ beforeAll(async () => {
+ // Roster for "roster" plus a lookalike project "roster-q4" whose slug
+ // has "roster" as a string prefix — must not cross-leak.
+ await writeAgentMeta({
+ agent_id: "roster-goal-beth",
+ project_slug: "roster",
+ name: "Beth",
+ slug: "goal-beth",
+ created_at: "2026-01-02T00:00:00.000Z",
+ });
+ await writeAgentMeta({
+ agent_id: "roster-goal-abe",
+ project_slug: "roster",
+ name: "Abe",
+ slug: "goal-abe",
+ source_agent_id: "roster-goal-beth",
+ created_at: "2026-01-01T00:00:00.000Z",
+ });
+ await writeAgentMeta({
+ agent_id: "roster-q4-goal-carl",
+ project_slug: "roster-q4",
+ name: "Carl",
+ slug: "goal-carl",
+ created_at: "2026-01-03T00:00:00.000Z",
+ });
+ // Sidecar written before `slug` existed: falls back to slugified name.
+ const legacy = {
+ agent_id: "roster-goal-dee-jones",
+ project_slug: "roster",
+ name: "Dee Jones!",
+ created_at: "2026-01-04T00:00:00.000Z",
+ };
+ const dir = join(h.dataDir, "agents", legacy.agent_id);
+ await mkdir(dir, { recursive: true });
+ writeFileSync(join(dir, "notfair-meta.json"), JSON.stringify(legacy), "utf8");
+ // Dir with the right prefix but no sidecar — skipped.
+ await mkdir(join(h.dataDir, "agents", "roster-goal-nometa"), {
+ recursive: true,
+ });
+ });
+
+ it("returns only this project's sidecars, oldest first", async () => {
+ const agents = await listProjectAgents("roster");
+ expect(agents.map((a) => a.agent_id)).toEqual([
+ "roster-goal-abe",
+ "roster-goal-beth",
+ "roster-goal-dee-jones",
+ ]);
+ expect(agents[0]!.source_agent_id).toBe("roster-goal-beth");
+ });
+
+ it("never leaks a prefix-colliding project's roster", async () => {
+ const agents = await listProjectAgents("roster-q4");
+ expect(agents.map((a) => a.agent_id)).toEqual(["roster-q4-goal-carl"]);
+ });
+
+ it("derives a slug for legacy sidecars without one", async () => {
+ const agents = await listProjectAgents("roster");
+ const dee = agents.find((a) => a.agent_id === "roster-goal-dee-jones")!;
+ expect(dee.slug).toBe("goal-dee-jones");
+ });
+
+ it("returns [] when the agents root doesn't exist yet", async () => {
+ const saved = process.env.NOTFAIR_DATA_DIR;
+ process.env.NOTFAIR_DATA_DIR = join(h.dataDir, "does-not-exist");
+ try {
+ await expect(listProjectAgents("roster")).resolves.toEqual([]);
+ } finally {
+ process.env.NOTFAIR_DATA_DIR = saved;
+ }
+ });
+});
+
+describe("resolveAgentBySlug", () => {
+ it("resolves a URL slug to the full agent id", async () => {
+ await expect(resolveAgentBySlug("roster", "goal-beth")).resolves.toEqual({
+ agent_id: "roster-goal-beth",
+ name: "Beth",
+ slug: "goal-beth",
+ });
+ });
+
+ it("returns null for an unknown slug", async () => {
+ await expect(resolveAgentBySlug("roster", "goal-nobody")).resolves.toBeNull();
+ });
+});
diff --git a/notfair/src/server/agents/clone.test.ts b/notfair/src/server/agents/clone.test.ts
new file mode 100644
index 00000000..815da800
--- /dev/null
+++ b/notfair/src/server/agents/clone.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it, vi } from "vitest";
+import { existsSync, readFileSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+// Real fs against a tmpdir data dir, per repo test conventions.
+// MUST be hoisted: static imports evaluate before module-level statements,
+// so a plain assignment would point the suite at the developer's ~/.notfair.
+const h = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-clone-"));
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir };
+});
+
+import { agentExistsInProject, cloneAgent } from "./clone";
+import { readAgentMeta } from "@/server/agent-meta";
+
+const agentsRoot = () => join(h.dataDir, "agents");
+
+async function seedAgent(agentId: string, files: Record<string, string> = {}) {
+ const dir = join(agentsRoot(), agentId);
+ await mkdir(dir, { recursive: true });
+ for (const [name, body] of Object.entries(files)) {
+ await writeFile(join(dir, name), body, "utf8");
+ }
+}
+
+describe("cloneAgent", () => {
+ it("copies the workspace and writes a fresh meta sidecar", async () => {
+ await seedAgent("acme-goal-src", {
+ "IDENTITY.md": "# identity",
+ "notes.txt": "scratch",
+ });
+
+ const result = await cloneAgent({
+ source_agent_id: "acme-goal-src",
+ project_slug: "acme",
+ new_slug: "Goal Copy!",
+ display_name: "Copy",
+ });
+
+ expect(result).toEqual({
+ new_agent_id: "acme-goal-copy",
+ new_slug: "goal-copy",
+ files_copied: 1,
+ sessions_copied: 0,
+ });
+ // Workspace files came along.
+ expect(
+ readFileSync(join(agentsRoot(), "acme-goal-copy", "IDENTITY.md"), "utf8"),
+ ).toBe("# identity");
+ // Sidecar reflects the clone, including provenance.
+ expect(readAgentMeta("acme-goal-copy")).toMatchObject({
+ agent_id: "acme-goal-copy",
+ project_slug: "acme",
+ slug: "goal-copy",
+ name: "Copy",
+ source_agent_id: "acme-goal-src",
+ });
+ });
+
+ it("defaults the display name to the source agent id", async () => {
+ await seedAgent("acme-goal-src2", { "a.txt": "a" });
+ await cloneAgent({
+ source_agent_id: "acme-goal-src2",
+ project_slug: "acme",
+ new_slug: "unnamed-clone",
+ });
+ expect(readAgentMeta("acme-unnamed-clone")?.name).toBe("acme-goal-src2");
+ });
+
+ it("still writes the sidecar when the source workspace is missing", async () => {
+ const result = await cloneAgent({
+ source_agent_id: "acme-goal-ghost",
+ project_slug: "acme",
+ new_slug: "from-ghost",
+ });
+ expect(result.files_copied).toBe(0);
+ // The sidecar itself creates the destination dir.
+ expect(readAgentMeta("acme-from-ghost")?.slug).toBe("from-ghost");
+ });
+
+ it("rejects an invalid user-entered slug", async () => {
+ await expect(
+ cloneAgent({
+ source_agent_id: "acme-goal-src",
+ project_slug: "acme",
+ new_slug: "!!!",
+ }),
+ ).rejects.toThrow(/Invalid agent slug/);
+ });
+
+ it("accepts a canonical slug verbatim and rejects malformed ones", async () => {
+ await expect(
+ cloneAgent({
+ source_agent_id: "acme-goal-src",
+ project_slug: "acme",
+ new_slug: "Bad_Canonical",
+ slug_is_canonical: true,
+ }),
+ ).rejects.toThrow(/Invalid canonical slug/);
+
+ const result = await cloneAgent({
+ source_agent_id: "acme-goal-src",
+ project_slug: "acme",
+ new_slug: "canon-ok",
+ slug_is_canonical: true,
+ });
+ expect(result.new_agent_id).toBe("acme-canon-ok");
+ });
+
+ it("refuses to clobber an existing agent with the same slug", async () => {
+ await seedAgent("acme-goal-taken", { "x.txt": "x" });
+ await expect(
+ cloneAgent({
+ source_agent_id: "acme-goal-src",
+ project_slug: "acme",
+ new_slug: "goal-taken",
+ }),
+ ).rejects.toThrow(/already exists/);
+ });
+});
+
+describe("agentExistsInProject", () => {
+ it("is false when the workspace dir doesn't exist", () => {
+ expect(agentExistsInProject("acme", "goal-nowhere")).toBe(false);
+ });
+
+ it("is false for an existing but empty dir (half-provisioned leftovers)", async () => {
+ await mkdir(join(agentsRoot(), "acme-goal-empty"), { recursive: true });
+ expect(agentExistsInProject("acme", "goal-empty")).toBe(false);
+ });
+
+ it("is true for a dir with contents", async () => {
+ await seedAgent("acme-goal-full", { "a.txt": "a" });
+ expect(agentExistsInProject("acme", "goal-full")).toBe(true);
+ });
+});
diff --git a/notfair/src/server/agents/provisioning.test.ts b/notfair/src/server/agents/provisioning.test.ts
new file mode 100644
index 00000000..fef1dc01
--- /dev/null
+++ b/notfair/src/server/agents/provisioning.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it, vi } from "vitest";
+import { join } from "node:path";
+import type { AgentProvisionSpec } from "@/server/adapters/types";
+
+// Point the workspace layout at a tmpdir — provisioning derives paths from
+// NOTFAIR_DATA_DIR and must never resolve to the developer's ~/.notfair.
+const h = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-provision-"));
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir, provisionAgent: vi.fn(async (_spec: AgentProvisionSpec) => {}) };
+});
+
+// Mock the harness boundary: the real adapter would write workspace files
+// and touch the developer's harness config.
+vi.mock("@/server/adapters/registry", () => ({
+ requireAdapter: vi.fn((id: string) => {
+ if (id !== "claude-code-local" && id !== "codex-local") {
+ throw new Error(`Unknown harness adapter: ${id}`);
+ }
+ return { provisionAgent: h.provisionAgent };
+ }),
+}));
+
+import { provisionAgent, workspaceDirFor } from "./provisioning";
+
+describe("workspaceDirFor", () => {
+ it("resolves under <data dir>/agents/<agent id>", () => {
+ expect(workspaceDirFor("acme-goal-alex")).toBe(
+ join(h.dataDir, "agents", "acme-goal-alex"),
+ );
+ });
+});
+
+describe("provisionAgent", () => {
+ it("hands the adapter a fully-resolved provision spec", async () => {
+ await provisionAgent({
+ projectSlug: "acme",
+ agentId: "acme-goal-alex",
+ displayName: "Alex",
+ templateKey: "goal",
+ identityMd: "# IDENTITY",
+ projectMd: "# PROJECT",
+ harnessAdapter: "claude-code-local",
+ });
+
+ expect(h.provisionAgent).toHaveBeenCalledTimes(1);
+ expect(h.provisionAgent).toHaveBeenCalledWith({
+ projectSlug: "acme",
+ agentId: "acme-goal-alex",
+ displayName: "Alex",
+ templateKey: "goal",
+ workspaceDir: join(h.dataDir, "agents", "acme-goal-alex"),
+ identityMd: "# IDENTITY",
+ projectMd: "# PROJECT",
+ });
+ });
+
+ it("propagates an unknown-adapter failure", async () => {
+ await expect(
+ provisionAgent({
+ projectSlug: "acme",
+ agentId: "acme-goal-alex",
+ displayName: "Alex",
+ templateKey: "goal",
+ identityMd: "# IDENTITY",
+ harnessAdapter: "not-a-harness" as never,
+ }),
+ ).rejects.toThrow(/Unknown harness adapter/);
+ });
+});
diff --git a/notfair/src/server/db/db.test.ts b/notfair/src/server/db/db.test.ts
new file mode 100644
index 00000000..1806a49d
--- /dev/null
+++ b/notfair/src/server/db/db.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it, vi } from "vitest";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+
+// Real better-sqlite3 against a tmpdir DB, per repo test conventions.
+// MUST be hoisted: db.ts captures NOTFAIR_DATA_DIR at import time, so a
+// plain assignment would point the suite at the developer's live ~/.notfair.
+const h = vi.hoisted(() => {
+ const { mkdtempSync, rmSync } = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-db-"));
+ // getDb creates the data dir itself when missing — exercise that path.
+ rmSync(dataDir, { recursive: true, force: true });
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir };
+});
+
+import { getDb, getDbPath } from "./db";
+
+describe("getDb", () => {
+ it("creates the data dir + db file and applies the schema", () => {
+ expect(existsSync(h.dataDir)).toBe(false);
+ const db = getDb();
+ expect(existsSync(join(h.dataDir, "db.sqlite"))).toBe(true);
+ // Schema applied: core tables exist.
+ const tables = db
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
+ .all() as Array<{ name: string }>;
+ const names = tables.map((t) => t.name);
+ expect(names).toContain("projects");
+ expect(names).toContain("sessions");
+ expect(names).toContain("transcript_events");
+ });
+
+ it("configures WAL journaling and foreign keys", () => {
+ const db = getDb();
+ expect(db.pragma("journal_mode", { simple: true })).toBe("wal");
+ expect(db.pragma("foreign_keys", { simple: true })).toBe(1);
+ expect(db.pragma("busy_timeout", { simple: true })).toBe(5000);
+ });
+
+ it("caches the connection — repeated calls return the same instance", () => {
+ expect(getDb()).toBe(getDb());
+ });
+});
+
+describe("getDbPath", () => {
+ it("points at db.sqlite inside the data dir", () => {
+ expect(getDbPath()).toBe(join(h.dataDir, "db.sqlite"));
+ });
+});
diff --git a/notfair/src/server/db/projects.test.ts b/notfair/src/server/db/projects.test.ts
new file mode 100644
index 00000000..f51e6d0f
--- /dev/null
+++ b/notfair/src/server/db/projects.test.ts
@@ -0,0 +1,280 @@
+import { describe, expect, it } from "vitest";
+import { 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-db-projects-"));
+});
+
+import { getDb } from "./db";
+import {
+ addHiddenMcpPresetKey,
+ archiveProject,
+ changeProjectSlug,
+ createProject,
+ deleteProjectRow,
+ getHiddenMcpPresetKeys,
+ getProject,
+ listProjects,
+ removeHiddenMcpPresetKey,
+ renameProject,
+ setProjectCodebasePath,
+ setProjectGoogleAdsAccount,
+ setProjectGscProperty,
+ setProjectHarnessAdapter,
+ setProjectMetaAdsAccount,
+ unarchiveProject,
+} from "./projects";
+import { createGoal } from "./goals";
+import { insertUserMcpServer, listUserMcpServers } from "./user-mcp-servers";
+
+describe("createProject", () => {
+ it("creates a project with defaults and a slug from the display name", () => {
+ const result = createProject({ display_name: " Acme Corp " });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.project.slug).toBe("acme-corp");
+ expect(result.project.display_name).toBe("Acme Corp");
+ expect(result.project.harness_adapter).toBe("claude-code-local");
+ expect(result.project.website_url).toBeNull();
+ expect(result.project.codebase_path).toBeNull();
+ // Round-trips through the DB.
+ expect(getProject("acme-corp")).toMatchObject({
+ slug: "acme-corp",
+ display_name: "Acme Corp",
+ archived_at: null,
+ });
+ });
+
+ it("rejects an unusable display name", () => {
+ const result = createProject({ display_name: "###" });
+ expect(result.ok).toBe(false);
+ });
+
+ it("rejects a duplicate slug", () => {
+ createProject({ display_name: "Dup Target" });
+ const result = createProject({ display_name: "Dup Target" });
+ expect(result).toMatchObject({ ok: false });
+ if (result.ok) return;
+ expect(result.reason).toContain("already exists");
+ });
+
+ it("honors an explicit slug, harness adapter, and trims optional hints", () => {
+ const result = createProject({
+ display_name: "Hints",
+ slug: "hints-custom",
+ website_url: " https://hints.dev ",
+ codebase_path: " ",
+ harness_adapter: "codex-local",
+ });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.project.slug).toBe("hints-custom");
+ expect(result.project.website_url).toBe("https://hints.dev");
+ expect(result.project.codebase_path).toBeNull();
+ expect(result.project.harness_adapter).toBe("codex-local");
+ });
+});
+
+describe("listProjects", () => {
+ it("filters archived projects unless asked for them", () => {
+ createProject({ display_name: "List Live" });
+ createProject({ display_name: "List Archived" });
+ archiveProject("list-archived");
+
+ const live = listProjects().map((p) => p.slug);
+ expect(live).toContain("list-live");
+ expect(live).not.toContain("list-archived");
+
+ const all = listProjects({ includeArchived: true }).map((p) => p.slug);
+ expect(all).toContain("list-archived");
+ });
+});
+
+describe("getProject", () => {
+ it("returns null for a missing slug", () => {
+ expect(getProject("nope-never")).toBeNull();
+ });
+});
+
+describe("project field setters", () => {
+ it("returns null when the project doesn't exist", () => {
+ expect(setProjectGoogleAdsAccount("ghost", "123")).toBeNull();
+ expect(setProjectMetaAdsAccount("ghost", "act_1")).toBeNull();
+ expect(setProjectCodebasePath("ghost", "/tmp")).toBeNull();
+ expect(setProjectGscProperty("ghost", "sc-domain:x")).toBeNull();
+ });
+
+ it("sets and clears the per-platform account fields", () => {
+ createProject({ display_name: "Setters" });
+ expect(setProjectGoogleAdsAccount("setters", "111")?.google_ads_account_id).toBe("111");
+ expect(setProjectMetaAdsAccount("setters", "act_2")?.meta_ads_account_id).toBe("act_2");
+ expect(setProjectCodebasePath("setters", "/repo")?.codebase_path).toBe("/repo");
+ expect(setProjectGscProperty("setters", "sc-domain:s")?.gsc_property_id).toBe("sc-domain:s");
+ expect(setProjectGoogleAdsAccount("setters", null)?.google_ads_account_id).toBeNull();
+ });
+
+ it("swaps the harness adapter", () => {
+ createProject({ display_name: "Adapter Swap" });
+ expect(setProjectHarnessAdapter("adapter-swap", "codex-local")?.harness_adapter).toBe(
+ "codex-local",
+ );
+ });
+});
+
+describe("renameProject", () => {
+ it("rejects an empty name and trims a valid one", () => {
+ createProject({ display_name: "Rename Me" });
+ expect(renameProject("rename-me", " ")).toBeNull();
+ expect(renameProject("rename-me", " Renamed ")?.display_name).toBe("Renamed");
+ });
+});
+
+describe("archive / unarchive", () => {
+ it("stamps and clears archived_at", () => {
+ createProject({ display_name: "Arch" });
+ const archived = archiveProject("arch");
+ expect(archived?.archived_at).toBeTruthy();
+ // Re-archiving doesn't overwrite the original stamp.
+ expect(archiveProject("arch")?.archived_at).toBe(archived?.archived_at);
+ expect(unarchiveProject("arch")?.archived_at).toBeNull();
+ });
+});
+
+describe("changeProjectSlug", () => {
+ it("handles the same-slug display-name-only path", () => {
+ createProject({ display_name: "Same Slug" });
+ const updated = changeProjectSlug("same-slug", "same-slug", " Same Slug 2 ");
+ expect(updated?.display_name).toBe("Same Slug 2");
+ expect(changeProjectSlug("same-slug", "same-slug")?.slug).toBe("same-slug");
+ });
+
+ it("returns null when the source slug doesn't exist", () => {
+ expect(changeProjectSlug("ghost-src", "ghost-dst")).toBeNull();
+ });
+
+ it("throws when the destination slug is taken", () => {
+ createProject({ display_name: "Slug Src" });
+ createProject({ display_name: "Slug Dst" });
+ expect(() => changeProjectSlug("slug-src", "slug-dst")).toThrow(
+ "already exists",
+ );
+ });
+
+ it("migrates every child row keyed off project_slug", () => {
+ createProject({ display_name: "Move Src" });
+ const now = new Date().toISOString();
+ getDb()
+ .prepare(
+ `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)
+ VALUES ('mv-s1', 'move-src', 'move-src-goal-1', 'main', 'claude-code-local', ?, ?)`,
+ )
+ .run(now, now);
+ const goal = createGoal({
+ project_slug: "move-src",
+ agent_id: "move-src-goal-1",
+ statement: "grow",
+ });
+ insertUserMcpServer({
+ project_slug: "move-src",
+ key: "acme",
+ display_name: "Acme",
+ resource_url: "https://mcp.acme.dev/sse",
+ discovery_url: "https://mcp.acme.dev/.well-known/oauth-protected-resource/sse",
+ });
+
+ const moved = changeProjectSlug("move-src", "move-dst", "Move Dst");
+ expect(moved).toMatchObject({ slug: "move-dst", display_name: "Move Dst" });
+ expect(getProject("move-src")).toBeNull();
+
+ const session = getDb()
+ .prepare("SELECT project_slug FROM sessions WHERE id = 'mv-s1'")
+ .get() as { project_slug: string };
+ expect(session.project_slug).toBe("move-dst");
+ const movedGoal = getDb()
+ .prepare("SELECT project_slug FROM goals WHERE id = ?")
+ .get(goal.id) as { project_slug: string };
+ expect(movedGoal.project_slug).toBe("move-dst");
+ expect(listUserMcpServers("move-dst").map((r) => r.key)).toEqual(["acme"]);
+ expect(listUserMcpServers("move-src")).toEqual([]);
+ });
+});
+
+describe("deleteProjectRow", () => {
+ it("deletes the project and every child row", () => {
+ createProject({ display_name: "Del Me" });
+ const now = new Date().toISOString();
+ getDb()
+ .prepare(
+ `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)
+ VALUES ('del-s1', 'del-me', 'del-me-goal-1', 'main', 'claude-code-local', ?, ?)`,
+ )
+ .run(now, now);
+ createGoal({ project_slug: "del-me", agent_id: "del-me-goal-1" });
+ insertUserMcpServer({
+ project_slug: "del-me",
+ key: "gone",
+ display_name: "Gone",
+ resource_url: "https://mcp.gone.dev",
+ discovery_url: "https://mcp.gone.dev/.well-known/oauth-protected-resource",
+ });
+
+ deleteProjectRow("del-me");
+
+ expect(getProject("del-me")).toBeNull();
+ const counts = getDb()
+ .prepare(
+ `SELECT
+ (SELECT COUNT(*) FROM sessions WHERE project_slug = 'del-me') AS sessions,
+ (SELECT COUNT(*) FROM goals WHERE project_slug = 'del-me') AS goals,
+ (SELECT COUNT(*) FROM user_mcp_servers WHERE project_slug = 'del-me') AS mcps`,
+ )
+ .get() as { sessions: number; goals: number; mcps: number };
+ expect(counts).toEqual({ sessions: 0, goals: 0, mcps: 0 });
+ });
+});
+
+describe("hidden MCP preset keys", () => {
+ it("adds, dedupes, and removes keys", () => {
+ createProject({ display_name: "Hide List" });
+ expect(getHiddenMcpPresetKeys("hide-list")).toEqual([]);
+
+ addHiddenMcpPresetKey("hide-list", "notfair-googleads");
+ addHiddenMcpPresetKey("hide-list", "notfair-googleads"); // no dup
+ addHiddenMcpPresetKey("hide-list", "notfair-metaads");
+ expect(getHiddenMcpPresetKeys("hide-list")).toEqual([
+ "notfair-googleads",
+ "notfair-metaads",
+ ]);
+
+ removeHiddenMcpPresetKey("hide-list", "notfair-googleads");
+ expect(getHiddenMcpPresetKeys("hide-list")).toEqual(["notfair-metaads"]);
+ // Removing an absent key is a no-op (no write).
+ removeHiddenMcpPresetKey("hide-list", "notfair-googleads");
+ expect(getHiddenMcpPresetKeys("hide-list")).toEqual(["notfair-metaads"]);
+ });
+
+ it("tolerates corrupt or non-array JSON in the column", () => {
+ createProject({ display_name: "Hide Corrupt" });
+ getDb()
+ .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")
+ .run("{not json", "hide-corrupt");
+ expect(getHiddenMcpPresetKeys("hide-corrupt")).toEqual([]);
+ getDb()
+ .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")
+ .run('{"a":1}', "hide-corrupt");
+ expect(getHiddenMcpPresetKeys("hide-corrupt")).toEqual([]);
+ getDb()
+ .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")
+ .run('["ok", 42]', "hide-corrupt");
+ expect(getHiddenMcpPresetKeys("hide-corrupt")).toEqual(["ok"]);
+ // Missing project → empty list.
+ expect(getHiddenMcpPresetKeys("no-such-project")).toEqual([]);
+ });
+});
diff --git a/notfair/src/server/db/user-mcp-servers.test.ts b/notfair/src/server/db/user-mcp-servers.test.ts
new file mode 100644
index 00000000..a374ebcc
--- /dev/null
+++ b/notfair/src/server/db/user-mcp-servers.test.ts
@@ -0,0 +1,120 @@
+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-db-umcp-"));
+});
+
+import { getDb } from "@/server/db/db";
+import {
+ deleteUserMcpServer,
+ findUserMcpServer,
+ findUserMcpServerByResourceUrl,
+ insertUserMcpServer,
+ listUserMcpServers,
+} from "./user-mcp-servers";
+
+const SLUG = "proj";
+
+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());
+});
+
+describe("insertUserMcpServer / findUserMcpServer", () => {
+ it("inserts a row and reads it back by key", () => {
+ const row = insertUserMcpServer({
+ project_slug: SLUG,
+ key: "acme",
+ display_name: "Acme MCP",
+ resource_url: "https://mcp.acme.dev/sse",
+ discovery_url:
+ "https://mcp.acme.dev/.well-known/oauth-protected-resource/sse",
+ });
+ expect(row.id).toBeTruthy();
+ expect(row.description).toBe(""); // defaulted when omitted
+
+ const found = findUserMcpServer(SLUG, "acme");
+ expect(found).toMatchObject({
+ project_slug: SLUG,
+ key: "acme",
+ display_name: "Acme MCP",
+ description: "",
+ resource_url: "https://mcp.acme.dev/sse",
+ });
+ });
+
+ it("returns null for a missing key or wrong project", () => {
+ expect(findUserMcpServer(SLUG, "nope")).toBeNull();
+ expect(findUserMcpServer("other-proj", "acme")).toBeNull();
+ });
+});
+
+describe("findUserMcpServerByResourceUrl", () => {
+ it("matches regardless of trailing slash, host case, and default port", () => {
+ for (const candidate of [
+ "https://mcp.acme.dev/sse/",
+ "https://MCP.ACME.DEV/sse",
+ "https://mcp.acme.dev:443/sse",
+ ]) {
+ expect(findUserMcpServerByResourceUrl(SLUG, candidate)?.key).toBe("acme");
+ }
+ });
+
+ it("returns null when no row matches", () => {
+ expect(
+ findUserMcpServerByResourceUrl(SLUG, "https://mcp.other.dev/sse"),
+ ).toBeNull();
+ // Path is case-sensitive by design.
+ expect(
+ findUserMcpServerByResourceUrl(SLUG, "https://mcp.acme.dev/SSE"),
+ ).toBeNull();
+ });
+
+ it("falls back to a lowercased string compare for unparseable URLs", () => {
+ insertUserMcpServer({
+ project_slug: SLUG,
+ key: "weird",
+ display_name: "Weird",
+ resource_url: "not a url",
+ discovery_url: "also not a url",
+ });
+ expect(findUserMcpServerByResourceUrl(SLUG, " NOT A URL/ ")?.key).toBe(
+ "weird",
+ );
+ });
+});
+
+describe("listUserMcpServers / deleteUserMcpServer", () => {
+ it("lists rows oldest-first and scopes to the project", () => {
+ // Force distinct created_at values so ORDER BY created_at is decisive.
+ getDb()
+ .prepare("UPDATE user_mcp_servers SET created_at = ? WHERE key = 'acme'")
+ .run("2026-01-01T00:00:00.000Z");
+ getDb()
+ .prepare("UPDATE user_mcp_servers SET created_at = ? WHERE key = 'weird'")
+ .run("2026-01-02T00:00:00.000Z");
+ expect(listUserMcpServers(SLUG).map((r) => r.key)).toEqual([
+ "acme",
+ "weird",
+ ]);
+ expect(listUserMcpServers("other-proj")).toEqual([]);
+ });
+
+ it("deletes only the (project, key) pair", () => {
+ deleteUserMcpServer("other-proj", "acme"); // wrong project: no-op
+ expect(findUserMcpServer(SLUG, "acme")).not.toBeNull();
+ deleteUserMcpServer(SLUG, "acme");
+ expect(findUserMcpServer(SLUG, "acme")).toBeNull();
+ expect(listUserMcpServers(SLUG).map((r) => r.key)).toEqual(["weird"]);
+ });
+});
diff --git a/notfair/src/server/fs/pick-folder.test.ts b/notfair/src/server/fs/pick-folder.test.ts
new file mode 100644
index 00000000..f0614436
--- /dev/null
+++ b/notfair/src/server/fs/pick-folder.test.ts
@@ -0,0 +1,199 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Never spawn real dialog binaries: mock the child_process + platform
+// boundary and drive each OS branch through the callback contract.
+type ExecCall = { cmd: string; args: string[] };
+type ExecOutcome = {
+ err?: (Error & { code?: number | string }) | null;
+ stdout?: string;
+ stderr?: string;
+};
+
+const h = vi.hoisted(() => {
+ const state = {
+ platform: "darwin" as string,
+ calls: [] as ExecCall[],
+ // Consumed in order — one entry per expected execFile invocation.
+ outcomes: [] as ExecOutcome[],
+ };
+ return { state };
+});
+
+vi.mock("node:os", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:os")>();
+ return { ...actual, platform: () => h.state.platform };
+});
+vi.mock("node:child_process", () => ({
+ execFile: (
+ cmd: string,
+ args: string[],
+ _opts: unknown,
+ cb: (err: Error | null, stdout: string, stderr: string) => void,
+ ) => {
+ h.state.calls.push({ cmd, args });
+ const outcome = h.state.outcomes.shift() ?? {};
+ queueMicrotask(() =>
+ cb(outcome.err ?? null, outcome.stdout ?? "", outcome.stderr ?? ""),
+ );
+ },
+}));
+
+import { pickFolder } from "./pick-folder";
+
+function errWithCode(code: number | string): Error & { code: number | string } {
+ return Object.assign(new Error(`exec failed (${code})`), { code });
+}
+
+beforeEach(() => {
+ h.state.platform = "darwin";
+ h.state.calls = [];
+ h.state.outcomes = [];
+});
+
+describe("platform dispatch", () => {
+ it("reports unsupported on Windows without spawning anything", async () => {
+ h.state.platform = "win32";
+ await expect(pickFolder({})).resolves.toEqual({
+ ok: false,
+ kind: "unsupported",
+ platform: "win32",
+ });
+ expect(h.state.calls).toHaveLength(0);
+ });
+});
+
+describe("macOS (osascript)", () => {
+ it("returns the picked path with the trailing slash stripped", async () => {
+ h.state.outcomes = [{ stdout: "/Users/me/Sites/acme/\n" }];
+ await expect(pickFolder({})).resolves.toEqual({
+ ok: true,
+ path: "/Users/me/Sites/acme",
+ });
+ expect(h.state.calls[0]!.cmd).toBe("/usr/bin/osascript");
+ expect(h.state.calls[0]!.args[0]).toBe("-e");
+ });
+
+ it("passes the prompt and default location into the script, escaped", async () => {
+ h.state.outcomes = [{ stdout: "/tmp/x/\n" }];
+ await pickFolder({
+ prompt: 'Pick "the" folder',
+ defaultLocation: '/Users/me/"quoted"',
+ });
+ const script = h.state.calls[0]!.args[1]!;
+ expect(script).toContain('choose folder with prompt "Pick \\"the\\" folder"');
+ expect(script).toContain('default location POSIX file "/Users/me/\\"quoted\\""');
+ });
+
+ it("omits the default-location clause when none is given", async () => {
+ h.state.outcomes = [{ stdout: "/tmp/x\n" }];
+ await pickFolder({});
+ const script = h.state.calls[0]!.args[1]!;
+ expect(script).toContain('choose folder with prompt "Select a folder"');
+ expect(script).not.toContain("default location");
+ });
+
+ it("maps the cancel sentinel to kind: cancelled", async () => {
+ h.state.outcomes = [{ stdout: "__USER_CANCELLED__\n" }];
+ await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });
+ });
+
+ it("treats empty output as cancelled", async () => {
+ h.state.outcomes = [{ stdout: "" }];
+ await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });
+ });
+
+ it("surfaces stderr when osascript exits non-zero", async () => {
+ h.state.outcomes = [
+ { err: errWithCode(1), stderr: "execution error: boom (-1)" },
+ ];
+ await expect(pickFolder({})).resolves.toEqual({
+ ok: false,
+ kind: "error",
+ message: "execution error: boom (-1)",
+ });
+ });
+
+ it("falls back to the exit code when stderr is empty", async () => {
+ h.state.outcomes = [{ err: errWithCode(2), stderr: "" }];
+ await expect(pickFolder({})).resolves.toEqual({
+ ok: false,
+ kind: "error",
+ message: "osascript exited with code 2",
+ });
+ });
+});
+
+describe("Linux (zenity → kdialog)", () => {
+ beforeEach(() => {
+ h.state.platform = "linux";
+ });
+
+ it("uses zenity when available and returns the picked path", async () => {
+ h.state.outcomes = [{ stdout: "/home/me/proj/\n" }];
+ await expect(
+ pickFolder({ prompt: "Pick it", defaultLocation: "/home/me" }),
+ ).resolves.toEqual({ ok: true, path: "/home/me/proj" });
+ expect(h.state.calls).toEqual([
+ {
+ cmd: "zenity",
+ args: [
+ "--file-selection",
+ "--directory",
+ "--title=Pick it",
+ "--filename=/home/me/",
+ ],
+ },
+ ]);
+ });
+
+ it("falls back to kdialog when zenity is not installed", async () => {
+ h.state.outcomes = [
+ { err: errWithCode("ENOENT") }, // zenity missing
+ { stdout: "/home/me/other\n" }, // kdialog succeeds
+ ];
+ await expect(pickFolder({ prompt: "Pick it" })).resolves.toEqual({
+ ok: true,
+ path: "/home/me/other",
+ });
+ expect(h.state.calls.map((c) => c.cmd)).toEqual(["zenity", "kdialog"]);
+ expect(h.state.calls[1]!.args).toEqual([
+ "--getexistingdirectory",
+ "",
+ "--title",
+ "Pick it",
+ ]);
+ });
+
+ it("reports a clear install hint when neither tool exists", async () => {
+ h.state.outcomes = [
+ { err: errWithCode("ENOENT") },
+ { err: errWithCode("ENOENT") },
+ ];
+ const result = await pickFolder({});
+ expect(result).toMatchObject({ ok: false, kind: "error" });
+ expect((result as { message: string }).message).toMatch(
+ /zenity.*kdialog|kdialog.*zenity/i,
+ );
+ });
+
+ it("maps zenity exit code 1 to cancelled", async () => {
+ h.state.outcomes = [{ err: errWithCode(1) }];
+ await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });
+ });
+
+ it("treats empty dialog output as cancelled", async () => {
+ h.state.outcomes = [{ stdout: "\n" }];
+ await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });
+ });
+
+ it("surfaces other dialog failures as errors", async () => {
+ h.state.outcomes = [
+ { err: errWithCode(255), stderr: "cannot open display" },
+ ];
+ await expect(pickFolder({})).resolves.toEqual({
+ ok: false,
+ kind: "error",
+ message: "cannot open display",
+ });
+ });
+});
diff --git a/notfair/src/server/goals/handlers.test.ts b/notfair/src/server/goals/handlers.test.ts
new file mode 100644
index 00000000..6138ab8f
--- /dev/null
+++ b/notfair/src/server/goals/handlers.test.ts
@@ -0,0 +1,794 @@
+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-handlers-"));
+});
+
+const mocks = vi.hoisted(() => ({
+ runMetricSource: vi.fn(),
+ runHistorySource: vi.fn(),
+ syncGoalIdentity: vi.fn(async () => {}),
+ syncProjectAgents: vi.fn(async () => 3),
+ runGoalTick: vi.fn(async () => {}),
+ syncGoalPrs: vi.fn(async () => {}),
+}));
+
+// Boundary mocks: metric execution (subprocess / MCP), identity re-render
+// (adapter runtime), the first tick (adapter runtime), and PR sync (gh).
+vi.mock("./metric", () => ({
+ LOCAL_SOURCE_KEY: "local",
+ runMetricSource: mocks.runMetricSource,
+ runHistorySource: mocks.runHistorySource,
+}));
+vi.mock("./provision", () => ({
+ syncGoalIdentity: mocks.syncGoalIdentity,
+ syncProjectAgents: mocks.syncProjectAgents,
+}));
+vi.mock("./tick", () => ({ runGoalTick: mocks.runGoalTick }));
+vi.mock("./pr-sync", () => ({
+ syncGoalPrs: mocks.syncGoalPrs,
+ maybeSyncGoalPrs: vi.fn(),
+}));
+
+import {
+ handleAddSupportMetric,
+ handleAmendGoal,
+ handleBackfillHistory,
+ handleDefineGoal,
+ handleGetGoal,
+ handleGetProject,
+ handleLogGoalAction,
+ handleLogLearning,
+ handleProposeGoalMetric,
+ handleProposeTarget,
+ handleReviewGoalAction,
+ handleSearchLearnings,
+ handleSetProjectBrief,
+ handleUpdateGoalStatus,
+} from "./handlers";
+import { getDb } from "@/server/db/db";
+import {
+ addGoalLearning,
+ createGoal,
+ createGoalAction,
+ getGoal,
+ listGoalLearnings,
+ listMetricSnapshots,
+ proposeTarget,
+ recordMetricSnapshot,
+ setGoalMetric,
+ setGoalStatus,
+ type Goal,
+} from "@/server/db/goals";
+import { listSupportMetrics } from "@/server/db/goal-support-metrics";
+import { readProjectBrief } from "@/server/onboarding/project-brief";
+import { PROJECT_BRIEF_MAX_BYTES } from "@/server/onboarding/project-brief";
+
+const SLUG = "proj";
+const ctxFor = (agent_id: string) => ({ project_slug: SLUG, agent_id });
+
+const LOCAL_SPEC = {
+ metric_source_key: "local",
+ metric_source_tool: "shell",
+ metric_source_args_json: JSON.stringify({ command: "echo 1" }),
+};
+
+function makeIntakeGoal(agent: string, statement = "Grow organic clicks"): Goal {
+ return createGoal({ project_slug: SLUG, agent_id: agent, statement });
+}
+
+function makeProposedGoal(agent: string): Goal {
+ const goal = makeIntakeGoal(agent);
+ return setGoalMetric(goal.id, {
+ metric_name: "clicks",
+ ...LOCAL_SPEC,
+ metric_direction: "increase",
+ baseline_value: 10,
+ })!;
+}
+
+function makeActiveGoal(agent: string): Goal {
+ const goal = makeProposedGoal(agent);
+ return proposeTarget(goal.id, { target_value: 100 })!;
+}
+
+beforeAll(() => {
+ const ts = new Date().toISOString();
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",
+ )
+ .run(SLUG, ts);
+ getDb()
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p2', 'other', 'Other', ?, 'claude-code-local')",
+ )
+ .run(ts);
+});
+
+beforeEach(() => {
+ mocks.runMetricSource.mockReset();
+ mocks.runHistorySource.mockReset();
+ mocks.runGoalTick.mockClear();
+ mocks.syncProjectAgents.mockClear();
+});
+
+describe("goal resolution / authorization", () => {
+ it("rejects an unknown goal id", async () => {
+ const r = await handleGetGoal({ goal_id: "nope" }, ctxFor("a"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Unknown goal_id");
+ });
+
+ it("rejects cross-project access", async () => {
+ const foreign = createGoal({ project_slug: "other", agent_id: "x-1", statement: "s" });
+ const r = await handleGetGoal({ goal_id: foreign.id }, ctxFor("x-1"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Cross-project");
+ });
+
+ it("rejects owner-required calls from another agent", () => {
+ const goal = makeIntakeGoal("own-1");
+ const r = handleDefineGoal(
+ { goal_id: goal.id, statement: "s", short_label: "l" },
+ ctxFor("someone-else"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("owned by 'own-1'");
+ });
+});
+
+describe("handleGetGoal", () => {
+ it("assembles the full state view", async () => {
+ const goal = makeActiveGoal("view-1");
+ recordMetricSnapshot(goal.id, 42, "tick");
+ addGoalLearning(goal.id, "Tuesday spikes are noise", "high");
+ createGoalAction({
+ goal_id: goal.id,
+ kind: "mutation",
+ description: "raised bids",
+ expected_effect: "more clicks",
+ review_after: new Date(Date.now() + 3600_000).toISOString(),
+ spend_usd: 12.5,
+ });
+ // Another agent's gated action in the same project is surfaced too.
+ const other = makeActiveGoal("view-2");
+ createGoalAction({
+ goal_id: other.id,
+ kind: "mutation",
+ description: "their experiment",
+ resources_touched: ["campaign:9"],
+ expected_effect: "n/a",
+ review_after: new Date(Date.now() + 3600_000).toISOString(),
+ });
+
+ const r = await handleGetGoal({ goal_id: goal.id }, ctxFor("view-1"));
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.data.goal.id).toBe(goal.id);
+ expect(r.data.target_met).toBe(false); // 42 < 100
+ expect(r.data.actions_gated).toHaveLength(1);
+ expect(r.data.actions_due_for_review).toHaveLength(0);
+ expect(r.data.recent_learnings[0]!.body).toContain("Tuesday");
+ expect(r.data.metric_history.map((s) => s.value)).toContain(42);
+ expect(r.data.logged_spend_usd).toBe(12.5);
+ expect(r.data.gated_by_other_agents).toEqual([
+ expect.objectContaining({ agent_id: "view-2", resources: ["campaign:9"] }),
+ ]);
+ });
+});
+
+describe("handleDefineGoal", () => {
+ it("records the trimmed statement and clamps the label to 48 chars", () => {
+ const goal = makeIntakeGoal("def-1", "");
+ const r = handleDefineGoal(
+ {
+ goal_id: goal.id,
+ statement: " Grow signups ",
+ short_label: ` ${"x".repeat(60)} `,
+ },
+ ctxFor("def-1"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.statement).toBe("Grow signups");
+ expect(getGoal(goal.id)!.short_label).toHaveLength(48);
+ });
+
+ it("refuses once the goal has left intake", () => {
+ const goal = makeProposedGoal("def-2");
+ const r = handleDefineGoal(
+ { goal_id: goal.id, statement: "s", short_label: "l" },
+ ctxFor("def-2"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("'proposed', not 'intake'");
+ });
+});
+
+describe("handleProposeGoalMetric", () => {
+ const input = (goal_id: string, key = "local") => ({
+ goal_id,
+ metric_name: "clicks",
+ metric_source_key: key,
+ metric_source_tool: "shell",
+ metric_source_args_json: JSON.stringify({ command: "echo 42" }),
+ metric_direction: "increase" as const,
+ });
+
+ it("refuses outside intake", async () => {
+ const goal = makeProposedGoal("pm-1");
+ const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-1"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("not 'intake'");
+ });
+
+ it("requires a defined statement first", async () => {
+ const goal = makeIntakeGoal("pm-2", "");
+ const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-2"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("define_goal");
+ });
+
+ it("rejects a non-local source without a connected MCP token", async () => {
+ const goal = makeIntakeGoal("pm-3");
+ const r = await handleProposeGoalMetric(
+ input(goal.id, "notfair-googleads"),
+ ctxFor("pm-3"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("No connected MCP 'notfair-googleads'");
+ expect(mocks.runMetricSource).not.toHaveBeenCalled();
+ });
+
+ it("bounces a metric the platform cannot reproduce", async () => {
+ const goal = makeIntakeGoal("pm-4");
+ mocks.runMetricSource.mockResolvedValueOnce({ ok: false, error: "shell exploded" });
+ const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-4"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("shell exploded");
+ expect(getGoal(goal.id)!.status).toBe("intake");
+ });
+
+ it("verifies server-side, moves to proposed, and snapshots the baseline", async () => {
+ const goal = makeIntakeGoal("pm-5");
+ mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 42 });
+ const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-5"));
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.baseline_value).toBe(42);
+ expect(r.data.status).toBe("proposed");
+ }
+ const fresh = getGoal(goal.id)!;
+ expect(fresh.baseline_value).toBe(42);
+ expect(fresh.current_value).toBe(42);
+ const snaps = listMetricSnapshots(goal.id);
+ expect(snaps).toEqual([expect.objectContaining({ value: 42, source: "intake" })]);
+ });
+});
+
+describe("handleBackfillHistory", () => {
+ const input = (goal_id: string, key = "local") => ({
+ goal_id,
+ source_key: key,
+ source_tool: "shell",
+ source_args_json: JSON.stringify({ command: "echo history" }),
+ });
+
+ it("rejects an unconnected source", async () => {
+ const goal = makeProposedGoal("bf-1");
+ const r = await handleBackfillHistory(input(goal.id, "nope-mcp"), ctxFor("bf-1"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("No connected MCP");
+ });
+
+ it("surfaces a failing history query", async () => {
+ const goal = makeProposedGoal("bf-2");
+ mocks.runHistorySource.mockResolvedValueOnce({ ok: false, error: "bad rows" });
+ const r = await handleBackfillHistory(input(goal.id), ctxFor("bf-2"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toBe("bad rows");
+ });
+
+ it("rejects a series with only future-dated points", async () => {
+ const goal = makeProposedGoal("bf-3");
+ mocks.runHistorySource.mockResolvedValueOnce({
+ ok: true,
+ points: [{ date: new Date(Date.now() + 86_400_000).toISOString(), value: 1 }],
+ });
+ const r = await handleBackfillHistory(input(goal.id), ctxFor("bf-3"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("no past-dated points");
+ });
+
+ it("stores past points and drops future ones", async () => {
+ const goal = makeProposedGoal("bf-4");
+ mocks.runHistorySource.mockResolvedValueOnce({
+ ok: true,
+ points: [
+ { date: "2026-07-01T00:00:00.000Z", value: 5 },
+ { date: "2026-07-02T00:00:00.000Z", value: 6 },
+ { date: new Date(Date.now() + 86_400_000).toISOString(), value: 99 },
+ ],
+ });
+ const r = await handleBackfillHistory(input(goal.id), ctxFor("bf-4"));
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.points).toBe(2);
+ expect(r.data.from).toBe("2026-07-01");
+ expect(r.data.to).toBe("2026-07-02");
+ }
+ const snaps = listMetricSnapshots(goal.id);
+ expect(snaps.map((s) => s.value)).toEqual([5, 6]);
+ expect(snaps.every((s) => s.source === "backfill")).toBe(true);
+ });
+});
+
+describe("handleAddSupportMetric", () => {
+ const input = (goal_id: string, over: Record<string, unknown> = {}) => ({
+ goal_id,
+ name: "impressions",
+ source_key: "local",
+ source_tool: "shell",
+ source_args_json: JSON.stringify({ command: "echo 7" }),
+ ...over,
+ });
+
+ it("requires a name", async () => {
+ const goal = makeActiveGoal("sm-1");
+ const r = await handleAddSupportMetric(input(goal.id, { name: " " }), ctxFor("sm-1"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("name");
+ });
+
+ it("refuses shadowing the primary metric", async () => {
+ const goal = makeActiveGoal("sm-2");
+ const r = await handleAddSupportMetric(
+ input(goal.id, { name: "clicks" }),
+ ctxFor("sm-2"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("primary metric");
+ });
+
+ it("rejects an unconnected source", async () => {
+ const goal = makeActiveGoal("sm-3");
+ const r = await handleAddSupportMetric(
+ input(goal.id, { source_key: "nope-mcp" }),
+ ctxFor("sm-3"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("No connected MCP");
+ });
+
+ it("bounces an unverifiable metric", async () => {
+ const goal = makeActiveGoal("sm-4");
+ mocks.runMetricSource.mockResolvedValueOnce({ ok: false, error: "no such column" });
+ const r = await handleAddSupportMetric(input(goal.id), ctxFor("sm-4"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("no such column");
+ expect(listSupportMetrics(goal.id)).toHaveLength(0);
+ });
+
+ it("stores the verified metric (no history)", async () => {
+ const goal = makeActiveGoal("sm-5");
+ mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 7 });
+ const r = await handleAddSupportMetric(input(goal.id), ctxFor("sm-5"));
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.metric.name).toBe("impressions");
+ expect(r.data.metric.baseline_value).toBe(7);
+ expect(r.data.backfilled).toBe(0);
+ }
+ });
+
+ it("backfills history when provided", async () => {
+ const goal = makeActiveGoal("sm-6");
+ mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 7 });
+ mocks.runHistorySource.mockResolvedValueOnce({
+ ok: true,
+ points: [
+ { date: "2026-07-01T00:00:00.000Z", value: 3 },
+ { date: new Date(Date.now() + 86_400_000).toISOString(), value: 9 },
+ ],
+ });
+ const r = await handleAddSupportMetric(
+ input(goal.id, { history_args_json: JSON.stringify({ command: "echo rows" }) }),
+ ctxFor("sm-6"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.backfilled).toBe(1); // future point dropped
+ });
+
+ it("keeps the metric but fails the call when history breaks", async () => {
+ const goal = makeActiveGoal("sm-7");
+ mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 7 });
+ mocks.runHistorySource.mockResolvedValueOnce({ ok: false, error: "bad shape" });
+ const r = await handleAddSupportMetric(
+ input(goal.id, { history_args_json: JSON.stringify({ command: "echo rows" }) }),
+ ctxFor("sm-7"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Metric stored, but the history query failed");
+ expect(listSupportMetrics(goal.id)).toHaveLength(1);
+ });
+});
+
+describe("handleProposeTarget", () => {
+ it("refuses before the metric is verified", () => {
+ const goal = makeIntakeGoal("pt-1");
+ const r = handleProposeTarget({ goal_id: goal.id, target_value: 5 }, ctxFor("pt-1"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("not 'proposed'");
+ });
+
+ it("rejects a target on the wrong side of the baseline (achieve)", () => {
+ const inc = makeProposedGoal("pt-2"); // increase, baseline 10
+ const below = handleProposeTarget({ goal_id: inc.id, target_value: 5 }, ctxFor("pt-2"));
+ expect(below.ok).toBe(false);
+ if (!below.ok) expect(below.error).toContain("'increase'");
+
+ const decGoal = makeIntakeGoal("pt-3");
+ setGoalMetric(decGoal.id, {
+ metric_name: "waste",
+ ...LOCAL_SPEC,
+ metric_direction: "decrease",
+ baseline_value: 10,
+ });
+ const above = handleProposeTarget(
+ { goal_id: decGoal.id, target_value: 20 },
+ ctxFor("pt-3"),
+ );
+ expect(above.ok).toBe(false);
+ if (!above.ok) expect(above.error).toContain("'decrease'");
+ });
+
+ it("maintain targets may sit on the already-met side", async () => {
+ const goal = makeProposedGoal("pt-4"); // increase, baseline 10
+ const r = handleProposeTarget(
+ { goal_id: goal.id, target_value: 5, mode: "maintain" },
+ ctxFor("pt-4"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.status).toBe("active");
+ expect(getGoal(goal.id)!.mode).toBe("maintain");
+ // The first tick fires immediately on confirmation.
+ await new Promise((r) => setImmediate(r));
+ expect(mocks.runGoalTick).toHaveBeenCalledWith(
+ expect.objectContaining({ id: goal.id }),
+ "manual",
+ );
+ });
+
+ it("surfaces an invalid cadence cron as an error result", () => {
+ const goal = makeProposedGoal("pt-5");
+ const r = handleProposeTarget(
+ { goal_id: goal.id, target_value: 100, cadence_cron: "not a cron" },
+ ctxFor("pt-5"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Invalid cadence cron");
+ });
+});
+
+describe("handleAmendGoal", () => {
+ it("only applies to active/paused goals", () => {
+ const goal = makeIntakeGoal("am-1");
+ const r = handleAmendGoal({ goal_id: goal.id, target_value: 5 }, ctxFor("am-1"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("amend applies to active/paused");
+ });
+
+ it("requires at least one field", () => {
+ const goal = makeActiveGoal("am-2");
+ const r = handleAmendGoal({ goal_id: goal.id }, ctxFor("am-2"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Nothing to amend");
+ });
+
+ it("re-checks target direction on amendment", () => {
+ const goal = makeActiveGoal("am-3"); // increase, baseline 10
+ const r = handleAmendGoal({ goal_id: goal.id, target_value: 3 }, ctxFor("am-3"));
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("'increase'");
+ });
+
+ it("surfaces an invalid cron as an error result", () => {
+ const goal = makeActiveGoal("am-4");
+ const r = handleAmendGoal(
+ { goal_id: goal.id, cadence_cron: "nope" },
+ ctxFor("am-4"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Invalid cadence cron");
+ });
+
+ it("amends envelope, deadline, and target on a live goal", () => {
+ const goal = makeActiveGoal("am-5");
+ const r = handleAmendGoal(
+ {
+ goal_id: goal.id,
+ target_value: 250,
+ deadline: "2026-12-31T00:00:00.000Z",
+ spend_envelope_usd: 3000,
+ },
+ ctxFor("am-5"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.target_value).toBe(250);
+ expect(r.data.deadline).toBe("2026-12-31T00:00:00.000Z");
+ expect(r.data.spend_envelope_usd).toBe(3000);
+ expect(r.data.cadence_cron).toBe("0 16 * * *");
+ }
+ });
+});
+
+describe("handleLogGoalAction", () => {
+ it("refuses mutations without an observation window", () => {
+ const goal = makeActiveGoal("la-1");
+ const r = handleLogGoalAction(
+ {
+ goal_id: goal.id,
+ kind: "mutation",
+ description: "raise bids",
+ expected_effect: "clicks up",
+ },
+ ctxFor("la-1"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("review_after_hours");
+ });
+
+ it("logs a mutation with a derived review_after", () => {
+ const goal = makeActiveGoal("la-2");
+ const before = Date.now();
+ const r = handleLogGoalAction(
+ {
+ goal_id: goal.id,
+ kind: "mutation",
+ description: "raise bids",
+ resources_touched: ["campaign:1"],
+ expected_effect: "clicks up",
+ review_after_hours: 48,
+ spend_usd: 20,
+ action_badge: "Bids raised",
+ },
+ ctxFor("la-2"),
+ );
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ const reviewAt = Date.parse(r.data.review_after!);
+ expect(reviewAt).toBeGreaterThanOrEqual(before + 48 * 3_600_000);
+ expect(reviewAt).toBeLessThan(before + 49 * 3_600_000);
+ });
+
+ it("research actions need no window", () => {
+ const goal = makeActiveGoal("la-3");
+ const r = handleLogGoalAction(
+ {
+ goal_id: goal.id,
+ kind: "research",
+ description: "read search terms",
+ expected_effect: "n/a",
+ },
+ ctxFor("la-3"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.review_after).toBeNull();
+ });
+});
+
+describe("handleReviewGoalAction", () => {
+ it("rejects an action from another goal", () => {
+ const goal = makeActiveGoal("rv-1");
+ const other = makeActiveGoal("rv-2");
+ const foreign = createGoalAction({
+ goal_id: other.id,
+ kind: "research",
+ description: "d",
+ expected_effect: "e",
+ });
+ const r = handleReviewGoalAction(
+ { goal_id: goal.id, action_id: foreign.id, observed_outcome: "o" },
+ ctxFor("rv-1"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Unknown action_id");
+ });
+
+ it("reviews once, records the learning, and refuses a second pass", () => {
+ const goal = makeActiveGoal("rv-3");
+ const action = createGoalAction({
+ goal_id: goal.id,
+ kind: "mutation",
+ description: "d",
+ expected_effect: "e",
+ review_after: new Date().toISOString(),
+ });
+ const r = handleReviewGoalAction(
+ {
+ goal_id: goal.id,
+ action_id: action.id,
+ observed_outcome: "worked",
+ learning: "bids move clicks within 2 days",
+ },
+ ctxFor("rv-3"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.status).toBe("reviewed");
+ expect(r.data.learning_id).not.toBeNull();
+ }
+ expect(listGoalLearnings(goal.id)[0]!.body).toContain("bids move clicks");
+
+ const again = handleReviewGoalAction(
+ { goal_id: goal.id, action_id: action.id, observed_outcome: "o" },
+ ctxFor("rv-3"),
+ );
+ expect(again.ok).toBe(false);
+ if (!again.ok) expect(again.error).toContain("not open");
+ });
+
+ it("abandoning records the abandoned status without a learning", () => {
+ const goal = makeActiveGoal("rv-4");
+ const action = createGoalAction({
+ goal_id: goal.id,
+ kind: "mutation",
+ description: "d",
+ expected_effect: "e",
+ review_after: new Date().toISOString(),
+ });
+ const r = handleReviewGoalAction(
+ { goal_id: goal.id, action_id: action.id, observed_outcome: "reverted", abandoned: true },
+ ctxFor("rv-4"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.status).toBe("abandoned");
+ expect(r.data.learning_id).toBeNull();
+ }
+ });
+});
+
+describe("learnings tools", () => {
+ it("logs with supersession and searches by substring", () => {
+ const goal = makeActiveGoal("ln-1");
+ const first = handleLogLearning(
+ { goal_id: goal.id, body: "old belief", confidence: "low" },
+ ctxFor("ln-1"),
+ );
+ expect(first.ok).toBe(true);
+ if (!first.ok) return;
+ const second = handleLogLearning(
+ { goal_id: goal.id, body: "new belief", supersedes_id: first.data.learning_id },
+ ctxFor("ln-1"),
+ );
+ expect(second.ok).toBe(true);
+
+ const all = handleSearchLearnings({ goal_id: goal.id }, ctxFor("ln-1"));
+ expect(all.ok).toBe(true);
+ if (all.ok) {
+ // The superseded learning is filtered out of listings.
+ expect(all.data.learnings.map((l) => l.body)).toEqual(["new belief"]);
+ }
+ const hit = handleSearchLearnings(
+ { goal_id: goal.id, query: "new", limit: 999 },
+ ctxFor("ln-1"),
+ );
+ expect(hit.ok).toBe(true);
+ if (hit.ok) expect(hit.data.learnings).toHaveLength(1);
+ const miss = handleSearchLearnings(
+ { goal_id: goal.id, query: "zzz" },
+ ctxFor("ln-1"),
+ );
+ expect(miss.ok).toBe(true);
+ if (miss.ok) expect(miss.data.learnings).toHaveLength(0);
+ });
+});
+
+describe("handleUpdateGoalStatus", () => {
+ it("never lets a maintain goal self-complete", () => {
+ const goal = makeProposedGoal("st-1");
+ proposeTarget(goal.id, { target_value: 5, mode: "maintain" });
+ const r = handleUpdateGoalStatus(
+ { goal_id: goal.id, status: "achieved", reason: "done" },
+ ctxFor("st-1"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("MAINTAIN");
+ });
+
+ it("refuses 'achieved' while the number says otherwise", () => {
+ const goal = makeActiveGoal("st-2"); // target 100
+ recordMetricSnapshot(goal.id, 50, "tick");
+ const r = handleUpdateGoalStatus(
+ { goal_id: goal.id, status: "achieved", reason: "trust me" },
+ ctxFor("st-2"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("has not met the target");
+ });
+
+ it("closes achieved when the measured metric agrees", () => {
+ const goal = makeActiveGoal("st-3");
+ recordMetricSnapshot(goal.id, 150, "tick");
+ const r = handleUpdateGoalStatus(
+ { goal_id: goal.id, status: "achieved", reason: "target crossed" },
+ ctxFor("st-3"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.status).toBe("achieved");
+ });
+
+ it("pauses without target checks", () => {
+ const goal = makeActiveGoal("st-4");
+ const r = handleUpdateGoalStatus(
+ { goal_id: goal.id, status: "paused", reason: "token expired" },
+ ctxFor("st-4"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.data.status).toBe("paused");
+ expect(getGoal(goal.id)!.next_tick_at).toBeNull();
+ });
+
+ it("terminal statuses are final", () => {
+ const goal = makeActiveGoal("st-5");
+ setGoalStatus(goal.id, "killed", "user closed it");
+ const r = handleUpdateGoalStatus(
+ { goal_id: goal.id, status: "paused", reason: "r" },
+ ctxFor("st-5"),
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("terminal");
+ });
+});
+
+describe("project tools", () => {
+ it("handleGetProject returns the caller's project or an error", () => {
+ const ok = handleGetProject({}, ctxFor("a"));
+ expect(ok.ok).toBe(true);
+ if (ok.ok) expect(ok.data.slug).toBe(SLUG);
+ const bad = handleGetProject({}, { project_slug: "ghost", agent_id: "a" });
+ expect(bad.ok).toBe(false);
+ });
+
+ it("handleSetProjectBrief validates project, content, and size", async () => {
+ const ghost = await handleSetProjectBrief(
+ { content: "x" },
+ { project_slug: "ghost", agent_id: "a" },
+ );
+ expect(ghost.ok).toBe(false);
+
+ const empty = await handleSetProjectBrief({ content: " " }, ctxFor("a"));
+ expect(empty.ok).toBe(false);
+ if (!empty.ok) expect(empty.error).toContain("empty");
+
+ const huge = await handleSetProjectBrief(
+ { content: "x".repeat(PROJECT_BRIEF_MAX_BYTES + 1) },
+ ctxFor("a"),
+ );
+ expect(huge.ok).toBe(false);
+ if (!huge.ok) expect(huge.error).toContain("bytes");
+ });
+
+ it("handleSetProjectBrief writes PROJECT.md and re-syncs every agent", async () => {
+ const r = await handleSetProjectBrief(
+ { content: " Acme sells anvils. " },
+ ctxFor("a"),
+ );
+ expect(r.ok).toBe(true);
+ if (r.ok) {
+ expect(r.data.bytes).toBe(Buffer.byteLength("Acme sells anvils."));
+ expect(r.data.synced_agents).toBe(3);
+ }
+ expect(mocks.syncProjectAgents).toHaveBeenCalledWith(SLUG);
+ await expect(readProjectBrief(SLUG)).resolves.toBe("Acme sells anvils.");
+ });
+});
diff --git a/notfair/src/server/goals/tick.more.test.ts b/notfair/src/server/goals/tick.more.test.ts
new file mode 100644
index 00000000..12e5a7ff
--- /dev/null
+++ b/notfair/src/server/goals/tick.more.test.ts
@@ -0,0 +1,468 @@
+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-tickmore-"));
+});
+
+const mocks = vi.hoisted(() => ({
+ measureGoalMetric: vi.fn(),
+ runMetricSource: vi.fn(),
+ syncGoalPrs: vi.fn(async () => {}),
+ /** Events the fake adapter yields on the next turn. */
+ events: [] as Array<Record<string, unknown>>,
+ /** Messages the adapter received (the composed tick briefs). */
+ seenMessages: [] as string[],
+}));
+
+vi.mock("@/server/goals/metric", () => ({
+ measureGoalMetric: mocks.measureGoalMetric,
+ runMetricSource: mocks.runMetricSource,
+}));
+vi.mock("./pr-sync", () => ({ syncGoalPrs: mocks.syncGoalPrs }));
+vi.mock("@/server/adapters/registry", () => ({
+ requireAdapter: () => ({
+ execute: async function* (input: { message: string }) {
+ mocks.seenMessages.push(input.message);
+ for (const evt of mocks.events) yield evt;
+ },
+ }),
+}));
+
+import {
+ buildTickMessage,
+ describePrForBrief,
+ runDueGoalTicks,
+ runGoalTick,
+ streamAgentTurn,
+ type TickContext,
+} from "./tick";
+import { getDb } from "@/server/db/db";
+import {
+ createGoal,
+ createGoalAction,
+ getGoal,
+ listGoalTicks,
+ proposeTarget,
+ recordMetricSnapshot,
+ setGoalMetric,
+ type Goal,
+ type GoalAction,
+ type GoalTick,
+} from "@/server/db/goals";
+import type { GoalPr as Pr } from "@/server/db/goal-prs";
+import {
+ listSupportMetricSnapshots,
+ upsertSupportMetric,
+} from "@/server/db/goal-support-metrics";
+
+const SLUG = "proj";
+
+function makeActiveGoal(agent: string, target = 100): Goal {
+ const goal = createGoal({ project_slug: SLUG, agent_id: agent, statement: "grow" });
+ setGoalMetric(goal.id, {
+ metric_name: "clicks",
+ metric_source_key: "local",
+ metric_source_tool: "shell",
+ metric_source_args_json: "{}",
+ metric_direction: "increase",
+ baseline_value: 10,
+ });
+ return proposeTarget(goal.id, { target_value: target })!;
+}
+
+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());
+});
+
+beforeEach(() => {
+ mocks.measureGoalMetric.mockReset();
+ mocks.runMetricSource.mockReset();
+ mocks.events = [{ kind: "final", text: "did one thing" }];
+ mocks.seenMessages = [];
+});
+
+describe("runGoalTick guards", () => {
+ it("does nothing for a goal that is not active", async () => {
+ const goal = createGoal({ project_slug: SLUG, agent_id: "g-intake", statement: "s" });
+ await runGoalTick(goal, "manual");
+ expect(listGoalTicks(goal.id, 10)).toHaveLength(0);
+ expect(mocks.measureGoalMetric).not.toHaveBeenCalled();
+ });
+
+ it("accepts a goal id string and ignores unknown ids", async () => {
+ await expect(runGoalTick("no-such-goal", "manual")).resolves.toBeUndefined();
+ });
+
+ it("skips a second tick while one is already running for the goal", async () => {
+ const goal = makeActiveGoal("g-reent");
+ let finish!: (v: unknown) => void;
+ mocks.measureGoalMetric.mockReturnValueOnce(new Promise((r) => (finish = r)));
+ const first = runGoalTick(goal, "manual");
+ const second = runGoalTick(goal, "manual"); // overlaps: must no-op
+ await second;
+ finish({ ok: true, value: 1 });
+ await first;
+ expect(listGoalTicks(goal.id, 10)).toHaveLength(1);
+ });
+});
+
+describe("observe-only heartbeats", () => {
+ it("records the check + chart point without waking the agent", async () => {
+ const goal = makeActiveGoal("g-noop");
+ recordMetricSnapshot(goal.id, 20, "tick"); // mid-flight, target not met
+ createGoalAction({
+ goal_id: goal.id,
+ kind: "mutation",
+ description: "in-window change",
+ expected_effect: "e",
+ review_after: new Date(Date.now() + 48 * 3600_000).toISOString(),
+ });
+ mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 21 });
+
+ await runGoalTick(getGoal(goal.id)!, "heartbeat");
+
+ const tick = listGoalTicks(goal.id, 10)[0]!;
+ expect(tick.status).toBe("done");
+ expect(tick.summary).toContain("No-op check");
+ expect(tick.metric_value).toBe(21);
+ expect(tick.session_id).toBeNull(); // no agent turn, no session
+ expect(mocks.seenMessages).toHaveLength(0);
+ expect(getGoal(goal.id)!.current_value).toBe(21); // snapshot still landed
+ });
+});
+
+describe("agent-turn ticks", () => {
+ it("measures supporting metrics, snapshots the good ones, and briefs both", async () => {
+ const goal = makeActiveGoal("g-support");
+ const good = upsertSupportMetric({
+ goal_id: goal.id,
+ name: "impressions",
+ source_key: "local",
+ source_tool: "shell",
+ source_args_json: "{}",
+ direction: "increase",
+ measured_value: 5,
+ });
+ upsertSupportMetric({
+ goal_id: goal.id,
+ name: "ctr",
+ source_key: "local",
+ source_tool: "shell",
+ source_args_json: "{}",
+ direction: null,
+ measured_value: 1,
+ });
+ mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 30 });
+ mocks.runMetricSource
+ .mockResolvedValueOnce({ ok: true, value: 9 })
+ .mockResolvedValueOnce({ ok: false, error: "column gone" });
+
+ await runGoalTick(getGoal(goal.id)!, "manual");
+
+ expect(listSupportMetricSnapshots(good.id).some((s) => s.value === 9)).toBe(true);
+ const brief = mocks.seenMessages[0]!;
+ expect(brief).toContain("[supporting] impressions: **9**");
+ expect(brief).toContain("healthy = increase");
+ expect(brief).toContain("[supporting] ctr: MEASUREMENT FAILED: column gone");
+ });
+
+ it("briefs a failed primary measurement and stores the error on the check", async () => {
+ const goal = makeActiveGoal("g-mfail");
+ mocks.measureGoalMetric.mockResolvedValueOnce({ ok: false, error: "token expired" });
+
+ await runGoalTick(getGoal(goal.id)!, "manual");
+
+ const tick = listGoalTicks(goal.id, 10)[0]!;
+ expect(tick.metric_value).toBeNull();
+ expect(tick.metric_error).toBe("token expired");
+ expect(mocks.seenMessages[0]!).toContain("MEASUREMENT FAILED: token expired");
+ });
+
+ it("leads with extraContext (approval wake-ups)", async () => {
+ const goal = makeActiveGoal("g-extra");
+ mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 1 });
+ await runGoalTick(getGoal(goal.id)!, "heartbeat", {
+ extraContext: "The user merged your PR.",
+ });
+ expect(mocks.seenMessages[0]!).toContain("The user merged your PR.");
+ });
+});
+
+describe("runDueGoalTicks", () => {
+ it("ticks exactly the goals whose heartbeat is due", async () => {
+ const due = makeActiveGoal("g-due");
+ getDb()
+ .prepare("UPDATE goals SET next_tick_at = ? WHERE id = ?")
+ .run(new Date(Date.now() - 1000).toISOString(), due.id);
+ const notDue = makeActiveGoal("g-notdue"); // next_tick_at in the future
+ mocks.measureGoalMetric.mockResolvedValue({ ok: true, value: 1 });
+
+ await runDueGoalTicks();
+
+ expect(listGoalTicks(due.id, 10)).toHaveLength(1);
+ expect(listGoalTicks(due.id, 10)[0]!.trigger_kind).toBe("heartbeat");
+ expect(listGoalTicks(notDue.id, 10)).toHaveLength(0);
+ // The heartbeat advanced past the stale timestamp.
+ expect(getGoal(due.id)!.next_tick_at! > new Date().toISOString()).toBe(true);
+ });
+});
+
+describe("streamAgentTurn", () => {
+ const turnInput = (agent: string) => ({
+ projectSlug: SLUG,
+ harnessAdapter: "claude-code-local" as const,
+ agentId: agent,
+ sessionLabel: "main",
+ message: "hello",
+ source: "test",
+ });
+
+ it("persists the handshake and returns the final text as summary", async () => {
+ mocks.events = [
+ { kind: "session", harnessSessionId: "h-123" },
+ { kind: "delta", text: "thinking…" },
+ { kind: "final", text: " all done " },
+ ];
+ const onSession = vi.fn();
+ const r = await streamAgentTurn({ ...turnInput("sa-1"), onSession });
+ expect(r.summary).toBe("all done");
+ expect(onSession).toHaveBeenCalledWith(r.sessionId);
+ const row = getDb()
+ .prepare("SELECT harness_session_id FROM sessions WHERE id = ?")
+ .get(r.sessionId) as { harness_session_id: string };
+ expect(row.harness_session_id).toBe("h-123");
+ });
+
+ it("falls back to the accumulated deltas when no final arrives", async () => {
+ mocks.events = [
+ { kind: "delta", text: "part one " },
+ { kind: "delta", text: "part two" },
+ ];
+ const r = await streamAgentTurn(turnInput("sa-2"));
+ expect(r.summary).toBe("part one part two");
+ });
+
+ it("returns a null summary for an empty turn", async () => {
+ mocks.events = [];
+ const r = await streamAgentTurn(turnInput("sa-3"));
+ expect(r.summary).toBeNull();
+ });
+
+ it("truncates an oversized final to the summary cap", async () => {
+ mocks.events = [{ kind: "final", text: "x".repeat(5000) }];
+ const r = await streamAgentTurn(turnInput("sa-4"));
+ expect(r.summary!.length).toBe(4001); // 4000 chars + ellipsis
+ expect(r.summary!.endsWith("…")).toBe(true);
+ });
+
+ it("throws the last non-transient error when the turn dies without a final", async () => {
+ mocks.events = [
+ { kind: "error", message: "harness crashed", transient: false },
+ { kind: "error", message: "retrying…", transient: true },
+ ];
+ await expect(streamAgentTurn(turnInput("sa-5"))).rejects.toThrow("harness crashed");
+ });
+
+ it("falls back to the last error when all were transient", async () => {
+ mocks.events = [
+ { kind: "error", message: "first blip", transient: true },
+ { kind: "error", message: "second blip", transient: true },
+ ];
+ await expect(streamAgentTurn(turnInput("sa-6"))).rejects.toThrow("second blip");
+ });
+});
+
+// ── pure brief composition ───────────────────────────────────────────────
+
+function pr(over: Partial<Pr>): Pr {
+ return {
+ id: "pr-1",
+ goal_id: "g",
+ action_id: null,
+ tick_number: null,
+ url: "https://github.com/acme/site/pull/7",
+ title: "Fix pricing meta",
+ branch: null,
+ state: "open",
+ review_decision: null,
+ comment_count: 0,
+ is_draft: false,
+ merged_at: null,
+ last_synced_at: null,
+ sync_error: null,
+ next_sync_at: null,
+ last_activity_at: null,
+ created_at: "",
+ updated_at: "",
+ ...over,
+ };
+}
+
+describe("describePrForBrief", () => {
+ it("covers the open-state variants", () => {
+ expect(describePrForBrief(pr({ is_draft: true }))).toContain("(draft)");
+ expect(describePrForBrief(pr({ review_decision: "CHANGES_REQUESTED" }))).toContain(
+ "CHANGES REQUESTED by the user",
+ );
+ expect(describePrForBrief(pr({ review_decision: "APPROVED" }))).toContain(
+ "approved, awaiting merge",
+ );
+ expect(describePrForBrief(pr({}))).toContain("awaiting the user's review");
+ expect(describePrForBrief(pr({ comment_count: 2 }))).toContain(
+ "2 comment(s)/review(s)",
+ );
+ });
+
+ it("covers merged, closed, sync errors, and action links", () => {
+ expect(
+ describePrForBrief(pr({ state: "merged", merged_at: "2026-07-13T00:00:00Z" })),
+ ).toContain("merged 2026-07-13T00:00:00Z");
+ expect(describePrForBrief(pr({ state: "closed" }))).toContain(
+ "closed WITHOUT merge",
+ );
+ expect(describePrForBrief(pr({ sync_error: "gh: not found" }))).toContain(
+ "(last sync failed: gh: not found)",
+ );
+ expect(describePrForBrief(pr({ action_id: "act-9" }))).toContain(
+ "linked action act-9",
+ );
+ });
+});
+
+const baseCtx: TickContext = {
+ goal: {
+ metric_name: "clicks",
+ baseline_value: 10,
+ target_value: 100,
+ metric_direction: "increase",
+ mode: "achieve",
+ deadline: null,
+ spend_envelope_usd: null,
+ } as unknown as Goal,
+ tickNumber: 3,
+ nowIso: "2026-07-21T00:00:00.000Z",
+ measurement: { ok: true, value: 30 },
+ supportReadings: [],
+ targetMet: false,
+ pastDeadline: false,
+ actionsDueForReview: [],
+ gatedActions: [],
+ gatedByOthers: [],
+ userActionRequests: [],
+ loggedSpendUsd: 0,
+ recentLearnings: [],
+ lastTick: null,
+ pullRequests: [],
+};
+
+describe("buildTickMessage sections", () => {
+ it("renders deadline countdown, spend envelope, and the gate lists", () => {
+ const gated = {
+ id: "act-g",
+ description: "raised bids",
+ resources_touched_json: JSON.stringify(["campaign:1"]),
+ review_after: "2026-07-25T00:00:00.000Z",
+ } as GoalAction;
+ const due = {
+ id: "act-d",
+ description: "paused waste",
+ expected_effect: "spend down",
+ review_after: "2026-07-20T00:00:00.000Z",
+ } as GoalAction;
+ const msg = buildTickMessage({
+ ...baseCtx,
+ goal: {
+ ...baseCtx.goal,
+ deadline: "2026-07-23T00:00:00.000Z",
+ spend_envelope_usd: 500,
+ } as Goal,
+ loggedSpendUsd: 120,
+ actionsDueForReview: [due],
+ gatedActions: [gated],
+ gatedByOthers: [
+ {
+ ...gated,
+ id: "act-o",
+ description: "their test",
+ resources_touched_json: "[]",
+ agent_id: "proj-goal-2",
+ } as GoalAction & { agent_id: string },
+ ],
+ });
+ expect(msg).toContain("(2 days left)");
+ expect(msg).toContain("$120 logged of $500 envelope");
+ expect(msg).toContain("[act-d] paused waste — expected: spend down");
+ expect(msg).toContain("[act-g] raised bids — resources: campaign:1");
+ expect(msg).toContain("## Gated by OTHER agents");
+ expect(msg).toContain("(proj-goal-2) their test — resources: (unspecified)");
+ });
+
+ it("flags a met stop condition and a passed deadline", () => {
+ const msg = buildTickMessage({
+ ...baseCtx,
+ goal: { ...baseCtx.goal, deadline: "2026-07-20T00:00:00.000Z" } as Goal,
+ targetMet: true,
+ pastDeadline: true,
+ });
+ expect(msg).toContain("- target_met: true");
+ expect(msg).toContain("(PASSED)");
+ expect(msg).toContain("A stop condition looks met.");
+ // No envelope set → new spend is out of bounds by default.
+ expect(msg).toContain("spend envelope: none set");
+ });
+
+ it("frames maintain goals as holding, not finished", () => {
+ const msg = buildTickMessage({
+ ...baseCtx,
+ goal: { ...baseCtx.goal, mode: "maintain" } as Goal,
+ targetMet: true,
+ });
+ expect(msg).toContain("holding_at_target: true");
+ expect(msg).toContain("NOT a reason to close");
+ expect(msg).not.toContain("A stop condition looks met.");
+ });
+
+ it("renders PRs, learnings, and the last tick", () => {
+ const msg = buildTickMessage({
+ ...baseCtx,
+ pullRequests: [pr({ title: "Fix pricing meta" })],
+ recentLearnings: [
+ { confidence: "high", body: "Tuesday spikes are noise" } as never,
+ ],
+ lastTick: {
+ tick_number: 2,
+ status: "done",
+ summary: "reviewed one action",
+ } as GoalTick,
+ });
+ expect(msg).toContain("## Your pull requests");
+ expect(msg).toContain("Fix pricing meta");
+ expect(msg).toContain("the user merges, never you");
+ expect(msg).toContain("- (high) Tuesday spikes are noise");
+ expect(msg).toContain("#2 (done): reviewed one action");
+ });
+
+ it("renders a summary-less last tick and the measurement-failure guidance", () => {
+ const msg = buildTickMessage({
+ ...baseCtx,
+ measurement: { ok: false, error: "boom" },
+ lastTick: { tick_number: 1, status: "failed", summary: null } as GoalTick,
+ });
+ expect(msg).toContain("- MEASUREMENT FAILED: boom");
+ expect(msg).toContain("Diagnose before anything else.");
+ expect(msg).toContain("- target_met: false");
+ expect(msg).toContain("#1 (failed): (no summary)");
+ expect(msg).toContain("- deadline: none");
+ });
+});
diff --git a/notfair/src/server/harness-usage.more.test.ts b/notfair/src/server/harness-usage.more.test.ts
new file mode 100644
index 00000000..284d163f
--- /dev/null
+++ b/notfair/src/server/harness-usage.more.test.ts
@@ -0,0 +1,394 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { EventEmitter } from "node:events";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+// harness-usage reads real HOME paths (~/.codex, ~/.claude) and spawns the
+// codex CLI. Point homedir at a tmpdir and fake the spawn + fetch surfaces —
+// no real binaries, no network, never the developer's actual home.
+const h = 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");
+ const home = mkdtempSync(join(tmpdir(), "notfair-usage-home-"));
+ return {
+ home,
+ state: {
+ loginOutput: "Logged in using ChatGPT\n",
+ loginStderr: "",
+ spawnMode: "close" as "close" | "error" | "hang",
+ killThrows: false,
+ spawns: [] as Array<{ cmd: string; args: string[] }>,
+ },
+ };
+});
+
+vi.mock("node:os", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:os")>();
+ return { ...actual, default: { ...actual, homedir: () => h.home }, homedir: () => h.home };
+});
+vi.mock("node:child_process", () => ({
+ spawn: (cmd: string, args: string[]) => {
+ h.state.spawns.push({ cmd, args });
+ const child = new EventEmitter() as EventEmitter & {
+ stdout: EventEmitter;
+ stderr: EventEmitter;
+ kill: (sig?: string) => void;
+ };
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = () => {
+ if (h.state.killThrows) throw new Error("already exited");
+ };
+ if (h.state.spawnMode === "close") {
+ queueMicrotask(() => {
+ if (h.state.loginOutput) {
+ child.stdout.emit("data", Buffer.from(h.state.loginOutput));
+ }
+ if (h.state.loginStderr) {
+ child.stderr.emit("data", Buffer.from(h.state.loginStderr));
+ }
+ child.emit("close", 0);
+ });
+ } else if (h.state.spawnMode === "error") {
+ queueMicrotask(() => child.emit("error", new Error("spawn ENOENT")));
+ }
+ // "hang": emit nothing — the 3s guard timer must resolve it.
+ return child;
+ },
+}));
+
+import {
+ normalizeCodexRateLimits,
+ parseCodexLoginStatus,
+ readHarnessUsage,
+ refreshHarnessUsage,
+} from "@/server/harness-usage";
+
+const codexDir = join(h.home, ".codex");
+const claudeDir = join(h.home, ".claude");
+const authPath = join(codexDir, "auth.json");
+const statsPath = join(claudeDir, "stats-cache.json");
+const today = () => new Date().toISOString().slice(0, 10);
+
+function writeAuth(auth: unknown): void {
+ mkdirSync(codexDir, { recursive: true });
+ writeFileSync(authPath, JSON.stringify(auth), "utf8");
+}
+
+function writeStats(stats: unknown): void {
+ mkdirSync(claudeDir, { recursive: true });
+ writeFileSync(
+ statsPath,
+ typeof stats === "string" ? stats : JSON.stringify(stats),
+ "utf8",
+ );
+}
+
+/** Base64url-encode JWT claims into a decodable fake id_token. */
+function fakeIdToken(claims: Record<string, unknown>): string {
+ const body = Buffer.from(JSON.stringify(claims)).toString("base64url");
+ return `hdr.${body}.sig`;
+}
+
+beforeEach(() => {
+ rmSync(codexDir, { recursive: true, force: true });
+ rmSync(claudeDir, { recursive: true, force: true });
+ h.state.loginOutput = "Logged in using ChatGPT\n";
+ h.state.loginStderr = "";
+ h.state.spawnMode = "close";
+ h.state.killThrows = false;
+ h.state.spawns = [];
+ vi.unstubAllGlobals();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("claude-code-local usage", () => {
+ it("reports zeros + stale when stats-cache.json doesn't exist", async () => {
+ await expect(refreshHarnessUsage("claude-code-local")).resolves.toEqual({
+ kind: "claude-code",
+ messagesToday: 0,
+ sessionsToday: 0,
+ tokensToday: 0,
+ stale: true,
+ lastComputedDate: null,
+ });
+ });
+
+ it("rolls up today's messages, sessions, and tokens across models", async () => {
+ writeStats({
+ dailyActivity: [
+ { date: "2020-01-01", messageCount: 999, sessionCount: 99 },
+ { date: today(), messageCount: 12, sessionCount: 3 },
+ ],
+ dailyModelTokens: [
+ {
+ date: today(),
+ tokensByModel: { "claude-fable-5": 1000, "claude-haiku": 250, bogus: "x" },
+ },
+ ],
+ lastComputedDate: today(),
+ });
+ await expect(refreshHarnessUsage("claude-code-local")).resolves.toEqual({
+ kind: "claude-code",
+ messagesToday: 12,
+ sessionsToday: 3,
+ tokensToday: 1250,
+ stale: false,
+ lastComputedDate: today(),
+ });
+ });
+
+ it("flags a snapshot last computed on an earlier day as stale", async () => {
+ writeStats({
+ dailyActivity: [],
+ lastComputedDate: "2020-01-01",
+ });
+ await expect(refreshHarnessUsage("claude-code-local")).resolves.toMatchObject({
+ stale: true,
+ lastComputedDate: "2020-01-01",
+ messagesToday: 0,
+ tokensToday: 0,
+ });
+ });
+
+ it("collapses malformed JSON to the unknown shape", async () => {
+ writeStats("{not json");
+ await expect(refreshHarnessUsage("claude-code-local")).resolves.toEqual({
+ kind: "unknown",
+ });
+ });
+
+ it("serves from the 60s cache until refreshed", async () => {
+ writeStats({ dailyActivity: [], lastComputedDate: today() });
+ const first = await refreshHarnessUsage("claude-code-local");
+ // Mutate the file — a cached read must not see it.
+ writeStats({
+ dailyActivity: [{ date: today(), messageCount: 5, sessionCount: 1 }],
+ lastComputedDate: today(),
+ });
+ await expect(readHarnessUsage("claude-code-local")).resolves.toBe(first);
+ // refresh drops the cache entry.
+ await expect(refreshHarnessUsage("claude-code-local")).resolves.toMatchObject({
+ messagesToday: 5,
+ });
+ });
+});
+
+describe("codex-local usage", () => {
+ it("reports login status with no rate limits when auth.json is missing", async () => {
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({
+ kind: "codex",
+ auth: "chatgpt",
+ plan: null,
+ email: null,
+ rateLimits: [],
+ });
+ expect(h.state.spawns[0]!.args).toEqual(["login", "status"]);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("infers auth from auth.json when the CLI's answer is unrecognized", async () => {
+ h.state.loginOutput = "codex 0.99 — usage: codex [options]\n";
+ writeAuth({ auth_mode: "apikey", tokens: { access_token: "tok" } });
+ const fetchSpy = vi.fn(async () => ({ ok: false }));
+ vi.stubGlobal("fetch", fetchSpy);
+ await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({
+ kind: "codex",
+ auth: "api-key",
+ });
+ });
+
+ it("stops at auth status when there's no access token", async () => {
+ h.state.loginOutput = "Not logged in\n";
+ writeAuth({ tokens: {} });
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({
+ kind: "codex",
+ auth: "signed-out",
+ plan: null,
+ email: null,
+ rateLimits: [],
+ });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("combines JWT identity with live wham/usage windows", async () => {
+ writeAuth({
+ tokens: {
+ access_token: "tok-123",
+ account_id: "acct-9",
+ id_token: fakeIdToken({
+ email: "[email protected]",
+ "https://api.openai.com/auth": {
+ chatgpt_account_id: "acct-from-jwt",
+ chatgpt_plan_type: "plus",
+ },
+ }),
+ },
+ });
+ const fetchSpy = vi.fn(async (url: string, init: { headers: Record<string, string> }) => {
+ expect(url).toBe("https://chatgpt.com/backend-api/wham/usage");
+ expect(init.headers.Authorization).toBe("Bearer tok-123");
+ // Explicit account_id wins over the JWT-derived one.
+ expect(init.headers["ChatGPT-Account-Id"]).toBe("acct-9");
+ return {
+ ok: true,
+ json: async () => ({
+ plan_type: "pro",
+ rate_limit: {
+ primary_window: {
+ used_percent: 12,
+ limit_window_seconds: 604_800,
+ reset_at: 1_800_000_000,
+ },
+ secondary_window: {
+ used_percent: 44,
+ limit_window_seconds: 18_000,
+ reset_at: 1_790_000_000,
+ },
+ },
+ }),
+ };
+ });
+ vi.stubGlobal("fetch", fetchSpy);
+
+ await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({
+ kind: "codex",
+ auth: "chatgpt",
+ plan: "pro",
+ email: "[email protected]",
+ rateLimits: [
+ {
+ label: "5-hour",
+ used_percent: 44,
+ limit_window_seconds: 18_000,
+ reset_at: 1_790_000_000,
+ },
+ {
+ label: "Weekly",
+ used_percent: 12,
+ limit_window_seconds: 604_800,
+ reset_at: 1_800_000_000,
+ },
+ ],
+ });
+ });
+
+ it("keeps the JWT plan when the usage endpoint is unreachable", async () => {
+ writeAuth({
+ tokens: {
+ access_token: "tok-123",
+ id_token: fakeIdToken({
+ email: "[email protected]",
+ "https://api.openai.com/auth": {
+ chatgpt_account_id: "acct-from-jwt",
+ chatgpt_plan_type: "plus",
+ },
+ }),
+ },
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new Error("network down");
+ }),
+ );
+ await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({
+ kind: "codex",
+ auth: "chatgpt",
+ plan: "plus",
+ email: "[email protected]",
+ rateLimits: [],
+ });
+ });
+
+ it("tolerates a malformed id_token", async () => {
+ writeAuth({ tokens: { access_token: "tok", id_token: "only-one-part" } });
+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false })));
+ await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({
+ email: null,
+ plan: null,
+ });
+ });
+
+ it("reads stderr and error events from the login-status child", async () => {
+ h.state.loginOutput = "";
+ h.state.loginStderr = "Logged in using agent identity\n";
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({
+ auth: "agent-identity",
+ });
+
+ h.state.spawnMode = "error";
+ await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({
+ auth: "unknown",
+ });
+ });
+
+ it("times out a wedged codex CLI instead of hanging the sidebar", async () => {
+ vi.useFakeTimers();
+ h.state.spawnMode = "hang";
+ h.state.killThrows = true; // kill() on an exited child must be swallowed
+ const pending = refreshHarnessUsage("codex-local");
+ await vi.advanceTimersByTimeAsync(3_000);
+ await expect(pending).resolves.toMatchObject({ kind: "codex", auth: "unknown" });
+ });
+
+ it("returns unknown for an unrecognized adapter id", async () => {
+ await expect(
+ refreshHarnessUsage("bogus-adapter" as never),
+ ).resolves.toEqual({ kind: "unknown" });
+ });
+});
+
+describe("normalizeCodexRateLimits labels", () => {
+ const window = (limit_window_seconds: number) => ({
+ used_percent: 1,
+ limit_window_seconds,
+ reset_at: 1,
+ });
+
+ it("labels known and derived window durations", () => {
+ expect(
+ normalizeCodexRateLimits({ primary_window: window(86_400) })[0]!.label,
+ ).toBe("Daily");
+ expect(
+ normalizeCodexRateLimits({ primary_window: window(172_800) })[0]!.label,
+ ).toBe("2-day");
+ expect(
+ normalizeCodexRateLimits({ primary_window: window(7_200) })[0]!.label,
+ ).toBe("2-hour");
+ expect(
+ normalizeCodexRateLimits({ primary_window: window(1_234) })[0]!.label,
+ ).toBe("Usage");
+ });
+
+ it("filters malformed windows and handles a missing rate_limit block", () => {
+ expect(normalizeCodexRateLimits(undefined)).toEqual([]);
+ expect(normalizeCodexRateLimits(null)).toEqual([]);
+ expect(
+ normalizeCodexRateLimits({
+ primary_window: { used_percent: 5 } as never,
+ secondary_window: window(18_000),
+ }),
+ ).toEqual([{ ...window(18_000), label: "5-hour" }]);
+ });
+});
+
+describe("parseCodexLoginStatus", () => {
+ it("recognizes agent identity and falls back to unknown", () => {
+ expect(parseCodexLoginStatus("Logged in using agent identity\n")).toBe(
+ "agent-identity",
+ );
+ expect(parseCodexLoginStatus("something else entirely")).toBe("unknown");
+ });
+});
diff --git a/notfair/src/server/mcp-catalog.test.ts b/notfair/src/server/mcp-catalog.test.ts
new file mode 100644
index 00000000..aff25697
--- /dev/null
+++ b/notfair/src/server/mcp-catalog.test.ts
@@ -0,0 +1,107 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ MCP_CATALOG_PRESETS,
+ getMcpCatalog,
+ getMcpPresets,
+ isPresetKey,
+ mcpSpecByKey,
+} from "./mcp-catalog";
+import { listUserMcpServers } from "@/server/db/user-mcp-servers";
+import { getHiddenMcpPresetKeys } from "@/server/db/projects";
+import type { UserMcpServer } from "@/server/db/user-mcp-servers";
+
+vi.mock("@/server/db/user-mcp-servers", () => ({
+ listUserMcpServers: vi.fn(),
+}));
+vi.mock("@/server/db/projects", () => ({
+ getHiddenMcpPresetKeys: vi.fn(),
+}));
+
+const listUserMcpServersMock = vi.mocked(listUserMcpServers);
+const getHiddenMcpPresetKeysMock = vi.mocked(getHiddenMcpPresetKeys);
+
+function userRow(overrides: Partial<UserMcpServer> = {}): UserMcpServer {
+ return {
+ project_slug: "proj",
+ key: "custom-server",
+ display_name: "Custom",
+ description: "A user-added server",
+ resource_url: "https://mcp.custom.dev/v1",
+ discovery_url: "https://mcp.custom.dev/.well-known/oauth-protected-resource/v1",
+ created_at: "2026-01-01T00:00:00.000Z",
+ ...overrides,
+ } as UserMcpServer;
+}
+
+beforeEach(() => {
+ listUserMcpServersMock.mockReset().mockReturnValue([]);
+ getHiddenMcpPresetKeysMock.mockReset().mockReturnValue([]);
+});
+
+describe("isPresetKey / getMcpPresets", () => {
+ it("recognizes every shipped preset key", () => {
+ for (const preset of MCP_CATALOG_PRESETS) {
+ expect(isPresetKey(preset.key)).toBe(true);
+ }
+ expect(isPresetKey("custom-server")).toBe(false);
+ });
+
+ it("getMcpPresets returns the static preset list", () => {
+ expect(getMcpPresets()).toBe(MCP_CATALOG_PRESETS);
+ expect(getMcpPresets().every((p) => p.source === "preset")).toBe(true);
+ });
+});
+
+describe("getMcpCatalog", () => {
+ it("returns presets first, then user rows tagged source:'user'", () => {
+ listUserMcpServersMock.mockReturnValue([userRow()]);
+ const catalog = getMcpCatalog("proj");
+ expect(catalog.slice(0, MCP_CATALOG_PRESETS.length)).toEqual(MCP_CATALOG_PRESETS);
+ expect(catalog.at(-1)).toEqual({
+ key: "custom-server",
+ display_name: "Custom",
+ description: "A user-added server",
+ resource_url: "https://mcp.custom.dev/v1",
+ discovery_url: "https://mcp.custom.dev/.well-known/oauth-protected-resource/v1",
+ source: "user",
+ });
+ expect(listUserMcpServersMock).toHaveBeenCalledWith("proj");
+ expect(getHiddenMcpPresetKeysMock).toHaveBeenCalledWith("proj");
+ });
+
+ it("a preset key shadows a colliding user row", () => {
+ listUserMcpServersMock.mockReturnValue([
+ userRow({ key: "notfair-googleads", display_name: "Impostor" }),
+ ]);
+ const catalog = getMcpCatalog("proj");
+ const ads = catalog.filter((m) => m.key === "notfair-googleads");
+ expect(ads).toHaveLength(1);
+ expect(ads[0]!.source).toBe("preset");
+ expect(ads[0]!.display_name).toBe("NotFair Google Ads");
+ });
+
+ it("hidden presets are removed — and no longer shadow user rows", () => {
+ getHiddenMcpPresetKeysMock.mockReturnValue(["notfair-xads"]);
+ listUserMcpServersMock.mockReturnValue([
+ userRow({ key: "notfair-xads", display_name: "My own X server" }),
+ ]);
+ const catalog = getMcpCatalog("proj");
+ const xads = catalog.filter((m) => m.key === "notfair-xads");
+ expect(xads).toHaveLength(1);
+ expect(xads[0]!.source).toBe("user");
+ expect(xads[0]!.display_name).toBe("My own X server");
+ });
+});
+
+describe("mcpSpecByKey", () => {
+ it("finds presets and user rows", () => {
+ listUserMcpServersMock.mockReturnValue([userRow()]);
+ expect(mcpSpecByKey("proj", "notfair-metaads")?.display_name).toBe("NotFair Meta Ads");
+ expect(mcpSpecByKey("proj", "custom-server")?.source).toBe("user");
+ });
+
+ it("returns undefined for unknown keys", () => {
+ expect(mcpSpecByKey("proj", "nope")).toBeUndefined();
+ });
+});
diff --git a/notfair/src/server/mcp-server/browser-tools.test.ts b/notfair/src/server/mcp-server/browser-tools.test.ts
new file mode 100644
index 00000000..e5bd5f9b
--- /dev/null
+++ b/notfair/src/server/mcp-server/browser-tools.test.ts
@@ -0,0 +1,332 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const actions = vi.hoisted(() => ({
+ back: vi.fn(),
+ click: vi.fn(),
+ navigate: vi.fn(),
+ press: vi.fn(),
+ scroll: vi.fn(),
+ snapshot: vi.fn(),
+ type: vi.fn(),
+}));
+const session = vi.hoisted(() => ({
+ getOrLaunchBrowser: vi.fn(),
+ getSessionStatus: vi.fn(),
+}));
+const tabs = vi.hoisted(() => ({
+ closeTab: vi.fn(),
+ getTab: vi.fn(),
+ listTabs: vi.fn(),
+ openTab: vi.fn(),
+}));
+
+vi.mock("@/server/browser/actions", () => actions);
+vi.mock("@/server/browser/session", () => session);
+vi.mock("@/server/browser/tabs", () => tabs);
+
+import { BROWSER_TOOLS } from "./browser-tools";
+import type { ToolResult } from "./tools";
+
+const PAGE = { fake: "page" };
+const BASE = { project_slug: "proj", target_id: "agent-1" };
+
+async function call(name: string, input: unknown): Promise<ToolResult> {
+ const tool = BROWSER_TOOLS.find((t) => t.name === name);
+ if (!tool) throw new Error(`no tool ${name}`);
+ return tool.handler(input, {});
+}
+
+function text(result: ToolResult): string {
+ if (!result.ok) throw new Error(`expected ok result, got: ${result.error}`);
+ return result.content.map((c) => c.text).join("\n");
+}
+
+function errorOf(result: ToolResult): string {
+ if (result.ok) throw new Error("expected error result");
+ return result.error;
+}
+
+beforeEach(() => {
+ for (const group of [actions, session, tabs]) {
+ for (const fn of Object.values(group)) fn.mockReset();
+ }
+ tabs.getTab.mockResolvedValue(PAGE);
+});
+
+describe("registry", () => {
+ it("exposes the full browser surface and no shutdown primitive", () => {
+ expect(BROWSER_TOOLS.map((t) => t.name)).toEqual([
+ "browser_status",
+ "browser_tabs",
+ "browser_open",
+ "browser_close",
+ "browser_navigate",
+ "browser_snapshot",
+ "browser_click",
+ "browser_type",
+ "browser_press",
+ "browser_scroll",
+ "browser_back",
+ ]);
+ expect(BROWSER_TOOLS.some((t) => t.name.includes("shutdown"))).toBe(false);
+ });
+
+ it("every tool rejects malformed args", async () => {
+ for (const tool of BROWSER_TOOLS) {
+ const r = await tool.handler({}, {});
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toMatch(/^Invalid arguments:/);
+ }
+ });
+});
+
+describe("browser_status", () => {
+ it("reports a running session", async () => {
+ session.getSessionStatus.mockReturnValue({
+ projectSlug: "proj",
+ running: true,
+ cdpPort: 19042,
+ userDataDir: "/tmp/x/user-data",
+ uptimeMs: 1234,
+ idleTimeoutMs: 300_000,
+ });
+ const r = await call("browser_status", { project_slug: "proj" });
+ const parsed = JSON.parse(text(r));
+ expect(parsed).toMatchObject({ running: true, cdpPort: 19042, uptimeMs: 1234 });
+ expect(parsed.note).toContain("is running");
+ expect(session.getSessionStatus).toHaveBeenCalledWith("proj");
+ });
+
+ it("reports a stopped session with launch guidance", async () => {
+ session.getSessionStatus.mockReturnValue({
+ projectSlug: "proj",
+ running: false,
+ cdpPort: 19042,
+ userDataDir: "/tmp/x/user-data",
+ idleTimeoutMs: 300_000,
+ });
+ const r = await call("browser_status", { project_slug: "proj" });
+ expect(JSON.parse(text(r)).note).toContain("not running");
+ });
+});
+
+describe("browser_tabs", () => {
+ it("lists tabs as JSON", async () => {
+ tabs.listTabs.mockResolvedValue([{ id: "agent-1", label: "agent-1", url: "https://x", title: "X" }]);
+ const r = await call("browser_tabs", { project_slug: "proj" });
+ expect(JSON.parse(text(r))).toEqual([
+ { id: "agent-1", label: "agent-1", url: "https://x", title: "X" },
+ ]);
+ });
+
+ it("wraps listing failures", async () => {
+ tabs.listTabs.mockRejectedValue(new Error("chrome died"));
+ const r = await call("browser_tabs", { project_slug: "proj" });
+ expect(errorOf(r)).toBe("browser_tabs failed: chrome died");
+ });
+});
+
+describe("browser_open", () => {
+ it("launches the session then opens the labeled tab", async () => {
+ session.getOrLaunchBrowser.mockResolvedValue({});
+ tabs.openTab.mockResolvedValue({ id: "agent-1", label: "agent-1", url: "https://x", title: "" });
+ const r = await call("browser_open", {
+ project_slug: "proj",
+ url: "https://x",
+ label: "agent-1",
+ });
+ expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("proj");
+ expect(tabs.openTab).toHaveBeenCalledWith("proj", { label: "agent-1", url: "https://x" });
+ expect(JSON.parse(text(r)).id).toBe("agent-1");
+ });
+
+ it("rejects a non-URL url and a malformed label", async () => {
+ expect((await call("browser_open", { project_slug: "proj", url: "not a url" })).ok).toBe(false);
+ expect(
+ (await call("browser_open", { project_slug: "proj", label: "-starts-with-dash" })).ok,
+ ).toBe(false);
+ expect(session.getOrLaunchBrowser).not.toHaveBeenCalled();
+ });
+
+ it("wraps launch failures", async () => {
+ session.getOrLaunchBrowser.mockRejectedValue(new Error("no chrome binary"));
+ const r = await call("browser_open", { project_slug: "proj" });
+ expect(errorOf(r)).toBe("browser_open failed: no chrome binary");
+ });
+});
+
+describe("browser_close", () => {
+ it("reports both the closed and the not-found outcome", async () => {
+ tabs.closeTab.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
+ expect(text(await call("browser_close", BASE))).toBe('Closed tab "agent-1".');
+ expect(text(await call("browser_close", BASE))).toBe('No tab "agent-1" to close.');
+ expect(tabs.closeTab).toHaveBeenCalledWith("proj", "agent-1");
+ });
+
+ it("wraps close failures", async () => {
+ tabs.closeTab.mockRejectedValue(new Error("boom"));
+ expect(errorOf(await call("browser_close", BASE))).toBe("browser_close failed: boom");
+ });
+});
+
+describe("browser_navigate", () => {
+ it("navigates the resolved tab and returns url + title", async () => {
+ actions.navigate.mockResolvedValue({ url: "https://x/after", title: "After" });
+ const r = await call("browser_navigate", {
+ ...BASE,
+ url: "https://x/after",
+ wait_until: "domcontentloaded",
+ timeout_ms: 5000,
+ });
+ expect(tabs.getTab).toHaveBeenCalledWith("proj", "agent-1");
+ expect(actions.navigate).toHaveBeenCalledWith(PAGE, {
+ url: "https://x/after",
+ waitUntil: "domcontentloaded",
+ timeoutMs: 5000,
+ });
+ expect(JSON.parse(text(r))).toEqual({ url: "https://x/after", title: "After" });
+ });
+
+ it("fails with guidance when the tab is unknown", async () => {
+ tabs.getTab.mockResolvedValue(null);
+ const r = await call("browser_navigate", { ...BASE, url: "https://x" });
+ expect(errorOf(r)).toContain('No tab "agent-1" in workspace "proj"');
+ expect(actions.navigate).not.toHaveBeenCalled();
+ });
+
+ it("caps timeout_ms at 120s", async () => {
+ const r = await call("browser_navigate", { ...BASE, url: "https://x", timeout_ms: 500_000 });
+ expect(r.ok).toBe(false);
+ });
+});
+
+describe("browser_snapshot", () => {
+ const SNAP = {
+ url: "https://x",
+ title: "X",
+ elements: [
+ { ref: "e1", role: "button", name: "Save" },
+ { ref: "e2", role: "a", name: "Docs", href: "https://x/docs" },
+ ],
+ text: "page text",
+ };
+
+ it("returns the full snapshot", async () => {
+ actions.snapshot.mockResolvedValue(SNAP);
+ const r = await call("browser_snapshot", BASE);
+ expect(JSON.parse(text(r))).toEqual(SNAP);
+ });
+
+ it("truncates the element list to max_elements", async () => {
+ actions.snapshot.mockResolvedValue(SNAP);
+ const r = await call("browser_snapshot", { ...BASE, max_elements: 1 });
+ const parsed = JSON.parse(text(r));
+ expect(parsed.elements).toEqual([SNAP.elements[0]]);
+ expect(parsed.text).toBe("page text");
+ });
+
+ it("fails when the tab is unknown", async () => {
+ tabs.getTab.mockResolvedValue(null);
+ expect(errorOf(await call("browser_snapshot", BASE))).toContain('No tab "agent-1"');
+ });
+});
+
+describe("browser_click", () => {
+ it("clicks the ref with the mapped options", async () => {
+ actions.click.mockResolvedValue(undefined);
+ const r = await call("browser_click", {
+ ...BASE,
+ ref: "e3",
+ button: "right",
+ modifiers: ["Meta"],
+ double_click: true,
+ timeout_ms: 2000,
+ });
+ expect(actions.click).toHaveBeenCalledWith(PAGE, {
+ ref: "e3",
+ button: "right",
+ modifiers: ["Meta"],
+ doubleClick: true,
+ timeoutMs: 2000,
+ });
+ expect(text(r)).toBe('Clicked e3 on tab "agent-1".');
+ });
+
+ it("rejects refs that do not look like snapshot refs", async () => {
+ const r = await call("browser_click", { ...BASE, ref: "button#save" });
+ expect(r.ok).toBe(false);
+ expect(actions.click).not.toHaveBeenCalled();
+ });
+});
+
+describe("browser_type", () => {
+ it("types with mapped options and reports the char count", async () => {
+ actions.type.mockResolvedValue(undefined);
+ const r = await call("browser_type", {
+ ...BASE,
+ ref: "e2",
+ text: "hello",
+ submit: true,
+ clear_first: false,
+ });
+ expect(actions.type).toHaveBeenCalledWith(PAGE, {
+ ref: "e2",
+ text: "hello",
+ submit: true,
+ clearFirst: false,
+ timeoutMs: undefined,
+ });
+ expect(text(r)).toBe("Typed 5 chars into e2 and submitted.");
+ });
+
+ it("omits the submit suffix by default", async () => {
+ actions.type.mockResolvedValue(undefined);
+ const r = await call("browser_type", { ...BASE, ref: "e2", text: "hi" });
+ expect(text(r)).toBe("Typed 2 chars into e2.");
+ });
+});
+
+describe("browser_press", () => {
+ it("presses at the page level without a ref", async () => {
+ actions.press.mockResolvedValue(undefined);
+ const r = await call("browser_press", { ...BASE, key: "Escape" });
+ expect(actions.press).toHaveBeenCalledWith(PAGE, { key: "Escape", ref: undefined });
+ expect(text(r)).toBe("Pressed Escape.");
+ });
+
+ it("focuses the ref first when given", async () => {
+ actions.press.mockResolvedValue(undefined);
+ const r = await call("browser_press", { ...BASE, key: "Enter", ref: "e4" });
+ expect(actions.press).toHaveBeenCalledWith(PAGE, { key: "Enter", ref: "e4" });
+ expect(text(r)).toBe("Pressed Enter on e4.");
+ });
+});
+
+describe("browser_scroll", () => {
+ it("scrolls with an explicit amount", async () => {
+ actions.scroll.mockResolvedValue(undefined);
+ const r = await call("browser_scroll", { ...BASE, direction: "down", amount: 900 });
+ expect(actions.scroll).toHaveBeenCalledWith(PAGE, { direction: "down", amount: 900 });
+ expect(text(r)).toBe("Scrolled down by 900px.");
+ });
+
+ it("omits the pixel clause when using the default amount", async () => {
+ actions.scroll.mockResolvedValue(undefined);
+ const r = await call("browser_scroll", { ...BASE, direction: "up" });
+ expect(text(r)).toBe("Scrolled up.");
+ });
+});
+
+describe("browser_back", () => {
+ it("navigates back on the tab", async () => {
+ actions.back.mockResolvedValue(undefined);
+ const r = await call("browser_back", BASE);
+ expect(actions.back).toHaveBeenCalledWith(PAGE);
+ expect(text(r)).toBe('Navigated back on tab "agent-1".');
+ });
+
+ it("fails when the tab is unknown", async () => {
+ tabs.getTab.mockResolvedValue(null);
+ expect(errorOf(await call("browser_back", BASE))).toContain('No tab "agent-1"');
+ });
+});
diff --git a/notfair/src/server/mcp-server/secret.test.ts b/notfair/src/server/mcp-server/secret.test.ts
new file mode 100644
index 00000000..13c42bb2
--- /dev/null
+++ b/notfair/src/server/mcp-server/secret.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from "vitest";
+import { existsSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+// Real fs against a tmpdir data dir, per repo test conventions.
+// MUST be hoisted: secret.ts captures NOTFAIR_DATA_DIR at import time, so a
+// plain assignment would point the suite at the developer's live ~/.notfair.
+const h = vi.hoisted(() => {
+ const { mkdtempSync, rmSync } = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-secret-"));
+ // The module mints the data dir itself when missing — exercise that path.
+ rmSync(dataDir, { recursive: true, force: true });
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir };
+});
+
+import {
+ getMcpServerSecretPath,
+ getOrCreateMcpServerSecret,
+ verifyMcpServerSecret,
+} from "./secret";
+
+describe("getOrCreateMcpServerSecret", () => {
+ it("mints a 32-byte hex secret and creates the data dir on first read", () => {
+ expect(existsSync(h.dataDir)).toBe(false);
+ const secret = getOrCreateMcpServerSecret();
+ expect(secret).toMatch(/^[0-9a-f]{64}$/);
+ expect(existsSync(h.dataDir)).toBe(true);
+ });
+
+ it("persists with 0600 perms and a trailing newline", () => {
+ getOrCreateMcpServerSecret();
+ const mode = statSync(getMcpServerSecretPath()).mode & 0o777;
+ expect(mode).toBe(0o600);
+ });
+
+ it("returns the same secret on subsequent reads", () => {
+ expect(getOrCreateMcpServerSecret()).toBe(getOrCreateMcpServerSecret());
+ });
+
+ it("re-mints when the stored file is empty", () => {
+ const first = getOrCreateMcpServerSecret();
+ writeFileSync(getMcpServerSecretPath(), "\n", "utf8");
+ const second = getOrCreateMcpServerSecret();
+ expect(second).toMatch(/^[0-9a-f]{64}$/);
+ expect(second).not.toBe(first);
+ });
+
+ it("re-mints after the file is deleted (manual rotation)", () => {
+ const first = getOrCreateMcpServerSecret();
+ rmSync(getMcpServerSecretPath());
+ expect(getOrCreateMcpServerSecret()).not.toBe(first);
+ });
+});
+
+describe("verifyMcpServerSecret", () => {
+ it("accepts the stored secret", () => {
+ const secret = getOrCreateMcpServerSecret();
+ expect(verifyMcpServerSecret(secret)).toBe(true);
+ });
+
+ it("rejects null / undefined / empty without throwing", () => {
+ expect(verifyMcpServerSecret(null)).toBe(false);
+ expect(verifyMcpServerSecret(undefined)).toBe(false);
+ expect(verifyMcpServerSecret("")).toBe(false);
+ });
+
+ it("rejects a length-mismatched bearer before the constant-time compare", () => {
+ expect(verifyMcpServerSecret("short")).toBe(false);
+ });
+
+ it("rejects an equal-length wrong bearer", () => {
+ const secret = getOrCreateMcpServerSecret();
+ const wrong = secret.slice(0, -1) + (secret.endsWith("0") ? "1" : "0");
+ expect(wrong).toHaveLength(secret.length);
+ expect(verifyMcpServerSecret(wrong)).toBe(false);
+ });
+});
+
+describe("getMcpServerSecretPath", () => {
+ it("lives inside the data dir", () => {
+ expect(getMcpServerSecretPath()).toBe(join(h.dataDir, "mcp-server-secret"));
+ });
+});
diff --git a/notfair/src/server/mcp-server/tools.test.ts b/notfair/src/server/mcp-server/tools.test.ts
new file mode 100644
index 00000000..0fd9e624
--- /dev/null
+++ b/notfair/src/server/mcp-server/tools.test.ts
@@ -0,0 +1,515 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const handlers = vi.hoisted(() => ({
+ handleAmendGoal: vi.fn(),
+ handleAddSupportMetric: vi.fn(),
+ handleBackfillHistory: vi.fn(),
+ handleDefineGoal: vi.fn(),
+ handleGetGoal: vi.fn(),
+ handleGetProject: vi.fn(),
+ handleLogGoalAction: vi.fn(),
+ handleLogLearning: vi.fn(),
+ handleProposeGoalMetric: vi.fn(),
+ handleProposeTarget: vi.fn(),
+ handleRegisterPullRequest: vi.fn(),
+ handleReviewGoalAction: vi.fn(),
+ handleSearchLearnings: vi.fn(),
+ handleSetProjectBrief: vi.fn(),
+ handleUpdateGoalStatus: vi.fn(),
+}));
+
+vi.mock("@/server/goals/handlers", () => handlers);
+
+import { TOOLS, describeTool, findTool, type ToolResult } from "./tools";
+
+const CTX = { project_slug: "proj", agent_id: "agent-1" };
+const BASE = { project_slug: "proj", agent_id: "agent-1", goal_id: "goal-1" };
+
+function ok<T>(data: T) {
+ return { ok: true as const, data };
+}
+
+async function call(name: string, input: unknown): Promise<ToolResult> {
+ const tool = findTool(name);
+ if (!tool) throw new Error(`no tool ${name}`);
+ return tool.handler(input, {});
+}
+
+function text(result: ToolResult): string {
+ if (!result.ok) throw new Error(`expected ok result, got: ${result.error}`);
+ return result.content.map((c) => c.text).join("\n");
+}
+
+beforeEach(() => {
+ for (const fn of Object.values(handlers)) fn.mockReset();
+});
+
+describe("registry", () => {
+ it("exposes the full goal-lifecycle surface", () => {
+ expect(TOOLS.map((t) => t.name)).toEqual([
+ "get_goal",
+ "define_goal",
+ "propose_goal_metric",
+ "backfill_metric_history",
+ "add_supporting_metric",
+ "propose_target",
+ "amend_goal",
+ "log_goal_action",
+ "register_pull_request",
+ "review_goal_action",
+ "log_learning",
+ "search_learnings",
+ "update_goal_status",
+ "get_project",
+ "set_shared_context",
+ ]);
+ for (const tool of TOOLS) {
+ expect(tool.description.length).toBeGreaterThan(20);
+ expect(typeof tool.handler).toBe("function");
+ }
+ });
+
+ it("findTool resolves by name and misses cleanly", () => {
+ expect(findTool("get_goal")?.name).toBe("get_goal");
+ expect(findTool("no_such_tool")).toBeUndefined();
+ });
+
+ it("every tool rejects malformed args without calling its handler", async () => {
+ for (const tool of TOOLS) {
+ const r = await tool.handler({ project_slug: 42 }, {});
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toMatch(/^Invalid arguments:/);
+ }
+ for (const fn of Object.values(handlers)) expect(fn).not.toHaveBeenCalled();
+ });
+});
+
+describe("describeTool JSON schema", () => {
+ it("maps enum/number/string/optionality for propose_goal_metric", () => {
+ const desc = describeTool(findTool("propose_goal_metric")!);
+ expect(desc.name).toBe("propose_goal_metric");
+ const schema = desc.inputSchema as {
+ type: string;
+ properties: Record<string, { type: string; enum?: string[]; description?: string }>;
+ required: string[];
+ additionalProperties: boolean;
+ };
+ expect(schema.type).toBe("object");
+ expect(schema.additionalProperties).toBe(false);
+ expect(schema.properties.metric_direction).toMatchObject({
+ type: "string",
+ enum: ["increase", "decrease"],
+ });
+ expect(schema.properties.project_slug).toMatchObject({
+ type: "string",
+ description: "From IDENTITY.md.",
+ });
+ expect(schema.required).toEqual([
+ "project_slug",
+ "agent_id",
+ "goal_id",
+ "metric_name",
+ "metric_source_key",
+ "metric_source_tool",
+ "metric_source_args_json",
+ "metric_direction",
+ ]);
+ });
+
+ it("optional numbers and booleans keep their types but leave required", () => {
+ const define = describeTool(findTool("define_goal")!).inputSchema as {
+ properties: Record<string, { type: string }>;
+ required: string[];
+ };
+ expect(define.properties.spend_envelope_usd.type).toBe("number");
+ expect(define.required).not.toContain("spend_envelope_usd");
+ expect(define.required).not.toContain("deadline");
+
+ const review = describeTool(findTool("review_goal_action")!).inputSchema as {
+ properties: Record<string, { type: string }>;
+ required: string[];
+ };
+ expect(review.properties.abandoned.type).toBe("boolean");
+ expect(review.required).not.toContain("abandoned");
+ });
+});
+
+describe("get_goal", () => {
+ it("dispatches and returns the goal state as JSON", async () => {
+ handlers.handleGetGoal.mockResolvedValueOnce(ok({ statement: "grow" }));
+ const r = await call("get_goal", BASE);
+ expect(handlers.handleGetGoal).toHaveBeenCalledWith({ goal_id: "goal-1" }, CTX);
+ expect(JSON.parse(text(r))).toEqual({ statement: "grow" });
+ });
+
+ it("surfaces handler errors", async () => {
+ handlers.handleGetGoal.mockResolvedValueOnce({ ok: false, error: "Unknown goal_id 'goal-1'" });
+ const r = await call("get_goal", BASE);
+ expect(r).toEqual({ ok: false, error: "Unknown goal_id 'goal-1'" });
+ });
+});
+
+describe("define_goal", () => {
+ it("splits caller identity from the payload", async () => {
+ handlers.handleDefineGoal.mockReturnValueOnce(ok({ statement: "Cut CAC to $30" }));
+ const r = await call("define_goal", {
+ ...BASE,
+ statement: "Cut CAC to $30",
+ short_label: "CAC → $30",
+ deadline: "2026-09-01",
+ spend_envelope_usd: 500,
+ });
+ expect(handlers.handleDefineGoal).toHaveBeenCalledWith(
+ {
+ goal_id: "goal-1",
+ statement: "Cut CAC to $30",
+ short_label: "CAC → $30",
+ deadline: "2026-09-01",
+ spend_envelope_usd: 500,
+ },
+ CTX,
+ );
+ expect(text(r)).toContain('goal defined: "Cut CAC to $30"');
+ });
+
+ it("enforces the 48-char short_label cap", async () => {
+ const r = await call("define_goal", {
+ ...BASE,
+ statement: "x",
+ short_label: "y".repeat(49),
+ });
+ expect(r.ok).toBe(false);
+ expect(handlers.handleDefineGoal).not.toHaveBeenCalled();
+ });
+});
+
+describe("propose_goal_metric", () => {
+ it("reports the verified baseline", async () => {
+ handlers.handleProposeGoalMetric.mockResolvedValueOnce(ok({ baseline_value: 42.5 }));
+ const r = await call("propose_goal_metric", {
+ ...BASE,
+ metric_name: "CAC (USD, trailing 30d)",
+ metric_source_key: "notfair-googleads",
+ metric_source_tool: "runScript",
+ metric_source_args_json: '{"script":"..."}',
+ metric_direction: "decrease",
+ });
+ expect(handlers.handleProposeGoalMetric).toHaveBeenCalledWith(
+ {
+ goal_id: "goal-1",
+ metric_name: "CAC (USD, trailing 30d)",
+ metric_source_key: "notfair-googleads",
+ metric_source_tool: "runScript",
+ metric_source_args_json: '{"script":"..."}',
+ metric_direction: "decrease",
+ },
+ CTX,
+ );
+ expect(text(r)).toContain("Baseline measured: 42.5");
+ });
+
+ it("rejects an unknown metric_direction", async () => {
+ const r = await call("propose_goal_metric", {
+ ...BASE,
+ metric_name: "x",
+ metric_source_key: "k",
+ metric_source_tool: "t",
+ metric_source_args_json: "{}",
+ metric_direction: "sideways",
+ });
+ expect(r.ok).toBe(false);
+ });
+});
+
+describe("backfill_metric_history", () => {
+ it("summarizes the backfilled range", async () => {
+ handlers.handleBackfillHistory.mockResolvedValueOnce(
+ ok({ points: 30, from: "2026-06-01", to: "2026-06-30" }),
+ );
+ const r = await call("backfill_metric_history", {
+ ...BASE,
+ source_key: "notfair-googleads",
+ source_tool: "runScript",
+ source_args_json: "{}",
+ });
+ expect(text(r)).toBe(
+ "History backfilled: 30 daily points from 2026-06-01 to 2026-06-30. The progress chart now has context.",
+ );
+ });
+
+ it("surfaces handler errors", async () => {
+ handlers.handleBackfillHistory.mockResolvedValueOnce({ ok: false, error: "query failed" });
+ const r = await call("backfill_metric_history", {
+ ...BASE,
+ source_key: "k",
+ source_tool: "t",
+ source_args_json: "{}",
+ });
+ expect(r).toEqual({ ok: false, error: "query failed" });
+ });
+});
+
+describe("add_supporting_metric", () => {
+ const args = {
+ ...BASE,
+ name: "PRs open (live)",
+ source_key: "local",
+ source_tool: "shell",
+ source_args_json: '{"command":"echo 3"}',
+ };
+
+ it("mentions backfilled points when history was provided", async () => {
+ handlers.handleAddSupportMetric.mockResolvedValueOnce(
+ ok({ metric: { name: "PRs open (live)", current_value: 3 }, backfilled: 30 }),
+ );
+ const r = await call("add_supporting_metric", { ...args, history_args_json: "{}" });
+ expect(text(r)).toContain("current value 3, 30 history points backfilled");
+ });
+
+ it("omits the backfill clause when nothing was backfilled", async () => {
+ handlers.handleAddSupportMetric.mockResolvedValueOnce(
+ ok({ metric: { name: "PRs open (live)", current_value: 3 }, backfilled: 0 }),
+ );
+ const r = await call("add_supporting_metric", args);
+ expect(text(r)).not.toContain("backfilled");
+ });
+});
+
+describe("propose_target", () => {
+ it("rejects an invalid cadence_cron before touching the handler", async () => {
+ const r = await call("propose_target", {
+ ...BASE,
+ target_value: 30,
+ cadence_cron: "not a cron",
+ });
+ expect(r).toEqual({
+ ok: false,
+ error: "Invalid cadence_cron 'not a cron' — must be a 5-field cron expression.",
+ });
+ expect(handlers.handleProposeTarget).not.toHaveBeenCalled();
+ });
+
+ it("accepts a valid cron and starts the loop", async () => {
+ handlers.handleProposeTarget.mockReturnValueOnce(ok({}));
+ const r = await call("propose_target", {
+ ...BASE,
+ target_value: 30,
+ mode: "maintain",
+ cadence_cron: "0 16 * * 1-5",
+ });
+ expect(handlers.handleProposeTarget).toHaveBeenCalledWith(
+ { goal_id: "goal-1", target_value: 30, mode: "maintain", cadence_cron: "0 16 * * 1-5" },
+ CTX,
+ );
+ expect(text(r)).toContain("loop is LIVE");
+ });
+
+ it("cadence_cron is optional", async () => {
+ handlers.handleProposeTarget.mockReturnValueOnce(ok({}));
+ const r = await call("propose_target", { ...BASE, target_value: 30 });
+ expect(r.ok).toBe(true);
+ });
+});
+
+describe("amend_goal", () => {
+ it("validates cadence_cron", async () => {
+ const r = await call("amend_goal", { ...BASE, cadence_cron: "99 99 * * *" });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toContain("Invalid cadence_cron");
+ expect(handlers.handleAmendGoal).not.toHaveBeenCalled();
+ });
+
+ it("echoes the amended values, with placeholders for unset fields", async () => {
+ handlers.handleAmendGoal.mockReturnValueOnce(
+ ok({ target_value: null, deadline: null, spend_envelope_usd: null, cadence_cron: "0 16 * * *" }),
+ );
+ const r = await call("amend_goal", { ...BASE, cadence_cron: "0 16 * * *" });
+ expect(text(r)).toBe(
+ "Goal amended: target=—, deadline=none, envelope=none, cadence=0 16 * * *. Confirm the change back to the user.",
+ );
+ });
+
+ it("formats set values", async () => {
+ handlers.handleAmendGoal.mockReturnValueOnce(
+ ok({
+ target_value: 25,
+ deadline: "2026-10-01",
+ spend_envelope_usd: 400,
+ cadence_cron: "0 16 * * 1",
+ }),
+ );
+ const r = await call("amend_goal", { ...BASE, target_value: 25 });
+ expect(text(r)).toContain("target=25, deadline=2026-10-01, envelope=$400, cadence=0 16 * * 1");
+ });
+});
+
+describe("log_goal_action", () => {
+ const args = {
+ ...BASE,
+ kind: "mutation",
+ description: "Lower tROAS to 220% on campaign 123",
+ expected_effect: "CPA -$3 within 7 days",
+ };
+
+ it("splits resources_touched into a trimmed list", async () => {
+ handlers.handleLogGoalAction.mockReturnValueOnce(
+ ok({ action_id: "act-1", review_after: "2026-07-25T00:00:00.000Z" }),
+ );
+ const r = await call("log_goal_action", {
+ ...args,
+ resources_touched: " campaign:123 , adgroup:456,, ",
+ review_after_hours: 120,
+ });
+ expect(handlers.handleLogGoalAction).toHaveBeenCalledWith(
+ {
+ goal_id: "goal-1",
+ kind: "mutation",
+ description: "Lower tROAS to 220% on campaign 123",
+ expected_effect: "CPA -$3 within 7 days",
+ resources_touched: ["campaign:123", "adgroup:456"],
+ review_after_hours: 120,
+ },
+ CTX,
+ );
+ expect(text(r)).toBe(
+ "action act-1 logged. Review due 2026-07-25T00:00:00.000Z. Its resources are gated until then.",
+ );
+ });
+
+ it("defaults resources to [] and omits the gate sentence without review_after", async () => {
+ handlers.handleLogGoalAction.mockReturnValueOnce(ok({ action_id: "act-2", review_after: null }));
+ const r = await call("log_goal_action", { ...args, kind: "research" });
+ expect(handlers.handleLogGoalAction).toHaveBeenCalledWith(
+ expect.objectContaining({ resources_touched: [] }),
+ CTX,
+ );
+ expect(text(r)).toBe("action act-2 logged.");
+ });
+});
+
+describe("register_pull_request", () => {
+ it("dispatches and reports the PR state", async () => {
+ handlers.handleRegisterPullRequest.mockResolvedValueOnce(ok({ state: "open" }));
+ const r = await call("register_pull_request", {
+ ...BASE,
+ url: "https://github.com/o/r/pull/7",
+ title: "feat: add landing page",
+ branch: "feat/landing",
+ action_id: "act-1",
+ });
+ expect(handlers.handleRegisterPullRequest).toHaveBeenCalledWith(
+ {
+ goal_id: "goal-1",
+ url: "https://github.com/o/r/pull/7",
+ title: "feat: add landing page",
+ branch: "feat/landing",
+ action_id: "act-1",
+ },
+ CTX,
+ );
+ expect(text(r)).toContain("PR registered (state: open)");
+ });
+});
+
+describe("review_goal_action", () => {
+ it("reports status and any recorded learning", async () => {
+ handlers.handleReviewGoalAction.mockReturnValueOnce(
+ ok({ action_id: "act-1", status: "reviewed", learning_id: "lrn-9" }),
+ );
+ const r = await call("review_goal_action", {
+ ...BASE,
+ action_id: "act-1",
+ observed_outcome: "CPA fell $2.10 vs the $3 predicted",
+ learning: "tROAS moves take ~5 days to settle",
+ });
+ expect(text(r)).toBe("action act-1 reviewed. Learning lrn-9 recorded.");
+ });
+
+ it("omits the learning clause when none was recorded", async () => {
+ handlers.handleReviewGoalAction.mockReturnValueOnce(
+ ok({ action_id: "act-1", status: "abandoned", learning_id: null }),
+ );
+ const r = await call("review_goal_action", {
+ ...BASE,
+ action_id: "act-1",
+ observed_outcome: "reverted",
+ abandoned: true,
+ });
+ expect(text(r)).toBe("action act-1 abandoned.");
+ });
+});
+
+describe("log_learning / search_learnings", () => {
+ it("log_learning confirms the recorded id", async () => {
+ handlers.handleLogLearning.mockReturnValueOnce(ok({ learning_id: "lrn-1" }));
+ const r = await call("log_learning", {
+ ...BASE,
+ body: "Brand campaigns cap out at ~$40/day",
+ confidence: "high",
+ });
+ expect(handlers.handleLogLearning).toHaveBeenCalledWith(
+ { goal_id: "goal-1", body: "Brand campaigns cap out at ~$40/day", confidence: "high" },
+ CTX,
+ );
+ expect(text(r)).toBe("learning lrn-1 recorded.");
+ });
+
+ it("search_learnings returns the matches as JSON", async () => {
+ handlers.handleSearchLearnings.mockReturnValueOnce(
+ ok({ learnings: [{ id: "lrn-1", body: "fact" }] }),
+ );
+ const r = await call("search_learnings", { ...BASE, query: "fact", limit: 5 });
+ expect(handlers.handleSearchLearnings).toHaveBeenCalledWith(
+ { goal_id: "goal-1", query: "fact", limit: 5 },
+ CTX,
+ );
+ expect(JSON.parse(text(r))).toEqual([{ id: "lrn-1", body: "fact" }]);
+ });
+});
+
+describe("update_goal_status", () => {
+ it("dispatches and confirms the new status", async () => {
+ handlers.handleUpdateGoalStatus.mockReturnValueOnce(
+ ok({ goal_id: "goal-1", status: "achieved" }),
+ );
+ const r = await call("update_goal_status", {
+ ...BASE,
+ status: "achieved",
+ reason: "CAC measured at $28.40, target $30",
+ });
+ expect(text(r)).toBe("goal goal-1 is now 'achieved'.");
+ });
+
+ it("rejects statuses outside the enum", async () => {
+ const r = await call("update_goal_status", { ...BASE, status: "done", reason: "x" });
+ expect(r.ok).toBe(false);
+ });
+});
+
+describe("get_project / set_shared_context", () => {
+ it("get_project returns project metadata as JSON", async () => {
+ handlers.handleGetProject.mockReturnValueOnce(ok({ slug: "proj", website: "https://x.co" }));
+ const r = await call("get_project", { project_slug: "proj", agent_id: "agent-1" });
+ expect(handlers.handleGetProject).toHaveBeenCalledWith({}, CTX);
+ expect(JSON.parse(text(r))).toEqual({ slug: "proj", website: "https://x.co" });
+ });
+
+ it("set_shared_context pluralizes the synced-agent count", async () => {
+ handlers.handleSetProjectBrief.mockResolvedValueOnce(ok({ bytes: 512, synced_agents: 2 }));
+ const two = await call("set_shared_context", {
+ project_slug: "proj",
+ agent_id: "agent-1",
+ content: "# Brief",
+ });
+ expect(handlers.handleSetProjectBrief).toHaveBeenCalledWith({ content: "# Brief" }, CTX);
+ expect(text(two)).toBe("shared context updated (512 bytes); 2 agent identities re-rendered.");
+
+ handlers.handleSetProjectBrief.mockResolvedValueOnce(ok({ bytes: 64, synced_agents: 1 }));
+ const one = await call("set_shared_context", {
+ project_slug: "proj",
+ agent_id: "agent-1",
+ content: "# Brief",
+ });
+ expect(text(one)).toBe("shared context updated (64 bytes); 1 agent identity re-rendered.");
+ });
+});
diff --git a/notfair/src/server/mcp/discovery-url.test.ts b/notfair/src/server/mcp/discovery-url.test.ts
new file mode 100644
index 00000000..474c6a27
--- /dev/null
+++ b/notfair/src/server/mcp/discovery-url.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+
+import { deriveDiscoveryUrl, normalizeResourceUrl } from "./discovery-url";
+
+describe("normalizeResourceUrl", () => {
+ it("lowercases scheme and host, preserves path case", () => {
+ expect(normalizeResourceUrl("HTTPS://NotFair.CO/Api/Mcp")).toBe(
+ "https://notfair.co/Api/Mcp",
+ );
+ });
+
+ it("drops trailing slashes from the path", () => {
+ expect(normalizeResourceUrl("https://notfair.co/api/mcp///")).toBe(
+ "https://notfair.co/api/mcp",
+ );
+ });
+
+ it("drops the default https port 443", () => {
+ expect(normalizeResourceUrl("https://notfair.co:443/api")).toBe(
+ "https://notfair.co/api",
+ );
+ });
+
+ it("drops the default http port 80", () => {
+ expect(normalizeResourceUrl("http://notfair.co:80/api")).toBe(
+ "http://notfair.co/api",
+ );
+ });
+
+ it("keeps a non-default port", () => {
+ expect(normalizeResourceUrl("http://127.0.0.1:3326/api/mcp/goals")).toBe(
+ "http://127.0.0.1:3326/api/mcp/goals",
+ );
+ });
+
+ it("root-only URLs normalize to origin with no trailing slash", () => {
+ expect(normalizeResourceUrl("https://notfair.co/")).toBe("https://notfair.co");
+ });
+
+ it("falls back to trim + lowercase + slash-strip for unparseable input", () => {
+ expect(normalizeResourceUrl(" Not A URL// ")).toBe("not a url");
+ });
+});
+
+describe("deriveDiscoveryUrl", () => {
+ it("inserts the well-known suffix between origin and path", () => {
+ expect(deriveDiscoveryUrl("https://notfair.co/api/mcp/google_ads")).toBe(
+ "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/google_ads",
+ );
+ });
+
+ it("root resources get the suffix with no trailing path", () => {
+ expect(deriveDiscoveryUrl("https://mcp.example.com/")).toBe(
+ "https://mcp.example.com/.well-known/oauth-protected-resource",
+ );
+ });
+
+ it("strips trailing slashes from a non-root path", () => {
+ expect(deriveDiscoveryUrl("https://mcp.example.com/v1/")).toBe(
+ "https://mcp.example.com/.well-known/oauth-protected-resource/v1",
+ );
+ });
+
+ it("supports plain http", () => {
+ expect(deriveDiscoveryUrl("http://127.0.0.1:9000/mcp")).toBe(
+ "http://127.0.0.1:9000/.well-known/oauth-protected-resource/mcp",
+ );
+ });
+
+ it("returns null for malformed input", () => {
+ expect(deriveDiscoveryUrl("not a url")).toBeNull();
+ });
+
+ it("returns null for non-HTTP(S) schemes", () => {
+ expect(deriveDiscoveryUrl("ftp://example.com/mcp")).toBeNull();
+ expect(deriveDiscoveryUrl("file:///tmp/mcp")).toBeNull();
+ });
+});
diff --git a/notfair/src/server/mcp/refresh.test.ts b/notfair/src/server/mcp/refresh.test.ts
new file mode 100644
index 00000000..cc3e9a4d
--- /dev/null
+++ b/notfair/src/server/mcp/refresh.test.ts
@@ -0,0 +1,172 @@
+import { afterEach, 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-refresh-"));
+});
+
+import { getDb } from "@/server/db/db";
+import { isExpiringSoon, refreshMcpToken } from "./refresh";
+import { getMcpToken, upsertMcpToken, type McpToken } from "./tokens";
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ // mcp_tokens.project_slug FKs to projects(slug).
+ getDb()
+ .prepare(
+ "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('proj', 'proj', 'proj', ?, 'claude-code-local')",
+ )
+ .run(new Date().toISOString());
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+let counter = 0;
+function makeToken(overrides: Partial<Parameters<typeof upsertMcpToken>[0]> = {}): McpToken {
+ return upsertMcpToken({
+ project_slug: "proj",
+ server_name: `srv-${++counter}`,
+ access_token: "old-at",
+ refresh_token: "rt-1",
+ token_endpoint: "https://oauth.example.com/token",
+ client_id: "cid",
+ ...overrides,
+ });
+}
+
+function jsonResponse(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+describe("refreshMcpToken", () => {
+ it("returns null without fetching when refresh fields are missing", async () => {
+ const noRefresh = makeToken({ refresh_token: undefined });
+ const noEndpoint = makeToken({ token_endpoint: undefined });
+ const noClient = makeToken({ client_id: undefined });
+ expect(await refreshMcpToken(noRefresh)).toBeNull();
+ expect(await refreshMcpToken(noEndpoint)).toBeNull();
+ expect(await refreshMcpToken(noClient)).toBeNull();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("posts a urlencoded refresh_token grant and persists the rotated pair", async () => {
+ const token = makeToken();
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ access_token: "new-at", refresh_token: "rt-2", expires_in: 3600 }),
+ );
+
+ const before = Date.now();
+ const refreshed = await refreshMcpToken(token);
+ const after = Date.now();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0]! as [string, RequestInit];
+ expect(url).toBe("https://oauth.example.com/token");
+ expect(init.method).toBe("POST");
+ expect((init.headers as Record<string, string>)["Content-Type"]).toBe(
+ "application/x-www-form-urlencoded",
+ );
+ const params = new URLSearchParams(init.body as string);
+ expect(params.get("grant_type")).toBe("refresh_token");
+ expect(params.get("refresh_token")).toBe("rt-1");
+ expect(params.get("client_id")).toBe("cid");
+ expect(params.get("client_secret")).toBeNull();
+
+ expect(refreshed).not.toBeNull();
+ expect(refreshed!.access_token_enc).toBe("new-at");
+ expect(refreshed!.refresh_token_enc).toBe("rt-2");
+ const expiresMs = Date.parse(refreshed!.expires_at!);
+ expect(expiresMs).toBeGreaterThanOrEqual(before + 3600 * 1000);
+ expect(expiresMs).toBeLessThanOrEqual(after + 3600 * 1000);
+
+ // Persisted, not just returned.
+ expect(getMcpToken(token.id)!.access_token_enc).toBe("new-at");
+ });
+
+ it("includes client_secret when stored", async () => {
+ const token = makeToken({ client_secret: "shh" });
+ fetchMock.mockResolvedValueOnce(jsonResponse({ access_token: "new-at" }));
+ await refreshMcpToken(token);
+ const params = new URLSearchParams(fetchMock.mock.calls[0]![1].body as string);
+ expect(params.get("client_secret")).toBe("shh");
+ });
+
+ it("keeps the existing refresh token when the response omits one", async () => {
+ const token = makeToken();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ access_token: "new-at" }));
+ const refreshed = await refreshMcpToken(token);
+ expect(refreshed!.refresh_token_enc).toBe("rt-1");
+ expect(refreshed!.expires_at).toBeNull();
+ });
+
+ it("returns null and leaves the row alone on network error", async () => {
+ const token = makeToken();
+ fetchMock.mockRejectedValueOnce(new Error("ECONNREFUSED"));
+ expect(await refreshMcpToken(token)).toBeNull();
+ expect(getMcpToken(token.id)!.access_token_enc).toBe("old-at");
+ });
+
+ it("returns null on a non-2xx response", async () => {
+ const token = makeToken();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ error: "invalid_grant" }, 400));
+ expect(await refreshMcpToken(token)).toBeNull();
+ expect(getMcpToken(token.id)!.access_token_enc).toBe("old-at");
+ });
+
+ it("returns null on a non-JSON body", async () => {
+ const token = makeToken();
+ fetchMock.mockResolvedValueOnce(new Response("<html>oops</html>", { status: 200 }));
+ expect(await refreshMcpToken(token)).toBeNull();
+ });
+
+ it("returns null when the response has no access_token", async () => {
+ const token = makeToken();
+ fetchMock.mockResolvedValueOnce(jsonResponse({ token_type: "Bearer" }));
+ expect(await refreshMcpToken(token)).toBeNull();
+ });
+});
+
+describe("isExpiringSoon", () => {
+ function tokenWithExpiry(expires_at: string | null): McpToken {
+ return { expires_at } as McpToken;
+ }
+
+ it("false when expires_at is missing (legacy rows)", () => {
+ expect(isExpiringSoon(tokenWithExpiry(null))).toBe(false);
+ });
+
+ it("false when expires_at is unparseable", () => {
+ expect(isExpiringSoon(tokenWithExpiry("not-a-date"))).toBe(false);
+ });
+
+ it("true when already expired", () => {
+ expect(
+ isExpiringSoon(tokenWithExpiry(new Date(Date.now() - 1000).toISOString())),
+ ).toBe(true);
+ });
+
+ it("true inside the skew window, false outside it", () => {
+ const in30s = new Date(Date.now() + 30_000).toISOString();
+ const in10m = new Date(Date.now() + 600_000).toISOString();
+ expect(isExpiringSoon(tokenWithExpiry(in30s))).toBe(true);
+ expect(isExpiringSoon(tokenWithExpiry(in10m))).toBe(false);
+ // Custom skew widens the window.
+ expect(isExpiringSoon(tokenWithExpiry(in10m), 700_000)).toBe(true);
+ });
+});
diff --git a/notfair/src/server/mcp/rpc.test.ts b/notfair/src/server/mcp/rpc.test.ts
new file mode 100644
index 00000000..982f3714
--- /dev/null
+++ b/notfair/src/server/mcp/rpc.test.ts
@@ -0,0 +1,384 @@
+import { afterEach, 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-rpc-"));
+});
+
+const refreshMocks = vi.hoisted(() => ({
+ refreshMcpToken: vi.fn(),
+ isExpiringSoon: vi.fn(),
+}));
+
+vi.mock("./refresh", () => refreshMocks);
+
+import {
+ bearerFromHeaders,
+ getMcpConfig,
+ mcpRpc,
+ mcpRpcAutoRefresh,
+ readMcpConfigRow,
+} from "./rpc";
+import { upsertMcpToken, type McpToken } from "./tokens";
+import { getDb } from "@/server/db/db";
+
+const ADS = "notfair-googleads";
+const ADS_URL = "https://notfair.co/api/mcp/google_ads";
+
+const fetchMock = vi.fn();
+
+beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal("fetch", fetchMock);
+ refreshMocks.refreshMcpToken.mockReset();
+ refreshMocks.isExpiringSoon.mockReset().mockReturnValue(false);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+let projCounter = 0;
+function freshProject(): string {
+ const slug = `proj-${++projCounter}`;
+ // mcp_tokens.project_slug FKs to projects(slug).
+ getDb()
+ .prepare(
+ "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",
+ )
+ .run(slug, slug, slug, new Date().toISOString());
+ return slug;
+}
+
+function storeToken(project_slug: string, access_token = "tok"): McpToken {
+ return upsertMcpToken({ project_slug, server_name: ADS, access_token });
+}
+
+/** Age the row's updated_at past the 5s "just refreshed" reactive-skip window. */
+function ageToken(token: McpToken): McpToken {
+ const old = new Date(Date.now() - 60_000).toISOString();
+ getDb().prepare("UPDATE mcp_tokens SET updated_at = ? WHERE id = ?").run(old, token.id);
+ return { ...token, updated_at: old };
+}
+
+function rpcSuccess(result: unknown): Response {
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: 1, result }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+describe("readMcpConfigRow / getMcpConfig", () => {
+ it("returns null for an unknown catalog key", () => {
+ expect(readMcpConfigRow(freshProject(), "no-such-server")).toBeNull();
+ expect(getMcpConfig(freshProject(), "no-such-server")).toBeNull();
+ });
+
+ it("returns url-only when no token is stored", () => {
+ const slug = freshProject();
+ expect(readMcpConfigRow(slug, ADS)).toEqual({ url: ADS_URL });
+ // No bearer → no usable config.
+ expect(getMcpConfig(slug, ADS)).toBeNull();
+ });
+
+ it("returns url + bearer header when a token exists", () => {
+ const slug = freshProject();
+ storeToken(slug, "secret-bearer");
+ expect(readMcpConfigRow(slug, ADS)).toEqual({
+ url: ADS_URL,
+ headers: { Authorization: "Bearer secret-bearer" },
+ });
+ expect(getMcpConfig(slug, ADS)).toEqual({ url: ADS_URL, token: "secret-bearer" });
+ });
+});
+
+describe("bearerFromHeaders", () => {
+ it("returns null for missing headers or missing Authorization", () => {
+ expect(bearerFromHeaders(undefined)).toBeNull();
+ expect(bearerFromHeaders({})).toBeNull();
+ });
+
+ it("extracts the bearer, case-insensitively", () => {
+ expect(bearerFromHeaders({ Authorization: "Bearer abc" })).toBe("abc");
+ expect(bearerFromHeaders({ authorization: "bearer xyz " })).toBe("xyz");
+ });
+
+ it("rejects non-bearer schemes", () => {
+ expect(bearerFromHeaders({ Authorization: "Basic dXNlcg==" })).toBeNull();
+ });
+});
+
+describe("mcpRpc", () => {
+ it("POSTs a JSON-RPC envelope with auth + protocol headers and parses the result", async () => {
+ fetchMock.mockResolvedValueOnce(rpcSuccess({ tools: [] }));
+ const r = await mcpRpc("https://mcp.example.com/x", "tok-1", "tools/list", { a: 1 });
+ expect(r).toEqual({ ok: true, result: { tools: [] } });
+
+ const [url, init] = fetchMock.mock.calls[0]! as [string, RequestInit];
+ expect(url).toBe("https://mcp.example.com/x");
+ expect(init.method).toBe("POST");
+ const headers = init.headers as Record<string, string>;
+ expect(headers.Authorization).toBe("Bearer tok-1");
+ expect(headers["MCP-Protocol-Version"]).toBe("2025-06-18");
+ expect(headers.Accept).toBe("application/json, text/event-stream");
+ expect(JSON.parse(init.body as string)).toEqual({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/list",
+ params: { a: 1 },
+ });
+ });
+
+ it("parses an SSE body, taking the last data frame", async () => {
+ const sse =
+ 'event: message\ndata: {"jsonrpc":"2.0","id":1,"result":"first"}\n\n' +
+ 'event: message\ndata: {"jsonrpc":"2.0",\ndata: "id":1,"result":"last"}\n\n';
+ fetchMock.mockResolvedValueOnce(new Response(sse, { status: 200 }));
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({ ok: true, result: "last" });
+ });
+
+ it("SSE body with no data lines is malformed", async () => {
+ fetchMock.mockResolvedValueOnce(new Response("event: ping\n\n", { status: 200 }));
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toMatchObject({ ok: false, kind: "malformed_response", message: "empty body" });
+ });
+
+ it("surfaces HTTP errors with the (truncated) body", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response("must initialize first", { status: 400 }),
+ );
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({
+ ok: false,
+ kind: "http_error",
+ status: 400,
+ body: "must initialize first",
+ });
+ });
+
+ it("HTTP error with a blank body reports body: undefined", async () => {
+ fetchMock.mockResolvedValueOnce(new Response(" ", { status: 503 }));
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({ ok: false, kind: "http_error", status: 503, body: undefined });
+ });
+
+ it("HTTP error where the body read throws still reports the status", async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: false,
+ status: 502,
+ text: () => Promise.reject(new Error("read failed")),
+ });
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({ ok: false, kind: "http_error", status: 502, body: undefined });
+ });
+
+ it("maps a JSON-RPC error envelope to rpc_error", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({ jsonrpc: "2.0", id: 1, error: { code: -32601, message: "no such method" } }),
+ { status: 200 },
+ ),
+ );
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({ ok: false, kind: "rpc_error", code: -32601, message: "no such method" });
+ });
+
+ it("flags malformed bodies: empty, unparseable, and result-less envelopes", async () => {
+ fetchMock.mockResolvedValueOnce(new Response("", { status: 200 }));
+ expect(await mcpRpc("https://x", "t", "m")).toMatchObject({
+ ok: false,
+ kind: "malformed_response",
+ message: "empty body",
+ });
+
+ fetchMock.mockResolvedValueOnce(new Response("{nope", { status: 200 }));
+ expect(await mcpRpc("https://x", "t", "m")).toMatchObject({
+ ok: false,
+ kind: "malformed_response",
+ });
+
+ fetchMock.mockResolvedValueOnce(new Response('{"jsonrpc":"2.0","id":1}', { status: 200 }));
+ expect(await mcpRpc("https://x", "t", "m")).toMatchObject({
+ ok: false,
+ kind: "malformed_response",
+ message: "envelope has neither result nor error",
+ });
+ });
+
+ it("maps fetch rejection to network_error", async () => {
+ fetchMock.mockRejectedValueOnce(new Error("ECONNREFUSED"));
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({ ok: false, kind: "network_error", message: "ECONNREFUSED" });
+ });
+
+ it("maps a body read failure on a 200 to network_error", async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ text: () => Promise.reject(new Error("stream reset")),
+ });
+ const r = await mcpRpc("https://x", "t", "m");
+ expect(r).toEqual({ ok: false, kind: "network_error", message: "stream reset" });
+ });
+
+ it("returns timeout when the deadline fires before the response", async () => {
+ fetchMock.mockImplementationOnce(
+ (_url: string, init: RequestInit) =>
+ new Promise((_, reject) => {
+ (init.signal as AbortSignal).addEventListener("abort", () =>
+ reject(new DOMException("The operation was aborted.", "AbortError")),
+ );
+ }),
+ );
+ const r = await mcpRpc("https://x", "t", "m", {}, { timeoutMs: 10 });
+ expect(r).toEqual({ ok: false, kind: "timeout" });
+ });
+
+ it("returns aborted when the caller's signal fires", async () => {
+ const controller = new AbortController();
+ fetchMock.mockImplementationOnce(
+ (_url: string, init: RequestInit) =>
+ new Promise((_, reject) => {
+ (init.signal as AbortSignal).addEventListener("abort", () =>
+ reject(new DOMException("The operation was aborted.", "AbortError")),
+ );
+ }),
+ );
+ const pending = mcpRpc("https://x", "t", "m", {}, { signal: controller.signal });
+ controller.abort();
+ expect(await pending).toEqual({ ok: false, kind: "aborted" });
+ });
+
+ it("returns aborted when the caller's signal is already aborted", async () => {
+ const controller = new AbortController();
+ controller.abort();
+ fetchMock.mockImplementationOnce((_url: string, init: RequestInit) => {
+ const signal = init.signal as AbortSignal;
+ return signal.aborted
+ ? Promise.reject(new DOMException("The operation was aborted.", "AbortError"))
+ : Promise.resolve(rpcSuccess("nope"));
+ });
+ const r = await mcpRpc("https://x", "t", "m", {}, { signal: controller.signal });
+ expect(r).toEqual({ ok: false, kind: "aborted" });
+ });
+});
+
+describe("mcpRpcAutoRefresh", () => {
+ it("404s on an unknown catalog key", async () => {
+ const r = await mcpRpcAutoRefresh(freshProject(), "no-such-server", "tools/list");
+ expect(r).toEqual({
+ ok: false,
+ kind: "http_error",
+ status: 404,
+ body: "unknown mcp catalog key",
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("401s when no token is stored", async () => {
+ const r = await mcpRpcAutoRefresh(freshProject(), ADS, "tools/list");
+ expect(r).toEqual({ ok: false, kind: "http_error", status: 401, body: "no token stored" });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("uses the stored token when it is not expiring", async () => {
+ const slug = freshProject();
+ storeToken(slug, "stored-tok");
+ fetchMock.mockResolvedValueOnce(rpcSuccess("fine"));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toEqual({ ok: true, result: "fine" });
+ expect(refreshMocks.refreshMcpToken).not.toHaveBeenCalled();
+ const headers = fetchMock.mock.calls[0]![1].headers as Record<string, string>;
+ expect(headers.Authorization).toBe("Bearer stored-tok");
+ expect(fetchMock.mock.calls[0]![0]).toBe(ADS_URL);
+ });
+
+ it("proactively refreshes an expiring token before the call", async () => {
+ const slug = freshProject();
+ const token = storeToken(slug, "stale-tok");
+ refreshMocks.isExpiringSoon.mockReturnValue(true);
+ refreshMocks.refreshMcpToken.mockResolvedValueOnce({
+ ...token,
+ access_token_enc: "fresh-tok",
+ });
+ fetchMock.mockResolvedValueOnce(rpcSuccess("ok"));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toEqual({ ok: true, result: "ok" });
+ expect(refreshMocks.refreshMcpToken).toHaveBeenCalledTimes(1);
+ const headers = fetchMock.mock.calls[0]![1].headers as Record<string, string>;
+ expect(headers.Authorization).toBe("Bearer fresh-tok");
+ });
+
+ it("falls back to the stored token when the proactive refresh fails", async () => {
+ const slug = freshProject();
+ ageToken(storeToken(slug, "stale-tok"));
+ refreshMocks.isExpiringSoon.mockReturnValue(true);
+ refreshMocks.refreshMcpToken.mockResolvedValueOnce(null);
+ fetchMock.mockResolvedValueOnce(rpcSuccess("still ok"));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toEqual({ ok: true, result: "still ok" });
+ const headers = fetchMock.mock.calls[0]![1].headers as Record<string, string>;
+ expect(headers.Authorization).toBe("Bearer stale-tok");
+ });
+
+ it("on 401, refreshes once and retries with the new token", async () => {
+ const slug = freshProject();
+ const token = ageToken(storeToken(slug, "revoked-tok"));
+ refreshMocks.refreshMcpToken.mockResolvedValueOnce({
+ ...token,
+ access_token_enc: "rotated-tok",
+ });
+ fetchMock
+ .mockResolvedValueOnce(new Response("unauthorized", { status: 401 }))
+ .mockResolvedValueOnce(rpcSuccess("recovered"));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toEqual({ ok: true, result: "recovered" });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ const retryHeaders = fetchMock.mock.calls[1]![1].headers as Record<string, string>;
+ expect(retryHeaders.Authorization).toBe("Bearer rotated-tok");
+ });
+
+ it("returns the original 401 when the reactive refresh fails", async () => {
+ const slug = freshProject();
+ ageToken(storeToken(slug));
+ refreshMocks.refreshMcpToken.mockResolvedValueOnce(null);
+ fetchMock.mockResolvedValueOnce(new Response("unauthorized", { status: 401 }));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toMatchObject({ ok: false, kind: "http_error", status: 401 });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("skips the reactive refresh when the token was refreshed within this call", async () => {
+ const slug = freshProject();
+ // Freshly upserted row → updated_at is now, inside the 5s skip window.
+ storeToken(slug);
+ fetchMock.mockResolvedValueOnce(new Response("unauthorized", { status: 401 }));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toMatchObject({ ok: false, kind: "http_error", status: 401 });
+ expect(refreshMocks.refreshMcpToken).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("passes through non-401 failures without refreshing", async () => {
+ const slug = freshProject();
+ ageToken(storeToken(slug));
+ fetchMock.mockRejectedValueOnce(new Error("down"));
+
+ const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");
+ expect(r).toEqual({ ok: false, kind: "network_error", message: "down" });
+ expect(refreshMocks.refreshMcpToken).not.toHaveBeenCalled();
+ });
+});
diff --git a/notfair/src/server/mcp/tokens.test.ts b/notfair/src/server/mcp/tokens.test.ts
new file mode 100644
index 00000000..c8737a77
--- /dev/null
+++ b/notfair/src/server/mcp/tokens.test.ts
@@ -0,0 +1,213 @@
+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-tokens-"));
+});
+
+import { getDb } from "@/server/db/db";
+import {
+ deleteMcpToken,
+ deleteProjectMcpTokens,
+ findMcpToken,
+ getMcpToken,
+ listProjectMcpTokens,
+ updateMcpTokenSecrets,
+ upsertMcpToken,
+} from "./tokens";
+
+// mcp_tokens.project_slug FKs to projects(slug); seed the parent rows the
+// cases reference before any upsert runs.
+beforeAll(() => {
+ const db = getDb();
+ const insert = db.prepare(
+ "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",
+ );
+ for (const slug of [
+ "proj-a", "proj-b", "proj-c", "proj-d", "proj-e",
+ "proj-f", "proj-g", "proj-h", "proj-i",
+ ]) {
+ insert.run(slug, slug, slug, new Date().toISOString());
+ }
+});
+
+describe("upsertMcpToken", () => {
+ it("inserts a new row with defaults applied", () => {
+ const token = upsertMcpToken({
+ project_slug: "proj-a",
+ server_name: "notfair-googleads",
+ access_token: "at-1",
+ });
+ expect(token.id).toBeTruthy();
+ expect(token.account_label).toBe("");
+ expect(token.access_token_enc).toBe("at-1");
+ expect(token.refresh_token_enc).toBeNull();
+ expect(token.expires_at).toBeNull();
+ expect(token.scope).toBeNull();
+ expect(token.metadata_json).toBeNull();
+ expect(token.token_endpoint).toBeNull();
+ expect(token.client_id).toBeNull();
+ expect(token.client_secret).toBeNull();
+
+ // Round-trips through the DB identically.
+ expect(getMcpToken(token.id)).toEqual(token);
+ });
+
+ it("updates in place on (project_slug, server_name, account_label) collision", () => {
+ const first = upsertMcpToken({
+ project_slug: "proj-b",
+ server_name: "notfair-metaads",
+ access_token: "old",
+ refresh_token: "old-rt",
+ });
+ const second = upsertMcpToken({
+ project_slug: "proj-b",
+ server_name: "notfair-metaads",
+ access_token: "new",
+ expires_at: "2027-01-01T00:00:00.000Z",
+ scope: "ads.read",
+ metadata: { account: "123" },
+ token_endpoint: "https://oauth.example.com/token",
+ client_id: "cid",
+ client_secret: "csec",
+ });
+ expect(second.id).toBe(first.id);
+ expect(second.access_token_enc).toBe("new");
+ // Update overwrites every secret column — omitted refresh_token becomes null.
+ expect(second.refresh_token_enc).toBeNull();
+ expect(second.expires_at).toBe("2027-01-01T00:00:00.000Z");
+ expect(second.scope).toBe("ads.read");
+ expect(second.metadata_json).toBe(JSON.stringify({ account: "123" }));
+ expect(second.token_endpoint).toBe("https://oauth.example.com/token");
+ expect(second.client_id).toBe("cid");
+ expect(second.client_secret).toBe("csec");
+ expect(listProjectMcpTokens("proj-b")).toHaveLength(1);
+ });
+
+ it("treats different account_labels as distinct rows", () => {
+ upsertMcpToken({
+ project_slug: "proj-c",
+ server_name: "notfair-googleads",
+ account_label: "acct-1",
+ access_token: "a",
+ });
+ upsertMcpToken({
+ project_slug: "proj-c",
+ server_name: "notfair-googleads",
+ account_label: "acct-2",
+ access_token: "b",
+ });
+ expect(listProjectMcpTokens("proj-c")).toHaveLength(2);
+ });
+});
+
+describe("updateMcpTokenSecrets", () => {
+ it("rotates the access token and keeps the refresh token via COALESCE", () => {
+ const token = upsertMcpToken({
+ project_slug: "proj-d",
+ server_name: "srv",
+ access_token: "at",
+ refresh_token: "rt-keep",
+ expires_at: "2026-01-01T00:00:00.000Z",
+ });
+ const updated = updateMcpTokenSecrets(token.id, {
+ access_token: "at-2",
+ refresh_token: null,
+ expires_at: "2026-02-01T00:00:00.000Z",
+ });
+ expect(updated).not.toBeNull();
+ expect(updated!.access_token_enc).toBe("at-2");
+ expect(updated!.refresh_token_enc).toBe("rt-keep");
+ expect(updated!.expires_at).toBe("2026-02-01T00:00:00.000Z");
+ });
+
+ it("replaces the refresh token when the provider rotates it", () => {
+ const token = upsertMcpToken({
+ project_slug: "proj-d",
+ server_name: "srv-rotate",
+ access_token: "at",
+ refresh_token: "rt-old",
+ });
+ const updated = updateMcpTokenSecrets(token.id, {
+ access_token: "at-2",
+ refresh_token: "rt-new",
+ });
+ expect(updated!.refresh_token_enc).toBe("rt-new");
+ // Omitted expires_at nulls the column.
+ expect(updated!.expires_at).toBeNull();
+ });
+
+ it("returns null when the row was deleted mid-refresh", () => {
+ expect(
+ updateMcpTokenSecrets("nope", { access_token: "x" }),
+ ).toBeNull();
+ });
+});
+
+describe("lookups and deletes", () => {
+ it("getMcpToken returns null for unknown id", () => {
+ expect(getMcpToken("missing")).toBeNull();
+ });
+
+ it("findMcpToken matches (project, server, label) and defaults label to ''", () => {
+ const token = upsertMcpToken({
+ project_slug: "proj-e",
+ server_name: "srv",
+ access_token: "at",
+ });
+ expect(findMcpToken("proj-e", "srv")).toEqual(token);
+ expect(findMcpToken("proj-e", "srv", "other-label")).toBeNull();
+ expect(findMcpToken("other-proj", "srv")).toBeNull();
+ });
+
+ it("listProjectMcpTokens orders by server_name then account_label", () => {
+ upsertMcpToken({ project_slug: "proj-f", server_name: "zeta", access_token: "1" });
+ upsertMcpToken({
+ project_slug: "proj-f",
+ server_name: "alpha",
+ account_label: "b",
+ access_token: "2",
+ });
+ upsertMcpToken({
+ project_slug: "proj-f",
+ server_name: "alpha",
+ account_label: "a",
+ access_token: "3",
+ });
+ const rows = listProjectMcpTokens("proj-f");
+ expect(rows.map((r) => [r.server_name, r.account_label])).toEqual([
+ ["alpha", "a"],
+ ["alpha", "b"],
+ ["zeta", ""],
+ ]);
+ });
+
+ it("deleteMcpToken removes one row", () => {
+ const token = upsertMcpToken({
+ project_slug: "proj-g",
+ server_name: "srv",
+ access_token: "at",
+ });
+ deleteMcpToken(token.id);
+ expect(getMcpToken(token.id)).toBeNull();
+ });
+
+ it("deleteProjectMcpTokens clears the whole project without touching others", () => {
+ upsertMcpToken({ project_slug: "proj-h", server_name: "one", access_token: "1" });
+ upsertMcpToken({ project_slug: "proj-h", server_name: "two", access_token: "2" });
+ const other = upsertMcpToken({
+ project_slug: "proj-i",
+ server_name: "one",
+ access_token: "3",
+ });
+ deleteProjectMcpTokens("proj-h");
+ expect(listProjectMcpTokens("proj-h")).toEqual([]);
+ expect(getMcpToken(other.id)).toEqual(other);
+ });
+});
diff --git a/notfair/src/server/onboarding/project-brief.test.ts b/notfair/src/server/onboarding/project-brief.test.ts
new file mode 100644
index 00000000..03832283
--- /dev/null
+++ b/notfair/src/server/onboarding/project-brief.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it, vi } from "vitest";
+import { existsSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+// Real fs against a tmpdir data dir, per repo test conventions.
+// MUST be hoisted: static imports evaluate before module-level statements,
+// so a plain assignment would point the suite at the developer's ~/.notfair.
+const h = 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");
+ const dataDir = mkdtempSync(join(tmpdir(), "notfair-brief-"));
+ process.env.NOTFAIR_DATA_DIR = dataDir;
+ return { dataDir };
+});
+
+import {
+ PROJECT_BRIEF_MAX_BYTES,
+ deleteProjectBriefDir,
+ projectBriefDir,
+ projectBriefPath,
+ readProjectBrief,
+ renameProjectBriefDir,
+ writeProjectBrief,
+} from "./project-brief";
+
+describe("project brief paths", () => {
+ it("lives under <data dir>/projects/<slug>/PROJECT.md", () => {
+ expect(projectBriefDir("acme")).toBe(join(h.dataDir, "projects", "acme"));
+ expect(projectBriefPath("acme")).toBe(
+ join(h.dataDir, "projects", "acme", "PROJECT.md"),
+ );
+ });
+
+ it("exposes the documented size cap", () => {
+ expect(PROJECT_BRIEF_MAX_BYTES).toBe(64 * 1024);
+ });
+});
+
+describe("read / write round trip", () => {
+ it("returns null before any brief has been written", async () => {
+ await expect(readProjectBrief("never-written")).resolves.toBeNull();
+ });
+
+ it("writes and reads back the exact body", async () => {
+ await writeProjectBrief("acme", "# Acme\n\nWe sell anvils.\n");
+ await expect(readProjectBrief("acme")).resolves.toBe(
+ "# Acme\n\nWe sell anvils.\n",
+ );
+ });
+
+ it("overwrites idempotently on rewrite", async () => {
+ await writeProjectBrief("acme", "v1");
+ await writeProjectBrief("acme", "v2");
+ await expect(readProjectBrief("acme")).resolves.toBe("v2");
+ });
+
+ it("propagates non-ENOENT fs errors instead of masking them as null", async () => {
+ // Make PROJECT.md a *directory* — readFile then fails with EISDIR,
+ // which must bubble (only ENOENT means "no brief yet").
+ await mkdir(projectBriefPath("dir-not-file"), { recursive: true });
+ await expect(readProjectBrief("dir-not-file")).rejects.toThrow();
+ });
+});
+
+describe("deleteProjectBriefDir", () => {
+ it("removes the canonical dir so a recreated slug starts clean", async () => {
+ await writeProjectBrief("doomed", "secret prior-tenant brief");
+ await deleteProjectBriefDir("doomed");
+ expect(existsSync(projectBriefDir("doomed"))).toBe(false);
+ await expect(readProjectBrief("doomed")).resolves.toBeNull();
+ });
+
+ it("is a no-op when the dir never existed", async () => {
+ await expect(deleteProjectBriefDir("never-existed")).resolves.toBeUndefined();
+ });
+});
+
+describe("renameProjectBriefDir", () => {
+ it("moves the brief to the new slug's dir", async () => {
+ await writeProjectBrief("old-slug", "the brief");
+ await renameProjectBriefDir("old-slug", "new-slug");
+ expect(existsSync(projectBriefDir("old-slug"))).toBe(false);
+ await expect(readProjectBrief("new-slug")).resolves.toBe("the brief");
+ });
+
+ it("no-ops when old and new slug are identical", async () => {
+ await expect(renameProjectBriefDir("same", "same")).resolves.toBeUndefined();
+ });
+
+ it("no-ops when the source dir doesn't exist", async () => {
+ await renameProjectBriefDir("ghost", "ghost-dest");
+ expect(existsSync(projectBriefDir("ghost-dest"))).toBe(false);
+ });
+
+ it("throws on a slug collision with a non-empty destination", async () => {
+ await writeProjectBrief("col-src", "src brief");
+ await writeProjectBrief("col-dst", "dst brief");
+ await expect(renameProjectBriefDir("col-src", "col-dst")).rejects.toThrow();
+ // Neither side was clobbered.
+ await expect(readProjectBrief("col-dst")).resolves.toBe("dst brief");
+ await expect(readProjectBrief("col-src")).resolves.toBe("src brief");
+ });
+
+ it("propagates non-ENOENT stat errors", async () => {
+ // A file where the *parent dir path component* should be a directory
+ // makes stat fail with ENOTDIR, which must bubble.
+ await mkdir(join(h.dataDir, "projects"), { recursive: true });
+ await writeFile(join(h.dataDir, "projects", "plainfile"), "x", "utf8");
+ await expect(
+ renameProjectBriefDir("plainfile/child", "elsewhere"),
+ ).rejects.toThrow();
+ });
+});
diff --git a/notfair/src/server/suggestions/engine.test.ts b/notfair/src/server/suggestions/engine.test.ts
new file mode 100644
index 00000000..fa67ac7c
--- /dev/null
+++ b/notfair/src/server/suggestions/engine.test.ts
@@ -0,0 +1,182 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { SuggestionDraft } from "@/server/db/suggestions";
+
+// Mock at the db-module / analyzer boundary: the engine's own logic is the
+// run-state machine, not the X Ads audit or the SQLite writes.
+const mocks = vi.hoisted(() => ({
+ hasSuggestionsForSource: vi.fn<(slug: string, key: string) => boolean>(),
+ replaceOpenSuggestions: vi.fn(),
+ listLiveGoals: vi.fn<(slug: string) => Array<{ statement: string }>>(() => []),
+ listProjectMcpTokens: vi.fn<(slug: string) => Array<{ server_name: string }>>(
+ () => [],
+ ),
+ auditXadsAccount: vi.fn(),
+ xadsSuggestionsFromSnapshot: vi.fn<() => SuggestionDraft[]>(() => []),
+}));
+
+vi.mock("@/server/db/suggestions", () => ({
+ hasSuggestionsForSource: mocks.hasSuggestionsForSource,
+ replaceOpenSuggestions: mocks.replaceOpenSuggestions,
+}));
+vi.mock("@/server/db/goals", () => ({
+ listLiveGoals: mocks.listLiveGoals,
+}));
+vi.mock("@/server/mcp/tokens", () => ({
+ listProjectMcpTokens: mocks.listProjectMcpTokens,
+}));
+vi.mock("./xads", () => ({
+ XADS_SOURCE_KEY: "notfair-xads",
+ auditXadsAccount: mocks.auditXadsAccount,
+ xadsSuggestionsFromSnapshot: mocks.xadsSuggestionsFromSnapshot,
+}));
+
+import {
+ analyzableSources,
+ anySuggestionRunActive,
+ generateSuggestionsForSource,
+ listSuggestionRuns,
+ maybeAutoGenerate,
+ suggestionSourceLabel,
+} from "./engine";
+
+// The engine keeps per-project run state in module memory for the process
+// lifetime — every test uses a distinct project slug for isolation.
+let seq = 0;
+const freshSlug = () => `proj-${++seq}`;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listLiveGoals.mockReturnValue([]);
+ mocks.listProjectMcpTokens.mockReturnValue([]);
+ mocks.xadsSuggestionsFromSnapshot.mockReturnValue([]);
+});
+
+describe("suggestionSourceLabel", () => {
+ it("labels known analyzers and returns null otherwise", () => {
+ expect(suggestionSourceLabel("notfair-xads")).toBe("X Ads");
+ expect(suggestionSourceLabel("notfair-googleads")).toBeNull();
+ });
+});
+
+describe("generateSuggestionsForSource", () => {
+ it("no-ops for a source without an analyzer", async () => {
+ const slug = freshSlug();
+ await generateSuggestionsForSource(slug, "notfair-googleads");
+ expect(listSuggestionRuns(slug)).toEqual([]);
+ expect(mocks.replaceOpenSuggestions).not.toHaveBeenCalled();
+ });
+
+ it("runs the analyzer, refreshes open suggestions, and records done", async () => {
+ const slug = freshSlug();
+ const drafts = [{ title: "Fix wasted spend" }] as unknown as SuggestionDraft[];
+ mocks.listLiveGoals.mockReturnValue([{ statement: "Grow clicks" }]);
+ mocks.auditXadsAccount.mockResolvedValue({ ok: true });
+ mocks.xadsSuggestionsFromSnapshot.mockReturnValue(drafts);
+
+ await generateSuggestionsForSource(slug, "notfair-xads");
+
+ expect(mocks.auditXadsAccount).toHaveBeenCalledWith(slug);
+ expect(mocks.xadsSuggestionsFromSnapshot).toHaveBeenCalledWith(
+ { ok: true },
+ ["Grow clicks"],
+ );
+ expect(mocks.replaceOpenSuggestions).toHaveBeenCalledWith(
+ slug,
+ "notfair-xads",
+ drafts,
+ );
+ const runs = listSuggestionRuns(slug);
+ expect(runs).toHaveLength(1);
+ expect(runs[0]).toMatchObject({
+ source_key: "notfair-xads",
+ label: "X Ads",
+ status: "done",
+ });
+ expect(runs[0]!.finished_at).toBeTypeOf("number");
+ expect(anySuggestionRunActive(slug)).toBe(false);
+ });
+
+ it("records a failed run with the error message instead of throwing", async () => {
+ const slug = freshSlug();
+ const consoleError = vi
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+ mocks.auditXadsAccount.mockRejectedValue(new Error("bearer expired"));
+
+ await generateSuggestionsForSource(slug, "notfair-xads");
+
+ expect(listSuggestionRuns(slug)[0]).toMatchObject({
+ status: "failed",
+ error: "bearer expired",
+ });
+ expect(mocks.replaceOpenSuggestions).not.toHaveBeenCalled();
+ consoleError.mockRestore();
+ });
+
+ it("ignores a second trigger while a run is live", async () => {
+ const slug = freshSlug();
+ let finish!: (v: unknown) => void;
+ mocks.auditXadsAccount.mockReturnValue(new Promise((r) => (finish = r)));
+
+ const first = generateSuggestionsForSource(slug, "notfair-xads");
+ expect(anySuggestionRunActive(slug)).toBe(true);
+
+ // Re-trigger mid-flight: must not start a second audit.
+ await generateSuggestionsForSource(slug, "notfair-xads");
+ expect(mocks.auditXadsAccount).toHaveBeenCalledTimes(1);
+
+ finish({});
+ await first;
+ expect(listSuggestionRuns(slug)[0]!.status).toBe("done");
+ });
+});
+
+describe("analyzableSources", () => {
+ it("keeps only connected sources that have an analyzer", () => {
+ const slug = freshSlug();
+ mocks.listProjectMcpTokens.mockReturnValue([
+ { server_name: "notfair-xads" },
+ { server_name: "notfair-googleads" },
+ ]);
+ expect(analyzableSources(slug)).toEqual(["notfair-xads"]);
+ });
+});
+
+describe("maybeAutoGenerate", () => {
+ it("kicks off analysis for a connected source with no prior suggestions", async () => {
+ const slug = freshSlug();
+ mocks.listProjectMcpTokens.mockReturnValue([{ server_name: "notfair-xads" }]);
+ mocks.hasSuggestionsForSource.mockReturnValue(false);
+ mocks.auditXadsAccount.mockResolvedValue({});
+
+ maybeAutoGenerate(slug);
+ // Fire-and-forget: wait for the promise chain to settle.
+ await vi.waitFor(() =>
+ expect(listSuggestionRuns(slug)[0]?.status).toBe("done"),
+ );
+ expect(mocks.auditXadsAccount).toHaveBeenCalledTimes(1);
+ });
+
+ it("skips sources that already have suggestion rows", () => {
+ const slug = freshSlug();
+ mocks.listProjectMcpTokens.mockReturnValue([{ server_name: "notfair-xads" }]);
+ mocks.hasSuggestionsForSource.mockReturnValue(true);
+
+ maybeAutoGenerate(slug);
+ expect(mocks.auditXadsAccount).not.toHaveBeenCalled();
+ expect(listSuggestionRuns(slug)).toEqual([]);
+ });
+
+ it("skips sources already attempted this process lifetime", async () => {
+ const slug = freshSlug();
+ mocks.listProjectMcpTokens.mockReturnValue([{ server_name: "notfair-xads" }]);
+ mocks.hasSuggestionsForSource.mockReturnValue(false);
+ mocks.auditXadsAccount.mockResolvedValue({});
+
+ await generateSuggestionsForSource(slug, "notfair-xads");
+ mocks.auditXadsAccount.mockClear();
+
+ maybeAutoGenerate(slug);
+ expect(mocks.auditXadsAccount).not.toHaveBeenCalled();
+ });
+});
diff --git a/notfair/vitest.config.ts b/notfair/vitest.config.ts
index e776860a..ba3610a8 100644
--- a/notfair/vitest.config.ts
+++ b/notfair/vitest.config.ts
@@ -18,5 +18,20 @@ export default defineConfig({
// per-file via `// @vitest-environment jsdom` (vitest 4 removed the
// environmentMatchGlobs shorthand).
environment: "node",
+ coverage: {
+ provider: "v8",
+ // The denominator is everything we unit-test by convention. Excluded
+ // per CLAUDE.md: Next.js pages/layouts/route handlers (live smoke
+ // covers those), vendored shadcn primitives, and the boot hook.
+ include: ["src/**/*.{ts,tsx}"],
+ exclude: [
+ "src/app/**",
+ "src/components/ui/**",
+ "src/instrumentation.ts",
+ "src/**/*.test.{ts,tsx}",
+ "src/**/*.d.ts",
+ "src/types.ts",
+ ],
+ },
},
});