Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Prune low-value tests and add the test-audit skill (#693)
Ben Senescu2664da2100fc
diff --git a/.agents/PAPERCUTS.md b/.agents/PAPERCUTS.mdindex 2e361788..a1d94faa 100644--- a/.agents/PAPERCUTS.md+++ b/.agents/PAPERCUTS.md@@ -10,6 +10,7 @@ data, or sensitive paths.## Open+- [ ] `2026-09-24T21:20:00Z` — `claude` — `pnpm format:write` is `prettier . --write`, so passing file paths (`pnpm format:write src/foo.ts`) silently formats the whole repository instead of the named files, which surprises agents working in parallel on one checkout. Use `pnpm exec prettier --write <files>` for targeted runs, or make the script forward arguments.- [ ] `2026-09-23T05:50:00Z` — `claude` — `pnpm install --frozen-lockfile` in `web/` rewrites the tracked `web/pnpm-workspace.yaml`, adding an `allowBuilds` block with `esbuild`/`workerd` set to the placeholder "set this to true or false". This leaves a dirty tree that is easy to commit by accident. Commit explicit `allowBuilds` values for those two packages.- [ ] `2026-09-23T04:52:00Z` — `claude` — `pnpm dev:agents` names the portless host after the git branch, and Linear branch names like `carter/eve-125-keyword-research-city-and-county-volume-not-just-country` make a 64-character DNS label (limit 63), so browsers show `chrome-error` for the `.localhost` URL. Workaround: open `http://127.0.0.1:<port>` from `.logs/dev-server.log`; fix: pass a truncated `--name` to portless in the script.- [ ] `2026-09-22T02:21:38Z` — `codex` — The documented portless `.localhost` development URL produces a Google OAuth `invalid_request` because Google rejects that callback hostname. Document registering `http://localhost:<assigned-port>/api/gsc/oauth/callback` and starting the connection from that direct origin while the server remains managed by portless.diff --git a/.agents/skills/test-audit/SKILL.md b/.agents/skills/test-audit/SKILL.mdnew file mode 100644index 00000000..e5c0f31b--- /dev/null+++ b/.agents/skills/test-audit/SKILL.md@@ -0,0 +1,230 @@+---+name: test-audit+description: "Invoke whenever writing, changing, reviewing, or sweeping Vitest tests in this repo. Authoring gate for new or changed tests, plus an audit workflow for low-value, implementation-coupled, or duplicative tests and the test-only production seams they keep alive. Use when asked to add tests, review tests, clean up tests, or when a PR touches *.test.ts."+metadata:+ internal: true+---++# Test Audit++Three modes, one value bar. **Authoring mode** gates every new or changed test+at write time. **Audit mode** runs focused sweeps for tests that re-assert+source, duplicate stronger proof, couple behavior to implementation, or keep+test-only production seams alive. **Campaign mode** reviews every test file+with a per-test verdict when the maintainer asks to prune the whole suite; see+[Campaign mode](#campaign-mode). Optimize for confidence, not deletion count.+Land one coherent batch per PR; continue broad audits as separate follow-ups.++The repository's own rules live in the "Testing" section of `CLAUDE.md`. This+skill is the procedure for applying them; when the two disagree, `CLAUDE.md`+wins and this file needs an update.++## Authoring gate++Before adding a test, answer four questions. A missing answer means do not add+it yet:++1. What observable behavior, invariant, or independent contract does it protect?+2. What credible regression makes it fail?+3. Why does existing coverage not already catch that failure? Each contract has+ one primary owner at the strongest boundary (usually the service or the MCP+ tool handler, not the repository or a private helper). Another layer needs+ its own distinct risk. Prefer extending a table-driven case or a shared+ factory (`ga4-test-fixtures.ts`, `tool-test-support.ts`) over a+ near-duplicate test, and consolidate duplicated setup in the same change.+4. Does it need a production seam (export, flag, wrapper, injection hook) that+ no production caller needs? If yes, test at the real boundary instead.+ Grep the whole repo for callers, not just `src/`; `scripts/` counts.++Then check the test against every [junk pattern](#junk-patterns); a match fails+the gate unless the [retention bar](#retention-bar) names the contract it+independently guards. A test that would break under behavior-preserving+refactoring is asserting implementation, not behavior; rewrite it at the owning+boundary before landing it.++Bug regression tests must fail on the pre-fix code for the intended reason and+pass after the fix. A regression test that never demonstrably failed proves the+mock, not the fix. One regression at the owner boundary covers the bug; do not+replay it at every layer it crosses.++## Junk patterns++The shared checklist for both modes. The authoring gate rejects a new test that+matches one; audits hunt for existing tests that do.++Repo-specific (each is a `CLAUDE.md` rule):++- per-test `await import()` or `vi.resetModules()` without a comment explaining+ which module-level state must reset;+- a production class re-declared inside a test instead of imported from a leaf+ module (`ga4Errors.ts`, `gscErrors.ts` are the pattern);+- `mockReset` / `mockClear` ceremonies in `beforeEach` (Vitest `clearMocks` is+ already on);+- fixtures longer than the assertions that read them, or inline copies of a+ shape that already has a factory;+- Zod schemas or third-party libraries re-tested through the module under test;+- an output-schema round-trip repeated in every happy path;+- Drizzle builder chains mocked (`select().from().where()` with `vi.fn()`+ chains); repositories are tested through services or real SQL;+- argument forwarding to a mock asserted when the mapping is not the contract+ (billing params and telemetry events are the contract; internal helper+ arguments are not).++General:++- assertion-free coverage probes;+- self-comparisons, and expected values produced by the helper or renderer+ under test;+- copied fixtures, inventories, manifests, or export lists;+- exact source, import, or string greps;+- private predicate or call-shape tests duplicated at real boundaries;+- duplicate invocations of the same contract;+- tests whose only purpose is preserving test-only exports or wrappers;+- dead production code whose only callers are tests;+- mocks that implement the asserted behavior, or one identical mock standing in+ for different APIs;+- negative controls that pass for an unrelated reason, such as a denial from a+ different guard or a rejection the production path never reaches;+- names or fixtures that promise more than the input exercises.++## Value bar++Tests justify their maintenance cost by protecting behavior, a credible+regression, or an independently meaningful contract. In an audit, an existing+test that must change for behavior-preserving source reorganization is suspect,+not automatically deletable; the authoring gate still rejects new ones.++Before judging a candidate, read the complete test and its production owner,+the entry point, callers, callees, sibling implementations, overlapping tests,+and relevant git history. When the test claims dependency-backed behavior+(DataForSEO response shapes, Autumn, Better Auth, Drizzle), inspect the+dependency source or types directly.++## Discovery++Keep discovery read-only and report evidence before editing. For broad scope,+run parallel read-only lanes (Explore subagents work well):++- `src/server/mcp/` and `src/server/mcp/tools/`;+- `src/server/lib/`, `src/server/auth/`, `src/server/billing/`,+ `src/server/workflows/`, `src/serverFunctions/`;+- `src/server/features/`;+- `src/client/`, `src/shared/`, `src/lib/`, `src/types/`, `scripts/`,+ `web/tests/`, plus a cross-cutting grep sweep for the repo-specific patterns+ above.++Prefer a few high-confidence candidates over a large speculative inventory.++## Campaign mode++Use only when the maintainer explicitly asks for a suite-wide prune. Run the+pipeline in two phases with disjoint file slices so agents never edit the same+file:++1. **Review, read-only.** Split every `*.test.ts` into 6-8 slices balanced by+ line count and grouped by directory. One reviewer per slice reads each test+ file and its production owner completely and writes a report with a table+ per file: test name, DELETE / MERGE / KEEP, one-line evidence naming the+ code change that would fail it or the test that already owns it. The+ report also lists test-only production seams (with callers checked in+ `src/`, `scripts/`, `badseo/`, `web/`), test support that becomes unused,+ whole files to delete, and a "risky calls" section. Reviewers do not edit.+2. **Apply, per slice.** One applier per slice re-verifies each DELETE and+ MERGE against the source before acting, keeps anything whose evidence does+ not hold, folds MERGE rows into table-driven siblings, deletes newly unused+ fixtures and mocks, and skips every risky item, listing it back for the+ maintainer. If a deletion's justification cites a test in another slice,+ the applier confirms that test still exists at the end of its run.++Rules that hold throughout a campaign:++- The only permitted non-test edit is removing an `export` keyword from a+ helper whose remaining callers are all tests. Knip fails `ci:check` on the+ orphaned export otherwise. Never remove parameters, delete branches, or+ change behavior in the same change, even when a test looks like the only+ reason the code exists; report those as follow-ups.+- Route modules under `src/routes/` and barrel files keep their exports.+- Use `pnpm exec prettier --write <files>`; `pnpm format:write` ignores+ arguments and formats the whole repository.+- After all slices land, run the full suite in normal order and with two or+ three `--sequence.shuffle.tests --sequence.seed=<n>` runs. Removing reset+ ceremony can surface latent order dependence; fix it by setting the mock's+ default in `beforeEach`, never by restoring the ceremony.++## Retention bar++Keep a test when it independently enforces a public API, MCP tool contract,+Zod boundary schema, config, migration, storage (both SQLite and Postgres),+billing, auth, security, default, prompt-byte, or package contract. Also keep:++- call ordering when order is observable behavior;+- regressions with a credible failure mode;+- source inspection when it is the cheapest independent guard: it fails when+ the contract changes (a user-facing key, byte, or path) and survives an+ identifier-only refactor. The pinned SAM skill roster in `samSkills.test.ts`+ and the unique-index parity check in `src/db/schema-parity.test.ts` are this kind;+- a retained test that fails on the baseline: treat it as a possible product+ bug, reproduce it, and repair the owner rather than deleting it.++Static or slow is not a deletion reason. A test that resembles implementation+may still be the independent contract; prove otherwise before removing it.++## Candidate evidence++Record every field before editing. A missing field means the candidate is not+ready for deletion:++- exact test name and location;+- what failure it can actually detect;+- non-test callers of the covered production or support seam, including+ `scripts/`, `badseo/`, and `web/` (a profiling script is still a caller);+- stronger remaining owner-boundary proof, or why no proof is needed;+- relevant history and the reason the test or seam exists;+- production or test-support deletion unlocked;+- risk and the focused validation command.++## Edit shape++Choose one coherent owner-boundary batch. Delete obsolete test-only exports,+wrappers, and dead production paths instead of preserving aliases (Knip will+flag survivors in `pnpm ci:check`). Move retained regressions to their+canonical owners. Consolidate repeated assertions into one table-driven case.++Prefer net-negative production LOC. Do not add replacement tests that restate+the same implementation, and do not convert uncertain candidates into cleanup+to increase deletion counts.++## Validation++Never edit tests while Vitest is running in the checkout.++1. Run the owner and sibling tests: `pnpm exec vitest run <path-or-filter>`.+2. For a removed source grep or static assertion, run the executable that owns+ the real contract (for example `pnpm sync-plugin-skills` for plugin skill+ drift).+3. `pnpm format:write`, then `pnpm ci:check` (prettier, knip, tsc, oxlint,+ plugin-skill sync). Knip failing on a now-unused export means delete the+ export, not re-add a test.+4. Run the full suite once: `pnpm test`.+5. Inspect `git diff --numstat`; report production/tooling separately from+ tests and test support.++## Landing++Commit, push, or open a PR only when authorized. Use the `merge-ready` skill+for the review and PR flow. If a verified finding exposes a recurring+invariant that `.greptile/` does not capture, use `maintain-greptile-rules`;+do not promote one-off cleanups into permanent rules. Log repository friction+met along the way with `papercuts`.++## Handoff++Report:++- removed low-value categories and the root cause behind them;+- production owner simplifications;+- retained false positives and why they remain valuable;+- focused and full proof actually run, with real output;+- production versus test LOC;+- PR and merge state;+- named follow-ups.diff --git a/.claude/skills/test-audit b/.claude/skills/test-auditnew file mode 120000index 00000000..7fb9bcd8--- /dev/null+++ b/.claude/skills/test-audit@@ -0,0 +1 @@+../../.agents/skills/test-audit\ No newline at end of filediff --git a/CLAUDE.md b/CLAUDE.mdindex 55d7ccca..22ee8d34 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -24,6 +24,9 @@- Fixtures contain only the fields the test asserts on or the types require. Shared shapes get a factory with overrides (see `ga4-test-fixtures.ts`, `tool-test-support.ts`); a fixture longer than its test's assertions is a smell.- One test per invariant. Don't re-test Zod or a library, and don't repeat an output-schema round-trip in every happy path.- Don't mock ORM builder chains. Test repositories through services or real SQL evaluation; chain mocks break on refactors that change no behavior.+- Don't export a function only so a test can reach it. Test through the public entry point (the service object, tool handler, or workflow); Knip fails CI on the orphaned export.+- Vitest's `clearMocks` clears call history only. A `mockResolvedValue` or `mockImplementation` set inside a test survives into the next one, so every persistent default belongs in `beforeEach`.+- A negative test must fail for the reason its name gives. If a different guard rejects first (hosted mode off, missing auth, an earlier validation), the test proves nothing about the behavior it names.## Documentation audiencediff --git a/scripts/serp-location-match.test.ts b/scripts/serp-location-match.test.tsindex 938f47ca..5e8a4c40 100644--- a/scripts/serp-location-match.test.ts+++ b/scripts/serp-location-match.test.ts@@ -32,15 +32,6 @@ const BR: SerpRegistryLocation[] = [];describe("matchSerpLocation", () => {- it("returns the registry row untouched when the name is already canonical", () => {- expect(- matchSerpLocation("Catonsville,Maryland,United States", US, "us"),- ).toEqual({- kind: "exact",- location: US[2],- });- });-it("forgives spacing, case and accents", () => {expect(matchSerpLocation("seattle, washington, united states", US, "us"),@@ -91,11 +82,4 @@ describe("matchSerpLocation", () => {location: { locationName: "Itajai,State of Santa Catarina,Brazil" },});});-- it("offers nearby suggestions when nothing matches", () => {- expect(matchSerpLocation("Catonsville, Delaware", US, "us")).toMatchObject({- kind: "unresolved",- suggestions: [{ locationName: "Catonsville,Maryland,United States" }],- });- });});diff --git a/src/client/components/table/url.test.ts b/src/client/components/table/url.test.tsindex 71e54be7..71b05330 100644--- a/src/client/components/table/url.test.ts+++ b/src/client/components/table/url.test.ts@@ -2,31 +2,15 @@ import { describe, expect, it } from "vitest";import { formatUrlForDisplay, resolveUrlHref } from "./url";describe("table URL helpers", () => {- it("formats URLs without scroll-to-text fragments", () => {+ it("strips scroll-to-text fragments but keeps normal hashes and queries", () => {expect(formatUrlForDisplay("https://example.com/a%20b?q=one#:~:text=needle"),).toBe("https://example.com/a b?q=one");- });-- it("keeps normal hashes and query strings in display labels", () => {expect(formatUrlForDisplay("https://example.com/path?q=1#section")).toBe("https://example.com/path?q=1#section",);});- it("falls back to raw display text for invalid URLs", () => {- expect(formatUrlForDisplay("/relative/path")).toBe("/relative/path");- });-- it("resolves relative URLs against a base domain", () => {- expect(resolveUrlHref("/pricing", "example.com")).toBe(- "https://example.com/pricing",- );- expect(resolveUrlHref("docs", "example.com")).toBe(- "https://example.com/docs",- );- });-it("rejects unsafe absolute URL schemes", () => {expect(resolveUrlHref("javascript:alert(1)", "example.com")).toBeNull();});diff --git a/src/client/features/ai-mcp/agentSetupPrompt.test.ts b/src/client/features/ai-mcp/agentSetupPrompt.test.tsindex 8e229273..3658a3c1 100644--- a/src/client/features/ai-mcp/agentSetupPrompt.test.ts+++ b/src/client/features/ai-mcp/agentSetupPrompt.test.ts@@ -2,21 +2,12 @@ import { describe, expect, it } from "vitest";import { getAgentSetupPrompt } from "./agentSetupPrompt";describe("agent setup prompt", () => {- it("copies the installer body without its internal skill metadata", () => {- const prompt = getAgentSetupPrompt("https://app.openseo.so");- expect(prompt).toContain("Identify this agent and its version");- expect(prompt).not.toContain("I use Codex");- expect(prompt).not.toContain("internal: true");- expect(prompt).toContain("https://openseo.so/docs/codex-plugin");- expect(prompt).toContain("https://openseo.so/docs/skills/setup");- expect(prompt).toContain("whoami and list_projects");- });it("uses the current instance for MCP and API keys while keeping public docs links", () => {const prompt = getAgentSetupPrompt("https://seo.example.com");expect(prompt).toContain("https://seo.example.com/mcp");expect(prompt).toContain("https://seo.example.com/settings");expect(prompt).not.toContain("https://app.openseo.so");expect(prompt).toContain("https://openseo.so/docs/mcp");- expect(prompt).not.toContain("I use Other agent");+ expect(prompt).not.toContain("internal: true");});});diff --git a/src/client/features/backlinks/BacklinksPageStates.test.ts b/src/client/features/backlinks/BacklinksPageStates.test.tsdeleted file mode 100644index 3e6faddb..00000000--- a/src/client/features/backlinks/BacklinksPageStates.test.ts+++ /dev/null@@ -1,19 +0,0 @@-import { createElement } from "react";-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it, vi } from "vitest";-import { BacklinksErrorState } from "./BacklinksPageStates";--describe("BacklinksErrorState", () => {- it("renders a visible retry state", () => {- const markup = renderToStaticMarkup(- createElement(BacklinksErrorState, {- errorMessage: "Could not load backlinks data.",- onRetry: vi.fn(),- }),- );-- expect(markup).toContain("Could not load backlinks");- expect(markup).toContain("Could not load backlinks data.");- expect(markup).toContain("Retry");- });-});diff --git a/src/client/features/backlinks/backlinksFilterTypes.test.ts b/src/client/features/backlinks/backlinksFilterTypes.test.tsindex 04948311..0b82b6f2 100644--- a/src/client/features/backlinks/backlinksFilterTypes.test.ts+++ b/src/client/features/backlinks/backlinksFilterTypes.test.ts@@ -10,7 +10,6 @@ it("preserves seven saved conditions and offers recovery before a filtered reque"choose All links (spammy included) from Best links",);expect(backlinksFilterBudgetError(values, "subdomains", false)).toBeNull();- expect(values.exclude).toBe("a,b,c,d,e,f,g");});it("accounts for subfolder conditions and accepts the exact remaining budget", () => {diff --git a/src/client/features/backlinks/backlinksPageUtils.test.ts b/src/client/features/backlinks/backlinksPageUtils.test.tsindex 74cc855f..cf7df568 100644--- a/src/client/features/backlinks/backlinksPageUtils.test.ts+++ b/src/client/features/backlinks/backlinksPageUtils.test.ts@@ -2,13 +2,6 @@ import { describe, expect, it } from "vitest";import { truncateMiddle } from "./backlinksPageUtils";describe("truncateMiddle", () => {- it("returns the value unchanged when it already fits", () => {- expect(truncateMiddle("short", 10)).toBe("short");- expect(truncateMiddle("exactly-ten", "exactly-ten".length)).toBe(- "exactly-ten",- );- });-it("never returns a string longer than maxLength", () => {const value = "/very/long/path/segment/that/keeps/going/here";for (let maxLength = 0; maxLength <= value.length; maxLength++) {@@ -24,10 +17,4 @@ describe("truncateMiddle", () => {"/ver...here",);});-- it("head-truncates when there is no room for both sides", () => {- expect(truncateMiddle("abcdefgh", 4)).toBe("a...");- expect(truncateMiddle("abcdefgh", 3)).toBe("abc");- expect(truncateMiddle("abcdefgh", 2)).toBe("ab");- });});diff --git a/src/client/features/backlinks/export.test.ts b/src/client/features/backlinks/export.test.tsindex c5ba8692..47ee8915 100644--- a/src/client/features/backlinks/export.test.ts+++ b/src/client/features/backlinks/export.test.ts@@ -146,29 +146,4 @@ describe("buildBacklinksTabExport", () => {);expect(content).toContain('"https://docs.example.com/start"');});-- it("sanitizes formula-like cell values to prevent CSV injection", () => {- const content = buildTabCsv({- tab: "backlinks",- rows: {- backlinks: [- makeBacklinkRow({- domainFrom: "=cmd|' /C calc'!A0",- urlFrom: "+https://evil.example/source",- urlTo: "@https://evil.example/target",- anchor: "\tformula",- relAttributes: [],- linksCount: 1,- }),- ],- referringDomains: [],- topPages: [],- },- });-- expect(content).toContain("\"'=cmd|' /C calc'!A0\"");- expect(content).toContain('"\'+https://evil.example/source"');- expect(content).toContain('"\'@https://evil.example/target"');- expect(content).toContain('"\'\tformula"');- });});diff --git a/src/client/features/billing/BillingFeatureBreakdown.test.ts b/src/client/features/billing/BillingFeatureBreakdown.test.tsindex 297d55fe..6e4d9d0d 100644--- a/src/client/features/billing/BillingFeatureBreakdown.test.ts+++ b/src/client/features/billing/BillingFeatureBreakdown.test.ts@@ -7,7 +7,7 @@ vi.mock("@/serverFunctions/billing", () => ({import { getBillingFeatureBreakdownRows } from "./BillingFeatureBreakdown";describe("getBillingFeatureBreakdownRows", () => {- it("uses explicit creditFeature when present", () => {+ it("prefers an explicit creditFeature (or its raw alias) over the path", () => {const rows = getBillingFeatureBreakdownRows([{value: 250,@@ -16,13 +16,6 @@ describe("getBillingFeatureBreakdownRows", () => {paths: ["v3/serp/google/organic/live/regular"],},},- ]);-- expect(rows).toEqual([{ label: "Rank Tracking", usd: 0.25 }]);- });-- it("supports raw Autumn property aliases", () => {- const rows = getBillingFeatureBreakdownRows([{value: 200,properties: {@@ -32,7 +25,10 @@ describe("getBillingFeatureBreakdownRows", () => {},]);- expect(rows).toEqual([{ label: "Local SEO", usd: 0.2 }]);+ expect(rows).toEqual([+ { label: "Rank Tracking", usd: 0.25 },+ { label: "Local SEO", usd: 0.2 },+ ]);});it("infers legacy events from DataForSEO paths", () => {@@ -84,15 +80,4 @@ describe("getBillingFeatureBreakdownRows", () => {expect(rows).toEqual([{ label: "AI Prompt Responses", usd: 0.5 }]);});-- it("falls back to Other when neither feature nor path is available", () => {- const rows = getBillingFeatureBreakdownRows([- {- value: 100,- properties: {},- },- ]);-- expect(rows).toEqual([{ label: "Other", usd: 0.1 }]);- });});diff --git a/src/client/features/billing/HostedBillingContentUtils.test.ts b/src/client/features/billing/HostedBillingContentUtils.test.tsindex cce44ff8..64e088b2 100644--- a/src/client/features/billing/HostedBillingContentUtils.test.ts+++ b/src/client/features/billing/HostedBillingContentUtils.test.ts@@ -2,21 +2,13 @@ import { describe, expect, it } from "vitest";import { parseTopUpAmount } from "./HostedBillingContentUtils";describe("parseTopUpAmount", () => {- it("accepts valid whole-dollar amounts", () => {- expect(parseTopUpAmount("20")).toEqual({ isValid: true, parsed: 20 });- expect(parseTopUpAmount("10")).toEqual({ isValid: true, parsed: 10 });- expect(parseTopUpAmount("99")).toEqual({ isValid: true, parsed: 99 });- });-- it("rejects amounts below minimum", () => {- expect(parseTopUpAmount("9")).toEqual({ isValid: false, parsed: 20 });- });-- it("rejects amounts above maximum", () => {- expect(parseTopUpAmount("100")).toEqual({ isValid: false, parsed: 20 });- });-- it("rejects non-numeric input", () => {- expect(parseTopUpAmount("abc")).toEqual({ isValid: false, parsed: 20 });+ it.each([+ ["10", { isValid: true, parsed: 10 }],+ ["99", { isValid: true, parsed: 99 }],+ ["9", { isValid: false, parsed: 20 }],+ ["100", { isValid: false, parsed: 20 }],+ ["abc", { isValid: false, parsed: 20 }],+ ])("parses %s", (input, expected) => {+ expect(parseTopUpAmount(input)).toEqual(expected);});});diff --git a/src/client/features/billing/plan-detection.test.ts b/src/client/features/billing/plan-detection.test.tsindex b50ae338..db1999f1 100644--- a/src/client/features/billing/plan-detection.test.ts+++ b/src/client/features/billing/plan-detection.test.ts@@ -1,18 +1,11 @@import { describe, expect, it } from "vitest";import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";-import {- getCustomerPaidPlan,- getCustomerPaidPlanId,- getCustomerPlanStatus,-} from "./plan-detection";+import { getCustomerPaidPlan, getCustomerPlanStatus } from "./plan-detection";describe("getCustomerPlanStatus", () => {- it("treats a customer without the paid entitlement as free", () => {+ it("treats any plan granting the paid entitlement as paid, everything else as free", () => {expect(getCustomerPlanStatus(undefined)).toBe("free");expect(getCustomerPlanStatus({ flags: {} })).toBe("free");- });-- it("treats any plan granting the paid entitlement as paid", () => {expect(getCustomerPlanStatus({flags: {@@ -25,17 +18,6 @@ describe("getCustomerPlanStatus", () => {});});-describe("getCustomerPaidPlanId", () => {- it("returns the plan that granted the paid entitlement", () => {- expect(- getCustomerPaidPlanId({- flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "yc-plan" } },- }),- ).toBe("yc-plan");- expect(getCustomerPaidPlanId({ flags: {} })).toBeNull();- });-});-describe("getCustomerPaidPlan", () => {it("reads the name from the expanded subscription and credits from balances", () => {expect(@@ -46,12 +28,4 @@ describe("getCustomerPaidPlan", () => {}),).toEqual({ id: "yc-plan", name: "YC Plan", monthlyCreditsUsd: 50 });});-- it("falls back to the plan ID when the plan is not expanded", () => {- expect(- getCustomerPaidPlan({- flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "yc-plan" } },- })?.name,- ).toBe("yc-plan");- });});diff --git a/src/client/features/billing/route-state.test.ts b/src/client/features/billing/route-state.test.tsindex 0bd9a6aa..675821b5 100644--- a/src/client/features/billing/route-state.test.ts+++ b/src/client/features/billing/route-state.test.ts@@ -1,49 +1,5 @@import { describe, expect, it } from "vitest";-import { getBillingRouteState, getSubscribeRouteState } from "./route-state";--describe("getBillingRouteState", () => {- it("shows ready after successful customer lookup", () => {- expect(- getBillingRouteState({- hasSession: true,- isSessionPending: false,- isCustomerLoading: false,- isCustomerError: false,- }),- ).toBe("ready");- });-- it("shows an error state on billing lookup failures", () => {- expect(- getBillingRouteState({- hasSession: true,- isSessionPending: false,- isCustomerLoading: false,- isCustomerError: true,- }),- ).toBe("error");- });-- it("keeps the page blank while auth or billing data is still loading", () => {- expect(- getBillingRouteState({- hasSession: true,- isSessionPending: true,- isCustomerLoading: false,- isCustomerError: false,- }),- ).toBe("loading");-- expect(- getBillingRouteState({- hasSession: true,- isSessionPending: false,- isCustomerLoading: true,- isCustomerError: false,- }),- ).toBe("loading");- });-});+import { getSubscribeRouteState } from "./route-state";describe("getSubscribeRouteState", () => {// hasManagedAccess is true for essentially every hosted customer: the free@@ -59,32 +15,20 @@ describe("getSubscribeRouteState", () => {finalizingTimedOut: false,};- it("shows an error state on billing lookup failures", () => {- expect(getSubscribeRouteState({ ...base, isCustomerError: true })).toBe(- "error",- );- });-- it("keeps the page blank while billing data is still loading", () => {- expect(getSubscribeRouteState({ ...base, isCustomerLoading: true })).toBe(- "loading",- );- });-it("redirects paying customers into the app", () => {expect(getSubscribeRouteState({ ...base, planStatus: "paid" })).toBe("redirectToApp",);});- it("redirects free-plan users into the app outside the upgrade flow", () => {+ it("redirects free-plan users with managed access into the app unless they asked to upgrade", () => {expect(getSubscribeRouteState(base)).toBe("redirectToApp");- });-- it("shows the paywall to free-plan users in the upgrade flow", () => {expect(getSubscribeRouteState({ ...base, isUpgradeFlow: true })).toBe("showPaywall",);+ expect(getSubscribeRouteState({ ...base, hasManagedAccess: false })).toBe(+ "showPaywall",+ );});it("finalizes after checkout even though managed access would redirect", () => {@@ -114,10 +58,4 @@ describe("getSubscribeRouteState", () => {}),).toBe("redirectToApp");});-- it("shows the paywall to users without managed access", () => {- expect(getSubscribeRouteState({ ...base, hasManagedAccess: false })).toBe(- "showPaywall",- );- });});diff --git a/src/client/features/dashboard/DashboardOnboarding.test.ts b/src/client/features/dashboard/DashboardOnboarding.test.tsindex 50dc19c7..e2486a2b 100644--- a/src/client/features/dashboard/DashboardOnboarding.test.ts+++ b/src/client/features/dashboard/DashboardOnboarding.test.ts@@ -40,12 +40,6 @@ function renderChecklist(activation = fresh) {}describe("dashboard onboarding visibility", () => {- it("keeps setup actions collapsed on an ordinary dashboard visit", () => {- const markup = renderChecklist();- expect(markup).not.toContain("Connection setup");- expect(markup).toContain('id="setup-competitor" hidden=""');- });-it("renders nothing once every step is completed or skipped", () => {expect(renderChecklist({diff --git a/src/client/features/dashboard/dashboardSteps.test.ts b/src/client/features/dashboard/dashboardSteps.test.tsindex 27d21aba..f860291e 100644--- a/src/client/features/dashboard/dashboardSteps.test.ts+++ b/src/client/features/dashboard/dashboardSteps.test.ts@@ -16,19 +16,6 @@ const fresh: DashboardActivation = {};describe("dashboard checklist", () => {- it("leads with research and ends with the multi-project step", () => {- expect(setupSteps.map((step) => step.id)).toEqual([- "competitor",- "keywords",- "audit",- "mcp",- "team",- "project",- ]);- expect(- setupSteps.every((step) => getStepStatus(fresh, step.id) === "todo"),- ).toBe(true);- });it("does not count skipped steps as completed", () => {expect(getStepStatus({ ...fresh, dismissedSteps: ["project"] }, "project"),@@ -55,7 +42,4 @@ describe("dashboard checklist", () => {setupSteps.every((step) => getStepStatus(complete, step.id) === "done"),).toBe(true);});- it("makes no-longer-completed steps available again", () => {- expect(getStepStatus(fresh, "team")).toBe("todo");- });});diff --git a/src/client/features/domain/domainRouteState.test.ts b/src/client/features/domain/domainRouteState.test.tsindex 4e94f575..0026b657 100644--- a/src/client/features/domain/domainRouteState.test.ts+++ b/src/client/features/domain/domainRouteState.test.ts@@ -3,29 +3,18 @@ import { getDomainRouteState } from "./domainRouteState";import { toScopeSearchParam } from "@/shared/researchScope";describe("research scope resolution", () => {- it("derives the scope from the domain input when the URL omits it", () => {- expect(getDomainRouteState({ domain: "example.com" }).scope).toBe(- "subdomains",- );- expect(getDomainRouteState({ domain: "example.com/blog" }).scope).toBe(- "subfolder",- );- });-- it("migrates the legacy subdomains param", () => {- expect(- getDomainRouteState({ domain: "example.com", subdomains: true }).scope,- ).toBe("subdomains");- expect(- getDomainRouteState({ domain: "example.com", subdomains: false }).scope,- ).toBe("domain");- });-- it("ignores a scope the domain input cannot support", () => {- expect(- getDomainRouteState({ domain: "example.com", scope: "subfolder" }).scope,- ).toBe("subdomains");- });+ it.each([+ [{ domain: "example.com" }, "subdomains"],+ [{ domain: "example.com/blog" }, "subfolder"],+ [{ domain: "example.com", subdomains: true }, "subdomains"],+ [{ domain: "example.com", subdomains: false }, "domain"],+ [{ domain: "example.com", scope: "subfolder" as const }, "subdomains"],+ ])(+ "derives the scope from the input, migrating legacy params and ignoring unsupported scopes: %o",+ (search, scope) => {+ expect(getDomainRouteState(search).scope).toBe(scope);+ },+ );it("omits the scope param when it matches the input's default", () => {expect(toScopeSearchParam("example.com", "subdomains")).toBeUndefined();@@ -38,27 +27,27 @@ describe("research scope resolution", () => {});describe("getDomainRouteState", () => {- it("uses a Labs-backed project market when the URL omits loc", () => {- const state = getDomainRouteState(- {},- { locationCode: 2704, languageCode: "vi" },- );-- expect(state.defaultLocationCode).toBe(2704);- expect(state.locationCode).toBe(2704);- expect(state.sentLocationCode).toBeUndefined();- });+ const project = { locationCode: 2704, languageCode: "vi" };- it("keeps an explicit Labs-backed URL location", () => {- const state = getDomainRouteState(+ it.each([+ [+ {},+ {+ defaultLocationCode: 2704,+ locationCode: 2704,+ sentLocationCode: undefined,+ },+ ],+ [{ loc: 2840 },- { locationCode: 2704, languageCode: "vi" },- );-- expect(state.defaultLocationCode).toBe(2704);- expect(state.locationCode).toBe(2840);- expect(state.sentLocationCode).toBe(2840);- });+ { defaultLocationCode: 2704, locationCode: 2840, sentLocationCode: 2840 },+ ],+ ])(+ "uses the Labs-backed project market unless the URL names a location: %o",+ (search, expected) => {+ expect(getDomainRouteState(search, project)).toMatchObject(expected);+ },+ );it("falls back to US for a Google-Ads-only project market", () => {const state = getDomainRouteState(@@ -72,10 +61,7 @@ describe("getDomainRouteState", () => {});it("ignores a Google-Ads-only URL location", () => {- const state = getDomainRouteState(- { loc: 2352 },- { locationCode: 2704, languageCode: "vi" },- );+ const state = getDomainRouteState({ loc: 2352 }, project);expect(state.defaultLocationCode).toBe(2704);expect(state.locationCode).toBe(2704);diff --git a/src/client/features/integrations/googleSetupState.test.ts b/src/client/features/integrations/googleSetupState.test.tsindex a2fceb3f..3f0d48ef 100644--- a/src/client/features/integrations/googleSetupState.test.ts+++ b/src/client/features/integrations/googleSetupState.test.ts@@ -97,20 +97,6 @@ describe.each(["gsc", "ga4", "onboarding"] as const)(expect(html).toContain("Select a property");expect(html).not.toContain("Connect with Google");});- it("offers authorization when no account has been linked", () => {- const html = renderSetup(surface, false);- expect(html).not.toContain("Select a property");- expect(html).toContain(- surface === "onboarding" ? "Connect with Google" : "Connect",- );- });- it("shows the saved connection rather than reopening setup", () => {- const html = renderSetup(surface, true, true);- expect(html).not.toContain("Select a property");- expect(html).toContain(- surface === "ga4" ? "Example" : "https://example.com/",- );- });},);@@ -147,27 +133,4 @@ describe("onboarding connection actions", () => {expect(html).not.toContain("Choose property");expect(html).toMatch(/disabled="">Save and continue<\/button>/);});-- it("requires saving a property or explicitly skipping before advancing", () => {- const html = renderSetup("onboarding", true);- expect(html).toContain("Save and continue");- expect(html).toContain("Skip for now");- expect(html).not.toMatch(/>Continue[ <]/);- expect(html).not.toContain("Save property");- });-- it("offers an explicit skip before Google authorization", () => {- const html = renderSetup("onboarding", false);- expect(html).toContain("Skip for now");- expect(html).not.toMatch(/>Continue[ <]/);- expect(html).toContain("Save and continue");- expect(html).toMatch(/disabled="">Save and continue<\/button>/);- });-- it("allows continuing without another save for an existing connection", () => {- const html = renderSetup("onboarding", true, true);- expect(html).toMatch(/>Continue[ <]/);- expect(html).not.toContain("Save and continue");- expect(html).not.toContain("Skip for now");- });});diff --git a/src/client/features/keywords/hooks/useKeywordFiltering.test.ts b/src/client/features/keywords/hooks/useKeywordFiltering.test.tsindex 9fb6973c..1117be1c 100644--- a/src/client/features/keywords/hooks/useKeywordFiltering.test.ts+++ b/src/client/features/keywords/hooks/useKeywordFiltering.test.ts@@ -41,33 +41,15 @@ const rows: KeywordResearchRow[] = [makeRow("mystery term", "unknown"),];-describe("parseIntentFilter", () => {- it("returns an empty list for an empty string", () => {- expect(parseIntentFilter("")).toEqual([]);- });-- it("parses a comma-separated string in canonical order", () => {+describe("toggleIntentFilter", () => {+ it("adds and removes intents while keeping canonical order", () => {expect(parseIntentFilter("transactional,informational")).toEqual(["informational","transactional",]);- });-- it("drops unknown tokens and de-duplicates", () => {- expect(parseIntentFilter("commercial,bogus,commercial")).toEqual([- "commercial",- ]);- });-});--describe("toggleIntentFilter", () => {- it("adds an intent when absent and keeps canonical order", () => {expect(toggleIntentFilter("transactional", "informational")).toBe("informational,transactional",);- });-- it("removes an intent when already present", () => {expect(toggleIntentFilter("informational,transactional", "informational"),).toBe("transactional");@@ -75,15 +57,6 @@ describe("toggleIntentFilter", () => {});describe("applyKeywordFiltersAndSort — intent filtering", () => {- it("returns every row when no intent is selected", () => {- expect(filter(rows, { intents: "" })).toHaveLength(rows.length);- });-- it("keeps only rows matching a single selected intent", () => {- const result = filter(rows, { intents: "transactional" });- expect(result.map((r) => r.keyword)).toEqual(["buy running shoes"]);- });-it("keeps rows matching any of multiple selected intents", () => {const result = filter(rows, { intents: "transactional,commercial" });expect(@@ -94,17 +67,10 @@ describe("applyKeywordFiltersAndSort — intent filtering", () => {).toEqual(["best running shoes", "buy running shoes"]);});- it("combines the intent filter with other filters (AND)", () => {- // "running" narrows to the two shoe rows; intent narrows to the commercial one.- const result = filter(rows, {- include: "running",- intents: "commercial",- });- expect(result.map((r) => r.keyword)).toEqual(["best running shoes"]);- });-it("ignores invalid intent tokens (treated as no intent match constraint)", () => {- const result = filter(rows, { intents: "bogus" });- expect(result).toHaveLength(rows.length);+ expect(parseIntentFilter("commercial,bogus,commercial")).toEqual([+ "commercial",+ ]);+ expect(filter(rows, { intents: "bogus" })).toHaveLength(rows.length);});});diff --git a/src/client/features/keywords/hooks/useKeywordResearchData.test.ts b/src/client/features/keywords/hooks/useKeywordResearchData.test.tsindex bcf6c322..c4a419ea 100644--- a/src/client/features/keywords/hooks/useKeywordResearchData.test.ts+++ b/src/client/features/keywords/hooks/useKeywordResearchData.test.ts@@ -21,41 +21,23 @@ const baseInput = {};describe("buildKeywordResearchRequest", () => {- it("carries an explicitly selected location without a language", () => {- const request = buildKeywordResearchRequest(baseInput);-- expect(request).toMatchObject({ locationCode: 2704, groupKeywords: false });- expect(request).not.toHaveProperty("languageCode");- const grouped = buildKeywordResearchRequest({- ...baseInput,- groupKeywords: true,- });- expect(grouped).toMatchObject({ groupKeywords: true });- expect(buildKeywordResearchQueryKey(grouped)).not.toEqual(- buildKeywordResearchQueryKey(request),- );- });-- it("never serves a national result for a local search", () => {+ it("never serves a national or ungrouped result for a local or grouped search", () => {const national = buildKeywordResearchRequest(baseInput);const local = buildKeywordResearchRequest({...baseInput,locationName: "Hanoi,Hanoi,Vietnam",});+ const grouped = buildKeywordResearchRequest({+ ...baseInput,+ groupKeywords: true,+ });expect(local).toMatchObject({ locationName: "Hanoi,Hanoi,Vietnam" });expect(buildKeywordResearchQueryKey(local)).not.toEqual(buildKeywordResearchQueryKey(national),);- });-- it("leaves the location undefined for the server to resolve", () => {- const request = buildKeywordResearchRequest({- ...baseInput,- locationCode: undefined,- });-- expect(request).toMatchObject({ locationCode: undefined });- expect(request).not.toHaveProperty("languageCode");+ expect(buildKeywordResearchQueryKey(grouped)).not.toEqual(+ buildKeywordResearchQueryKey(national),+ );});});diff --git a/src/client/features/keywords/hooks/useLocalKeywordFilters.test.ts b/src/client/features/keywords/hooks/useLocalKeywordFilters.test.tsindex 2c54e2bc..ed275858 100644--- a/src/client/features/keywords/hooks/useLocalKeywordFilters.test.ts+++ b/src/client/features/keywords/hooks/useLocalKeywordFilters.test.ts@@ -1,5 +1,4 @@import { describe, expect, it } from "vitest";-import { EMPTY_FILTERS } from "@/client/features/keywords/keywordResearchTypes";import { filterValuesSchema } from "./useLocalKeywordFilters";describe("filterValuesSchema — persistence migration", () => {@@ -23,13 +22,4 @@ describe("filterValuesSchema — persistence migration", () => {expect(parsed.include).toBe("shoes");expect(parsed.minVol).toBe("100");});-- it("preserves a stored intents value", () => {- const parsed = filterValuesSchema.parse({- ...EMPTY_FILTERS,- intents: "transactional,commercial",- });-- expect(parsed.intents).toBe("transactional,commercial");- });});diff --git a/src/client/features/onboarding/onboardingModel.test.ts b/src/client/features/onboarding/onboardingModel.test.tsindex 17db9fce..889d2efd 100644--- a/src/client/features/onboarding/onboardingModel.test.ts+++ b/src/client/features/onboarding/onboardingModel.test.ts@@ -14,14 +14,9 @@ const saved = {foundVia: "Google",};+// Persisted analytics values must round-trip unchanged (not become "Other")+// even when the display labels change.describe("historical onboarding values", () => {- it("keeps a previously saved Google source recognized", () => {- const answers = restoreOnboardingAnswers({ ...saved, foundVia: "Google" });- expect(answers.source).toBe("Google");- expect(answers.sourceOther).toBe("");- expect(buildOnboardingPayload(answers, 4).foundVia).toBe("Google");- });-it.each(["My own startup or business", "My employer's website"])("restores and saves the original work-for value: %s",(workFor) => {@@ -32,13 +27,15 @@ describe("historical onboarding values", () => {},);- it("keeps the original AI workflow value when restoring and saving", () => {+ it("keeps the original source and AI workflow values", () => {const interestedFeatures = ["AI workflows with Claude or Codex (MCP)"];const answers = restoreOnboardingAnswers({ ...saved, interestedFeatures });+ expect(answers.source).toBe("Google");+ expect(answers.sourceOther).toBe("");expect(answers.selectedInterests).toEqual(interestedFeatures);expect(answers.interestOther).toBe("");- expect(buildOnboardingPayload(answers, 4).interestedFeatures).toEqual(- interestedFeatures,- );+ const payload = buildOnboardingPayload(answers, 4);+ expect(payload.foundVia).toBe("Google");+ expect(payload.interestedFeatures).toEqual(interestedFeatures);});});diff --git a/src/client/features/rank-tracking/RankTrackingFilters.logic.ts b/src/client/features/rank-tracking/RankTrackingFilters.logic.tsindex 3bfd2eab..545d7550 100644--- a/src/client/features/rank-tracking/RankTrackingFilters.logic.ts+++ b/src/client/features/rank-tracking/RankTrackingFilters.logic.ts@@ -188,7 +188,7 @@ export function applyFilters(});}-export function matchesPositionFilter(+function matchesPositionFilter(position: number | null,minValue: string,maxValue: string,@@ -204,7 +204,7 @@ export function matchesPositionFilter(return position >= min && position <= max;}-export function matchesMetricRangeFilter(+function matchesMetricRangeFilter(value: number | null,minValue: string,maxValue: string,diff --git a/src/client/features/rank-tracking/RankTrackingFilters.test.ts b/src/client/features/rank-tracking/RankTrackingFilters.test.tsindex 57633403..c0983651 100644--- a/src/client/features/rank-tracking/RankTrackingFilters.test.ts+++ b/src/client/features/rank-tracking/RankTrackingFilters.test.ts@@ -3,23 +3,11 @@ import type { RankTrackingRow } from "@/types/schemas/rank-tracking";import {applyDomainListFilters,applyFilters,- countActiveDomainListFilters,EMPTY_DOMAIN_LIST_FILTERS,EMPTY_FILTERS,- getDomainListFilterOptions,- matchesMetricRangeFilter,- matchesPositionFilter,- type DomainListFilters,type Filters,} from "./RankTrackingFilters";-type DomainSummary = {- id: string;- domain: string;- devices: "both" | "desktop" | "mobile";- locationCode: number;-};-function makeRow(keyword: string,desktopPosition: number | null,@@ -52,39 +40,12 @@ function makeRow(};}-function withFilters(overrides: Partial<Filters>): Filters {- return { ...EMPTY_FILTERS, ...overrides };-}--function makeSummary(- id: string,- domain: string,- devices: DomainSummary["devices"],- locationCode: number,-): DomainSummary {- return { id, domain, devices, locationCode };-}--function withDomainFilters(- overrides: Partial<DomainListFilters>,-): DomainListFilters {- return { ...EMPTY_DOMAIN_LIST_FILTERS, ...overrides };+function keywords(rows: RankTrackingRow[], overrides: Partial<Filters>) {+ return applyFilters(rows, { ...EMPTY_FILTERS, ...overrides }).map(+ (row) => row.keyword,+ );}-describe("matchesPositionFilter", () => {- it("matches only unranked positions when max is zero", () => {- expect(matchesPositionFilter(null, "", "0")).toBe(true);- expect(matchesPositionFilter(1, "", "0")).toBe(false);- expect(matchesPositionFilter(20, "10", "0")).toBe(false);- });-- it("keeps regular rank ranges unchanged", () => {- expect(matchesPositionFilter(4, "1", "10")).toBe(true);- expect(matchesPositionFilter(11, "1", "10")).toBe(false);- expect(matchesPositionFilter(null, "1", "10")).toBe(false);- });-});-describe("applyFilters", () => {const rows = [makeRow("ranked both", 3, 6),@@ -93,152 +54,57 @@ describe("applyFilters", () => {makeRow("unranked both", null, null),];- it("filters desktop unranked rows with desktop max zero", () => {- expect(- applyFilters(rows, withFilters({ maxDesktopPos: "0" })).map(- (row) => row.keyword,- ),- ).toEqual(["desktop unranked", "unranked both"]);- });-- it("filters mobile unranked rows with mobile max zero", () => {- expect(- applyFilters(rows, withFilters({ maxMobilePos: "0" })).map(- (row) => row.keyword,- ),- ).toEqual(["mobile unranked", "unranked both"]);+ it.each([+ [{ maxDesktopPos: "0" }, ["desktop unranked", "unranked both"]],+ [{ maxMobilePos: "0" }, ["mobile unranked", "unranked both"]],+ ])("treats a max position of zero as unranked: %o", (filters, expected) => {+ expect(keywords(rows, filters)).toEqual(expected);});- it("requires both devices to be unranked when both max values are zero", () => {- expect(- applyFilters(- rows,- withFilters({ maxDesktopPos: "0", maxMobilePos: "0" }),- ).map((row) => row.keyword),- ).toEqual(["unranked both"]);+ it("keeps regular rank ranges and excludes unranked rows from them", () => {+ expect(keywords(rows, { minDesktopPos: "1", maxDesktopPos: "10" })).toEqual(+ ["ranked both", "mobile unranked"],+ );});});describe("applyDomainListFilters", () => {- const summaries = [- makeSummary("alpha-us-mobile", "alpha.example.com", "mobile", 2840),- makeSummary("alpha-fr-desktop", "alpha.example.com", "desktop", 2250),- makeSummary("alpha-fr-mobile", "alpha.example.com", "mobile", 2250),- makeSummary("bravo-fr-both", "bravo.example.com", "both", 2250),- makeSummary("charlie-uk-desktop", "charlie.example.com", "desktop", 2826),- ];-- it("narrows by text query and restores all when cleared", () => {- expect(- applyDomainListFilters(- summaries,- withDomainFilters({ query: "ALPHA" }),- ).map((summary) => summary.id),- ).toEqual(["alpha-us-mobile", "alpha-fr-desktop", "alpha-fr-mobile"]);-- expect(- applyDomainListFilters(summaries, EMPTY_DOMAIN_LIST_FILTERS).map(- (summary) => summary.id,- ),- ).toEqual(summaries.map((summary) => summary.id));- });-- it("filters by device", () => {- expect(- applyDomainListFilters(- summaries,- withDomainFilters({ device: "mobile" }),- ).map((summary) => summary.id),- ).toEqual(["alpha-us-mobile", "alpha-fr-mobile"]);- });-- it("filters by country", () => {- expect(- applyDomainListFilters(- summaries,- withDomainFilters({ locationCode: "2250" }),- ).map((summary) => summary.id),- ).toEqual(["alpha-fr-desktop", "alpha-fr-mobile", "bravo-fr-both"]);- });-it("combines domain, device, and country filters with AND semantics", () => {- expect(- applyDomainListFilters(- summaries,- withDomainFilters({- query: "alpha",- device: "mobile",- locationCode: "2250",- }),- ).map((summary) => summary.id),- ).toEqual(["alpha-fr-mobile"]);- });-- it("returns an empty list when filters match nothing", () => {- expect(- applyDomainListFilters(- summaries,- withDomainFilters({ query: "missing", device: "mobile" }),- ),- ).toEqual([]);- });-});--describe("getDomainListFilterOptions", () => {- it("derives distinct device and country options from available summaries", () => {- const options = getDomainListFilterOptions([- makeSummary("a", "a.com", "mobile", 2250),- makeSummary("b", "b.com", "desktop", 2250),- makeSummary("c", "c.com", "mobile", 2826),- ]);-- expect(options.devices).toEqual([- { value: "desktop", label: "Desktop" },- { value: "mobile", label: "Mobile" },- ]);- expect(options.locations).toEqual([- { value: "2250", label: "FR" },- { value: "2826", label: "UK" },- ]);- });-});+ const summaries = [+ {+ id: "alpha-us-mobile",+ domain: "alpha.example.com",+ devices: "mobile" as const,+ locationCode: 2840,+ },+ {+ id: "alpha-fr-desktop",+ domain: "alpha.example.com",+ devices: "desktop" as const,+ locationCode: 2250,+ },+ {+ id: "alpha-fr-mobile",+ domain: "alpha.example.com",+ devices: "mobile" as const,+ locationCode: 2250,+ },+ {+ id: "bravo-fr-both",+ domain: "bravo.example.com",+ devices: "both" as const,+ locationCode: 2250,+ },+ ];-describe("countActiveDomainListFilters", () => {- it("counts non-empty domain list filters", () => {- expect(countActiveDomainListFilters(EMPTY_DOMAIN_LIST_FILTERS)).toBe(0);expect(- countActiveDomainListFilters(- withDomainFilters({- query: "alpha",- device: "desktop",- locationCode: "2840",- }),- ),- ).toBe(3);- });-});--describe("matchesMetricRangeFilter", () => {- it("matches everything when no bounds are set", () => {- expect(matchesMetricRangeFilter(null, "", "")).toBe(true);- expect(matchesMetricRangeFilter(500, "", "")).toBe(true);- });-- it("excludes null values once a bound is set", () => {- expect(matchesMetricRangeFilter(null, "10", "")).toBe(false);- expect(matchesMetricRangeFilter(null, "", "100")).toBe(false);- });-- it("treats zero as a real value, not 'no data'", () => {- expect(matchesMetricRangeFilter(0, "0", "10")).toBe(true);- expect(matchesMetricRangeFilter(0, "1", "10")).toBe(false);- });-- it("respects min-only and max-only bounds", () => {- expect(matchesMetricRangeFilter(50, "20", "")).toBe(true);- expect(matchesMetricRangeFilter(10, "20", "")).toBe(false);- expect(matchesMetricRangeFilter(50, "", "40")).toBe(false);- expect(matchesMetricRangeFilter(50, "", "60")).toBe(true);+ applyDomainListFilters(summaries, {+ ...EMPTY_DOMAIN_LIST_FILTERS,+ query: "alpha",+ device: "mobile",+ locationCode: "2250",+ }).map((summary) => summary.id),+ ).toEqual(["alpha-fr-mobile"]);});});@@ -246,38 +112,19 @@ describe("applyFilters metric ranges", () => {const rows = [makeRow("high volume", 3, 6, { volume: 5000, kd: 40, cpc: 2.5 }),makeRow("low volume", 3, 6, { volume: 10, kd: 80, cpc: 0.1 }),+ makeRow("zero volume", 3, 6, { volume: 0, kd: 0, cpc: 0 }),makeRow("no data", 3, 6, {}),];- it("filters by volume range", () => {- expect(- applyFilters(rows, withFilters({ minVolume: "100" })).map(- (row) => row.keyword,- ),- ).toEqual(["high volume"]);- });-- it("filters by KD range", () => {- expect(- applyFilters(rows, withFilters({ maxKd: "50" })).map(- (row) => row.keyword,- ),- ).toEqual(["high volume"]);- });-- it("filters by CPC range", () => {- expect(- applyFilters(rows, withFilters({ minCpc: "1" })).map(- (row) => row.keyword,- ),- ).toEqual(["high volume"]);- });-- it("excludes rows without metric data once a metric filter is active", () => {- expect(- applyFilters(rows, withFilters({ minVolume: "0" })).map(- (row) => row.keyword,- ),- ).toEqual(["high volume", "low volume"]);+ it("treats zero as a real value but excludes rows without metric data", () => {+ expect(keywords(rows, { minVolume: "0" })).toEqual([+ "high volume",+ "low volume",+ "zero volume",+ ]);+ expect(keywords(rows, { maxKd: "50" })).toEqual([+ "high volume",+ "zero volume",+ ]);});});diff --git a/src/client/features/rank-tracking/tableSelection.test.ts b/src/client/features/rank-tracking/tableSelection.test.tsindex b0def3a9..0a398e97 100644--- a/src/client/features/rank-tracking/tableSelection.test.ts+++ b/src/client/features/rank-tracking/tableSelection.test.ts@@ -46,32 +46,26 @@ function makeTable(ids: string[], selectedIds: Set<string>) {}describe("applyShiftRangeSelection", () => {- it("records the next selected state on a plain click", () => {+ it("selects the visible range from an anchor set by a plain click", () => {const selectedIds = new Set<string>();- const table = makeTable(["a", "b"], selectedIds);+ const table = makeTable(["a", "b", "c", "d"], selectedIds);const anchorRef: MutableRefObject<SelectionAnchor | null> = {current: null,};- const event = makeEvent(false);+ const plainClick = makeEvent(false);expect(applyShiftRangeSelection(- event,+ plainClick,makeRow("a", selectedIds),table,anchorRef,),).toBe(false);expect(anchorRef.current).toEqual({ id: "a", selected: true });- expect(event.defaultPrevented).toBe(false);- });+ expect(plainClick.defaultPrevented).toBe(false);+ selectedIds.add("a");- it("selects the visible range from a selected anchor", () => {- const selectedIds = new Set<string>(["a"]);- const table = makeTable(["a", "b", "c", "d"], selectedIds);- const anchorRef: MutableRefObject<SelectionAnchor | null> = {- current: { id: "a", selected: true },- };const event = makeEvent(true);expect(diff --git a/src/client/features/search-tabs/useSearchTabs.test.ts b/src/client/features/search-tabs/useSearchTabs.test.tsindex cfbee35a..bc33844c 100644--- a/src/client/features/search-tabs/useSearchTabs.test.ts+++ b/src/client/features/search-tabs/useSearchTabs.test.ts@@ -27,16 +27,6 @@ function searchTab(index: number): SearchTab {}describe("appendTabWithEviction", () => {- it("appends without evicting below the limit", () => {- const tabs = Array.from({ length: 19 }, (_, index) => searchTab(index));-- const next = appendTabWithEviction(tabs, searchTab(19));-- expect(next).toHaveLength(20);- expect(next[0].id).toBe("tab-0");- expect(next[19].id).toBe("tab-19");- });-it("evicts the oldest tab at capacity", () => {const tabs = Array.from({ length: 20 }, (_, index) => searchTab(index));@@ -46,38 +36,12 @@ describe("appendTabWithEviction", () => {expect(next[0].id).toBe("tab-1");expect(next[19].id).toBe("tab-20");});-- it("appends to an empty list", () => {- expect(appendTabWithEviction([], searchTab(0))).toHaveLength(1);- });});describe("parseStoredState", () => {- it("keeps domain tabs persisted without a locationCode (default location)", () => {+ it("migrates domain tabs stored before research scopes or locations", () => {const state = parseStoredState({activeTabId: "tab-1",- tabs: [- persistedTab({- type: "domain",- domain: "example.com",- scope: "subfolder",- }),- ],- });-- expect(state.tabs).toHaveLength(1);- expect(state.activeTabId).toBe("tab-1");- expect(state.tabs[0].input).toEqual({- type: "domain",- domain: "example.com",- scope: "subfolder",- locationCode: undefined,- });- });-- it("migrates domain tabs stored before research scopes", () => {- const state = parseStoredState({- activeTabId: null,tabs: [{...persistedTab({@@ -103,9 +67,18 @@ describe("parseStoredState", () => {}),id: "tab-3",},+ {+ ...persistedTab({+ type: "domain",+ domain: "c.com",+ scope: "subfolder",+ }),+ id: "tab-4",+ },],});+ expect(state.activeTabId).toBe("tab-1");expect(state.tabs.map((tab) => tab.input)).toEqual([{type: "domain",@@ -120,6 +93,12 @@ describe("parseStoredState", () => {locationCode: undefined,},{ type: "backlinks", target: "d.com/page", scope: "exact_url" },+ {+ type: "domain",+ domain: "c.com",+ scope: "subfolder",+ locationCode: undefined,+ },]);});@@ -168,23 +147,6 @@ describe("parseStoredState", () => {expect(state.tabs[0].input).toMatchObject({ groupKeywords: true });});- it("keeps tabs persisted with an explicit locationCode", () => {- const state = parseStoredState({- activeTabId: "tab-1",- tabs: [- persistedTab({- type: "domain",- domain: "example.com",- scope: "domain",- locationCode: 2840,- }),- ],- });-- expect(state.tabs).toHaveLength(1);- expect(state.tabs[0].input).toMatchObject({ locationCode: 2840 });- });-it("keeps the newest tabs when stored state exceeds the limit", () => {const state = parseStoredState({activeTabId: null,diff --git a/src/client/lib/clipboard.test.ts b/src/client/lib/clipboard.test.tsindex 2047dad8..227ec7b2 100644--- a/src/client/lib/clipboard.test.ts+++ b/src/client/lib/clipboard.test.ts@@ -38,33 +38,20 @@ describe("copyTableToClipboard", () => {vi.unstubAllGlobals();});- it("emits TSV with tab/newline separators", async () => {+ it("emits TSV with tab/newline separators and flattens them inside cells", async () => {const { written } = mockClipboard();await copyTableToClipboard(["Keyword", "Volume"],[["seo audit", 1200],- ["site speed", 800],+ ["one\ttwo\nthree", 800],],);expect(written[0].plain).toBe(- "Keyword\tVolume\nseo audit\t1200\nsite speed\t800",+ "Keyword\tVolume\nseo audit\t1200\none two three\t800",);});- it("emits HTML with raw numeric cells (no comma formatting)", async () => {- const { written } = mockClipboard();- await copyTableToClipboard(["Volume"], [[1234]]);- expect(written[0].html).toContain("<td>1234</td>");- });-- it("rounds decimal numbers to at most two places", async () => {- const { written } = mockClipboard();- await copyTableToClipboard(["Traffic"], [[1250.321954]]);- expect(written[0].plain).toBe("Traffic\n1250.32");- expect(written[0].html).toContain("<td>1250.32</td>");- });-it("emits URL cells as HTML links for spreadsheet paste", async () => {const { written } = mockClipboard();await copyTableToClipboard(["URL"], [["https://example.com/tools"]]);@@ -88,24 +75,4 @@ describe("copyTableToClipboard", () => {expect(written[0].html).not.toContain("<script>");expect(written[0].html).toContain("<script>");});-- it("flattens tabs and newlines inside string cells", async () => {- const { written } = mockClipboard();- await copyTableToClipboard(["Body"], [["one\ttwo\nthree"]]);- // Single space replaces both \t and \n so the row stays one line in TSV.- expect(written[0].plain).toBe("Body\none two three");- });-- it("treats null and undefined as empty cells", async () => {- const { written } = mockClipboard();- await copyTableToClipboard(["A", "B"], [[null, undefined]]);- expect(written[0].plain).toBe("A\tB\n\t");- });-- it("throws when the Clipboard API is unavailable", async () => {- vi.stubGlobal("navigator", {});- await expect(copyTableToClipboard(["X"], [["y"]])).rejects.toThrow(- /Clipboard API not available/,- );- });});diff --git a/src/client/lib/csv.test.ts b/src/client/lib/csv.test.tsindex 6b1bf655..94dde889 100644--- a/src/client/lib/csv.test.ts+++ b/src/client/lib/csv.test.ts@@ -13,8 +13,14 @@ describe("buildCsv", () => {});it("keeps formula-injection protection for string cells", () => {- const csv = buildCsv(["Value"], [['=HYPERLINK("evil")']]);+ const csv = buildCsv(+ ["Value"],+ [['=HYPERLINK("evil")'], ["+1"], ["@SUM(A1)"], ["\tformula"]],+ );expect(csv).toContain('"\'=HYPERLINK(""evil"")"');+ expect(csv).toContain('"\'+1"');+ expect(csv).toContain('"\'@SUM(A1)"');+ expect(csv).toContain('"\'\tformula"');});});diff --git a/src/client/lib/error-messages.test.ts b/src/client/lib/error-messages.test.tsindex 6f5b6d4b..e6501095 100644--- a/src/client/lib/error-messages.test.ts+++ b/src/client/lib/error-messages.test.ts@@ -4,32 +4,12 @@ import {getStandardErrorMessage,} from "@/client/lib/error-messages";-describe("getStandardErrorMessage", () => {- it("maps known error codes to standard copy", () => {- expect(getStandardErrorMessage(new Error("PAYMENT_REQUIRED"))).toBe(- "An active hosted subscription is required before you can use OpenSEO.",- );- });-- it("returns custom messages when the error is not a shared code", () => {- expect(- getStandardErrorMessage(- new Error("DataForSEO task missing billing metadata. Response: {...}"),- ),- ).toBe("DataForSEO task missing billing metadata. Response: {...}");- });-});-describe("coded error messages (CODE: detail)", () => {- const coded = new Error(- "AUTH_CONFIG_MISSING: TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",- );-- it("extracts the code from a coded message", () => {- expect(getErrorCode(coded)).toBe("AUTH_CONFIG_MISSING");- });-it("shows the server detail instead of the generic text", () => {+ const coded = new Error(+ "AUTH_CONFIG_MISSING: TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",+ );+ expect(getErrorCode(coded)).toBe("AUTH_CONFIG_MISSING");expect(getStandardErrorMessage(coded)).toBe("TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",);@@ -39,6 +19,9 @@ describe("coded error messages (CODE: detail)", () => {const bare = new Error("AUTH_CONFIG_MISSING");expect(getErrorCode(bare)).toBe("AUTH_CONFIG_MISSING");expect(getStandardErrorMessage(bare)).toContain("not configured");+ expect(getStandardErrorMessage(new Error("PAYMENT_REQUIRED"))).toBe(+ "An active hosted subscription is required before you can use OpenSEO.",+ );});it("does not treat arbitrary colon messages as coded", () => {diff --git a/src/client/lib/posthog-sanitize.test.ts b/src/client/lib/posthog-sanitize.test.tsindex a5c46ea8..cfb4bb36 100644--- a/src/client/lib/posthog-sanitize.test.ts+++ b/src/client/lib/posthog-sanitize.test.ts@@ -5,13 +5,26 @@ import {} from "@/client/lib/posthog-sanitize";const consentUrl =- "https://app.example.test/oauth-consent?response_type=code&client_id=test-client&redirect_uri=https%3A%2F%2Fclient.example%2Fcallback&scope=openid&state=state-secret&code_challenge=pkce-challenge&code_challenge_method=S256&resource=https%3A%2F%2Fapp.example.test%2Fmcp&future_parameter=future-secret";+ "https://app.example.test/oauth-consent?state=state-secret&future_parameter=future-secret";describe("sanitizePostHogUrl", () => {- it("removes the complete query from OAuth consent URLs", () => {+ it("removes the complete query from OAuth consent URLs, including on event and session properties", () => {expect(sanitizePostHogUrl(consentUrl)).toBe("https://app.example.test/oauth-consent",);+ expect(+ sanitizePostHogProperties({+ $current_url: consentUrl,+ $session_entry_url: consentUrl,+ $referrer: consentUrl,+ event_detail: "kept",+ }),+ ).toEqual({+ $current_url: "https://app.example.test/oauth-consent",+ $session_entry_url: "https://app.example.test/oauth-consent",+ $referrer: "https://app.example.test/oauth-consent",+ event_detail: "kept",+ });});it("preserves ordinary query data while removing email", () => {@@ -21,26 +34,4 @@ describe("sanitizePostHogUrl", () => {),).toBe("https://app.example.test/onboarding?step=2");});-- it("leaves malformed URLs unchanged", () => {- expect(sanitizePostHogUrl("not a URL")).toBe("not a URL");- });-});--describe("sanitizePostHogProperties", () => {- it("sanitizes consent URLs on custom events and session properties", () => {- const properties: Record<string, unknown> = {- $current_url: consentUrl,- $session_entry_url: consentUrl,- $referrer: consentUrl,- event_detail: "kept",- };-- expect(sanitizePostHogProperties(properties)).toEqual({- $current_url: "https://app.example.test/oauth-consent",- $session_entry_url: "https://app.example.test/oauth-consent",- $referrer: "https://app.example.test/oauth-consent",- event_detail: "kept",- });- });});diff --git a/src/db/pg/retry.test.ts b/src/db/pg/retry.test.tsindex 5b00c7f4..65f53751 100644--- a/src/db/pg/retry.test.ts+++ b/src/db/pg/retry.test.ts@@ -113,10 +113,4 @@ describe("withQueryRetries", () => {await expect(rows).rejects.toBe(error);expect(unsafe).toHaveBeenCalledTimes(4); // initial + 3 retries});-- it("passes everything except unsafe through to the client", () => {- const { sql } = fakeSql(0, connectionError("unused"));- const wrapped = withQueryRetries(sql);- expect(wrapped.options).toBe(sql.options);- });});diff --git a/src/lib/auth-redirect.test.ts b/src/lib/auth-redirect.test.tsindex 772a5118..798542f0 100644--- a/src/lib/auth-redirect.test.ts+++ b/src/lib/auth-redirect.test.ts@@ -1,11 +1,8 @@import { describe, expect, it } from "vitest";import {getAuthRedirectFromSearch,- getCurrentAuthRedirectFromHref,- getOAuthAuthorizeRedirectFromSearch,getOAuthSignedQuery,getSignInHref,- getVerifyEmailSearch,isDocumentRoute,normalizeAuthRedirect,} from "./auth-redirect";@@ -39,23 +36,15 @@ describe("auth redirect helpers", () => {expect(isDocumentRoute("/sign-in")).toBe(false);});- it("defaults unsafe or missing redirects to the app root", () => {+ it("defaults unsafe or missing redirects to the app root, keeping same-origin paths", () => {expect(normalizeAuthRedirect(undefined)).toBe("/");expect(normalizeAuthRedirect("https://evil.example/app")).toBe("/");expect(normalizeAuthRedirect("//evil.example/app")).toBe("/");- });-- it("keeps same-origin relative redirects", () => {expect(normalizeAuthRedirect("/api/auth/oauth2/authorize?client_id=abc"),).toBe("/api/auth/oauth2/authorize?client_id=abc");});- it("rejects external and protocol-relative redirects", () => {- expect(normalizeAuthRedirect("https://evil.test")).toBe("/");- expect(normalizeAuthRedirect("//evil.test")).toBe("/");- });-it("rejects backslash redirects that URL parsers treat as slashes", () => {expect(normalizeAuthRedirect("/\\evil.test")).toBe("/");expect(normalizeAuthRedirect("/path\\..\\evil")).toBe("/");@@ -68,30 +57,6 @@ describe("auth redirect helpers", () => {);});- it("builds verify-email search params without a root redirect", () => {- expect(getVerifyEmailSearch("[email protected]", "/")).toEqual({- email: "[email protected]",- });- expect(- getVerifyEmailSearch("[email protected]", "/onboarding?step=0"),- ).toEqual({- email: "[email protected]",- redirect: "/onboarding?step=0",- });- });-- it("extracts the current path, query, and hash from hrefs", () => {- expect(- getCurrentAuthRedirectFromHref(- "https://open-seo.test/projects?tab=keywords#top",- ),- ).toBe("/projects?tab=keywords#top");- });-- it("preserves safe internal redirects", () => {- expect(getAuthRedirectFromSearch("", "/app")).toBe("/app");- });-it("extracts Better Auth signed OAuth query parameters through sig", () => {const signedQuery = getOAuthSignedQuery(`${oauthSearch}&ignored_after_sig=true`,@@ -100,23 +65,6 @@ describe("auth redirect helpers", () => {expect(signedQuery).toBe(oauthSearch);});- it("builds an internal OAuth authorize continuation redirect", () => {- const redirect = getOAuthAuthorizeRedirectFromSearch(oauthSearch);-- expect(redirect).toBe(`/api/auth/oauth2/authorize?${oauthSearch}`);- expect(redirect).toContain("client_id=claude-client");- expect(redirect).toContain(- "redirect_uri=https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback",- );- expect(redirect).toContain("scope=offline_access+mcp");- expect(redirect).toContain("state=state-123");- expect(redirect).toContain("code_challenge=challenge-123");- expect(redirect).toContain("code_challenge_method=S256");- expect(redirect).toContain("resource=https%3A%2F%2Fapp.openseo.so%2Fmcp");- expect(redirect).toContain("exp=1778271800");- expect(redirect).toContain("sig=signed-value");- });-it("prefers OAuth continuation over a generic redirect", () => {expect(getAuthRedirectFromSearch(oauthSearch, "/app")).toBe(`/api/auth/oauth2/authorize?${oauthSearch}`,diff --git a/src/lib/auth-redirect.ts b/src/lib/auth-redirect.tsindex f7443e7c..398123ff 100644--- a/src/lib/auth-redirect.ts+++ b/src/lib/auth-redirect.ts@@ -41,7 +41,7 @@ export function getOAuthSignedQuery(search: string | null | undefined) {return signedParams.toString();}-export function getOAuthAuthorizeRedirectFromSearch(+function getOAuthAuthorizeRedirectFromSearch(search: string | null | undefined,) {const signedQuery = getOAuthSignedQuery(search);diff --git a/src/lib/auth-turnstile.test.ts b/src/lib/auth-turnstile.test.tsindex 03acdefd..4a5600a0 100644--- a/src/lib/auth-turnstile.test.ts+++ b/src/lib/auth-turnstile.test.ts@@ -5,16 +5,13 @@ import {} from "@/lib/auth-turnstile";describe("hosted Turnstile auth config", () => {- it("enforces captcha from the hosted server secret even when the runtime site key is absent", () => {+ it("enforces captcha from the hosted server secret alone, and only in hosted mode", () => {expect(getHostedTurnstileSecretKey({AUTH_MODE: "hosted",TURNSTILE_SECRET_KEY: " server-secret ",}),).toBe("server-secret");- });-- it("does not install captcha outside hosted mode", () => {expect(getHostedTurnstileSecretKey({AUTH_MODE: "local_noauth",@@ -23,16 +20,14 @@ describe("hosted Turnstile auth config", () => {).toBeUndefined();});- it("fails hosted config when a runtime site key is configured without a secret", () => {+ it("fails hosted config on a site key without a secret, not on a secret without a site key", () => {expect(hasHostedTurnstileConfig({AUTH_MODE: "hosted",TURNSTILE_SITE_KEY: "site-key",}),).toBe(false);- });-- it("allows hosted config with no runtime site key so build/runtime divergence can still enforce from the secret", () => {+ // Build/runtime divergence: the secret alone still enforces captcha.expect(hasHostedTurnstileConfig({AUTH_MODE: "hosted",diff --git a/src/lib/pr-preview-access.test.ts b/src/lib/pr-preview-access.test.tsindex ade2770a..e4141977 100644--- a/src/lib/pr-preview-access.test.ts+++ b/src/lib/pr-preview-access.test.ts@@ -35,8 +35,6 @@ describe("preview Access verification", () => {{ responses: ["403 "], status: 1, retries: 0 },{ responses: ["404 ", "200 "], status: 1, retries: 1 },{ responses: Array<string>(8).fill("404 "), status: 1, retries: 8 },- { responses: Array<string>(8).fill("503 "), status: 1, retries: 8 },- { responses: Array<string>(8).fill("000 "), status: 1, retries: 8 },])("handles $responses", ({ responses, status, retries }) => {const directory = mkdtempSync(join(tmpdir(), "preview-access-"));try {@@ -70,7 +68,6 @@ ${script}`,if (retries === 8) {expect(result.stdout).toContain("Could not verify");expect(result.stdout).not.toContain("preview is public");- expect(result.stdout).not.toContain("still sits behind");}} finally {rmSync(directory, { recursive: true, force: true });diff --git a/src/lib/selfhost-preflight.test.ts b/src/lib/selfhost-preflight.test.tsindex 8911e0d1..b07724a5 100644--- a/src/lib/selfhost-preflight.test.ts+++ b/src/lib/selfhost-preflight.test.ts@@ -29,35 +29,19 @@ describe("runSelfhostPreflight", () => {);});- it("fails cloudflare_access mode without TEAM_DOMAIN and POLICY_AUD", () => {- const result = runSelfhostPreflight({});+ it.each([+ [{}, ["TEAM_DOMAIN and POLICY_AUD", "AUTH_MODE is unset"]],+ [+ { AUTH_MODE: "hosted", BETTER_AUTH_SECRET: "x".repeat(40) },+ ["BETTER_AUTH_URL", "GOOGLE_CLIENT_ID"],+ ],+ ])("fails %o listing every missing variable", (env, mentions) => {+ const result = runSelfhostPreflight(env);expect(result.failed).toBe(true);- const item = itemFor(result, "AUTH_MODE");- expect(item?.message).toContain("TEAM_DOMAIN and POLICY_AUD");- expect(item?.message).toContain("AUTH_MODE is unset");- });-- it("fails a bare-hostname TEAM_DOMAIN with the https:// fix", () => {- const result = runSelfhostPreflight({- AUTH_MODE: "cloudflare_access",- TEAM_DOMAIN: "your-team.cloudflareaccess.com",- POLICY_AUD: "aud-tag",- });-- expect(result.failed).toBe(true);- expect(itemFor(result, "TEAM_DOMAIN")?.message).toContain("https://");- });-- it("warns on a DataForSEO key that is not base64 login:password", () => {- const result = runSelfhostPreflight({- AUTH_MODE: "local_noauth",- DATAFORSEO_API_KEY: "raw-dashboard-key",- });-- expect(result.failed).toBe(false);- expect(itemFor(result, "DATAFORSEO_API_KEY")?.level).toBe("warn");- expect(itemFor(result, "DATAFORSEO_API_KEY")?.message).toContain("base64");+ const message = itemFor(result, "AUTH_MODE")?.message;+ for (const mention of mentions) expect(message).toContain(mention);+ expect(message).not.toContain("BETTER_AUTH_SECRET,");});it("warns that GSC stays disabled on a short BETTER_AUTH_SECRET", () => {@@ -71,24 +55,4 @@ describe("runSelfhostPreflight", () => {expect(itemFor(result, "Search Console")?.level).toBe("warn");expect(itemFor(result, "Search Console")?.message).toContain("32");});-- it("fails hosted mode listing every missing variable", () => {- const result = runSelfhostPreflight({- AUTH_MODE: "hosted",- BETTER_AUTH_SECRET: "x".repeat(40),- });-- expect(result.failed).toBe(true);- const item = itemFor(result, "AUTH_MODE");- expect(item?.message).toContain("BETTER_AUTH_URL");- expect(item?.message).toContain("GOOGLE_CLIENT_ID");- expect(item?.message).not.toContain("BETTER_AUTH_SECRET,");- });-- it("mentions ALLOWED_HOST when unset", () => {- const result = runSelfhostPreflight({ AUTH_MODE: "local_noauth" });-- expect(itemFor(result, "ALLOWED_HOST")?.level).toBe("info");- expect(itemFor(result, "ALLOWED_HOST")?.message).toContain("reverse proxy");- });});diff --git a/src/middleware/ensure-user/accessTokenErrors.test.ts b/src/middleware/ensure-user/accessTokenErrors.test.tsindex 33dfac67..efd04c34 100644--- a/src/middleware/ensure-user/accessTokenErrors.test.ts+++ b/src/middleware/ensure-user/accessTokenErrors.test.ts@@ -3,32 +3,21 @@ import { describe, expect, it } from "vitest";import { classifyAccessVerificationError } from "./accessTokenErrors";describe("classifyAccessVerificationError", () => {- it("maps audience mismatch to a POLICY_AUD config error", () => {+ it.each([+ ["aud", "POLICY_AUD"],+ ["iss", "TEAM_DOMAIN"],+ ])("maps an %s claim mismatch to a %s config error", (claim, variable) => {const error = classifyAccessVerificationError(new joseErrors.JWTClaimValidationFailed(- 'unexpected "aud" claim value',+ `unexpected "${claim}" claim value`,{},- "aud",+ claim,"check_failed",),);expect(error.code).toBe("AUTH_CONFIG_MISSING");- expect(error.message).toContain("POLICY_AUD");- });-- it("maps issuer mismatch to a TEAM_DOMAIN config error", () => {- const error = classifyAccessVerificationError(- new joseErrors.JWTClaimValidationFailed(- 'unexpected "iss" claim value',- {},- "iss",- "check_failed",- ),- );-- expect(error.code).toBe("AUTH_CONFIG_MISSING");- expect(error.message).toContain("TEAM_DOMAIN");+ expect(error.message).toContain(variable);});it("keeps expired tokens as UNAUTHENTICATED (re-auth fixes them)", () => {@@ -48,21 +37,17 @@ describe("classifyAccessVerificationError", () => {expect(error.message).toContain("TEAM_DOMAIN");});- it("maps network failures fetching the JWKS to a config error", () => {- const error = classifyAccessVerificationError(- new TypeError("fetch failed"),- );-- expect(error.code).toBe("AUTH_CONFIG_MISSING");- });-- it("maps workerd-style plain network errors to a config error", () => {- const error = classifyAccessVerificationError(- new Error("Network connection lost"),- );-- expect(error.code).toBe("AUTH_CONFIG_MISSING");- });+ it.each([+ new TypeError("fetch failed"),+ new Error("Network connection lost"),+ ])(+ "maps non-jose network failures fetching the JWKS to a config error: %s",+ (cause) => {+ expect(classifyAccessVerificationError(cause).code).toBe(+ "AUTH_CONFIG_MISSING",+ );+ },+ );it("keeps other jose failures (bad signature) as UNAUTHENTICATED", () => {const error = classifyAccessVerificationError(diff --git a/src/server/auth/default-hosted-organization.test.ts b/src/server/auth/default-hosted-organization.test.tsindex 39a3ad33..e51c3725 100644--- a/src/server/auth/default-hosted-organization.test.ts+++ b/src/server/auth/default-hosted-organization.test.ts@@ -36,20 +36,15 @@ describe("resolveSignInHostedOrganization", () => {// must NOT get a personal organization auto-minted at sign-in — accepting the// invite should leave them in exactly the inviter's org.it("defers organization creation while an invitation is pending", async () => {- mocks.hasPendingInvitationForEmail.mockResolvedValue(true);- const createOrganization = vi.fn();+ const createOrganization = vi.fn().mockResolvedValue({ id: "org-new" });+ mocks.hasPendingInvitationForEmail.mockResolvedValue(true);await expect(resolveSignInHostedOrganization("user-1", createOrganization),).resolves.toBeNull();-expect(createOrganization).not.toHaveBeenCalled();- });- it("creates the default organization when no invitation is pending", async () => {mocks.hasPendingInvitationForEmail.mockResolvedValue(false);- const createOrganization = vi.fn().mockResolvedValue({ id: "org-new" });-await expect(resolveSignInHostedOrganization("user-1", createOrganization),).resolves.toMatchObject({ organizationId: "org-new" });diff --git a/src/server/auth/workspace-merge.test.ts b/src/server/auth/workspace-merge.test.tsindex 22d2493c..d1693293 100644--- a/src/server/auth/workspace-merge.test.ts+++ b/src/server/auth/workspace-merge.test.ts@@ -202,20 +202,4 @@ describe("WorkspaceMergeService", () => {expect.objectContaining({ n: 4 }),]);});-- it("is a no-op when run again", async () => {- await seedLegacyWorkspaces();- await WorkspaceMergeService.mergeLegacyWorkspaces();-- await expect(- WorkspaceMergeService.mergeLegacyWorkspaces(),- ).resolves.toEqual({ mergedWorkspaces: 0 });- await expect(WorkspaceMergeService.countLegacyWorkspaces()).resolves.toBe(- 0,- );- // Nothing renamed twice.- expect(- await rows("SELECT name FROM projects WHERE id = 'p1-default'"),- ).toEqual([expect.objectContaining({ name: "Default (ben)" })]);- });});diff --git a/src/server/billing/customer-status-model.test.ts b/src/server/billing/customer-status-model.test.tsindex d5b3c323..0c92bde1 100644--- a/src/server/billing/customer-status-model.test.ts+++ b/src/server/billing/customer-status-model.test.ts@@ -7,59 +7,41 @@ const paidFlags = (planId: string) => ({});describe("deriveBillingCustomerStatusSnapshot", () => {- it("marks customers whose paid plan is active as paying", () => {- const snapshot = deriveBillingCustomerStatusSnapshot({- id: "org_123",+ it.each([+ {+ name: "an active paid plan is paying",flags: paidFlags("yc-plan"),subscriptions: [{ planId: "yc-plan", status: "active" }],- });-- expect(snapshot).toMatchObject({- organizationId: "org_123",- isPaying: true,- paidPlanId: "yc-plan",- paidPlanStatus: "active",- });- });-- it("preserves the full customer payload in customerJson", () => {- const snapshot = deriveBillingCustomerStatusSnapshot({- id: "org_123",- email: "[email protected]",- stripeId: "cus_123",- });-- expect(JSON.parse(snapshot.customerJson)).toMatchObject({- id: "org_123",- email: "[email protected]",- stripeId: "cus_123",- });- });-- it("keeps customers without the paid entitlement queryable but not paying", () => {- const snapshot = deriveBillingCustomerStatusSnapshot({- id: "org_123",+ expected: {+ isPaying: true,+ paidPlanId: "yc-plan",+ paidPlanStatus: "active",+ },+ },+ {+ name: "no paid entitlement stays queryable but not paying",flags: {},subscriptions: [{ planId: "free", status: "active" }],- });-- expect(snapshot.isPaying).toBe(false);- expect(snapshot.paidPlanId).toBeNull();- expect(snapshot.paidPlanStatus).toBeNull();- });-- it("records a past-due paid plan as not paying", () => {- const snapshot = deriveBillingCustomerStatusSnapshot({- id: "org_456",+ expected: { isPaying: false, paidPlanId: null, paidPlanStatus: null },+ },+ {+ name: "a past-due paid plan is not paying",flags: paidFlags("base-plan"),subscriptions: [{ planId: "base-plan", status: "past_due" }],- });-- expect(snapshot).toMatchObject({- isPaying: false,- paidPlanId: "base-plan",- paidPlanStatus: "past_due",- });+ expected: {+ isPaying: false,+ paidPlanId: "base-plan",+ paidPlanStatus: "past_due",+ },+ },+ ])("$name", ({ flags, subscriptions, expected }) => {+ expect(+ deriveBillingCustomerStatusSnapshot({+ id: "org_123",+ flags,+ subscriptions,+ }),+ ).toMatchObject({ organizationId: "org_123", ...expected });});it("prefers the active row when the plan has several subscriptions", () => {diff --git a/src/server/billing/loops-contact-properties.test.ts b/src/server/billing/loops-contact-properties.test.tsindex 94d60a56..aa6be68f 100644--- a/src/server/billing/loops-contact-properties.test.ts+++ b/src/server/billing/loops-contact-properties.test.ts@@ -5,18 +5,6 @@ import {} from "./loops-contact-properties";describe("getBillingLoopsContactProperties", () => {- it("maps Autumn billing fields to Loops custom properties", () => {- expect(- getBillingLoopsContactProperties({- paidPlanId: "base-plan",- paidPlanStatus: "active",- }),- ).toEqual({- billingPlanId: "base-plan",- billingPlanStatus: "active",- });- });-it("uses explicit none values when the customer has no paid plan", () => {expect(getBillingLoopsContactProperties({diff --git a/src/server/billing/subscription.test.ts b/src/server/billing/subscription.test.tsindex 3a951e64..d0466fac 100644--- a/src/server/billing/subscription.test.ts+++ b/src/server/billing/subscription.test.ts@@ -49,10 +49,6 @@ vi.mock("@/server/billing/autumn", () => ({AUTUMN_TRACK_RETRY_OPTIONS: {},}));-vi.mock("@/server/lib/runtime-env", () => ({- isHostedServerAuthMode: vi.fn(),-}));-// subscription.ts now imports posthog (for trackUsageCreditSpend); stub it so// the test doesn't pull in the cloudflare:workers runtime it depends on.vi.mock("@/server/lib/posthog", () => ({@@ -77,7 +73,6 @@ const customer = {describe("subscription billing", () => {beforeEach(() => {- vi.clearAllMocks();kvGetMock.mockResolvedValue(null);kvPutMock.mockResolvedValue(undefined);});@@ -86,24 +81,6 @@ describe("subscription billing", () => {vi.useRealTimers();});- it("checks the paid plan entitlement", async () => {- checkMock.mockResolvedValue({ allowed: true });-- await expect(customerHasPaidPlan("org_123")).resolves.toBe(true);-- expect(checkMock).toHaveBeenCalledWith({- customerId: "org_123",- featureId: AUTUMN_PAID_PLAN_FEATURE_ID,- });- });-- it("returns false without retrying when org lacks paid plan", async () => {- checkMock.mockResolvedValue({ allowed: false });-- await expect(customerHasPaidPlan("org_123")).resolves.toBe(false);- expect(checkMock).toHaveBeenCalledTimes(1);- });-it("recovers from a degraded negative read when retryDenied is set", async () => {vi.useFakeTimers();checkMock@@ -115,6 +92,10 @@ describe("subscription billing", () => {await expect(result).resolves.toBe(true);expect(checkMock).toHaveBeenCalledTimes(2);+ expect(checkMock).toHaveBeenCalledWith({+ customerId: "org_123",+ featureId: AUTUMN_PAID_PLAN_FEATURE_ID,+ });});it("retries a missing monthly balance once", async () => {@@ -172,7 +153,6 @@ describe("subscription billing", () => {customerId: "org_123",email: "[email protected]",});- expect(kvPutMock).toHaveBeenCalled();});it("skips the Autumn round trip when the customer was recently ensured", async () => {@@ -188,49 +168,30 @@ describe("subscription billing", () => {expect(getOrCreateMock).not.toHaveBeenCalled();});- it("falls back to Autumn when the customer cache read fails", async () => {- const cacheError = new Error("KV read unavailable");- vi.spyOn(console, "warn").mockImplementation(() => undefined);- kvGetMock.mockRejectedValue(cacheError);- getOrCreateMock.mockResolvedValue({ id: "cust_123" });-- await expect(- getOrCreateOrganizationCustomer({- organizationId: "org_123",- userId: "user_123",- userEmail: "[email protected]",- }),- ).resolves.toEqual({ id: "cust_123" });-- expect(getOrCreateMock).toHaveBeenCalledWith({- customerId: "org_123",- email: "[email protected]",- });- expect(console.warn).toHaveBeenCalledWith(- "billing.customer-cache-read failed:",- cacheError,- );- });-- it("returns the resolved customer when the customer cache write fails", async () => {- const cacheError = new Error("KV write unavailable");- vi.spyOn(console, "warn").mockImplementation(() => undefined);- getOrCreateMock.mockResolvedValue({ id: "cust_123" });- kvPutMock.mockRejectedValue(cacheError);-- await expect(- getOrCreateOrganizationCustomer({- organizationId: "org_123",- userId: "user_123",- userEmail: "[email protected]",- }),- ).resolves.toEqual({ id: "cust_123" });-- expect(console.warn).toHaveBeenCalledWith(- "billing.customer-cache-write failed:",- cacheError,- );- });+ // A KV outage must never block billing; the customer still resolves.+ it.each([+ ["read", () => kvGetMock.mockRejectedValue(new Error("KV unavailable"))],+ ["write", () => kvPutMock.mockRejectedValue(new Error("KV unavailable"))],+ ])(+ "falls back to Autumn when the customer cache %s fails",+ async (_op, breakCache) => {+ vi.spyOn(console, "warn").mockImplementation(() => undefined);+ breakCache();+ getOrCreateMock.mockResolvedValue({ id: "cust_123" });++ await expect(+ getOrCreateOrganizationCustomer({+ organizationId: "org_123",+ userId: "user_123",+ userEmail: "[email protected]",+ }),+ ).resolves.toEqual({ id: "cust_123" });+ expect(getOrCreateMock).toHaveBeenCalledWith({+ customerId: "org_123",+ email: "[email protected]",+ });+ },+ );});describe("reserveUsageCredits", () => {diff --git a/src/server/billing/svix.test.ts b/src/server/billing/svix.test.tsindex 1aa88899..b7b486b8 100644--- a/src/server/billing/svix.test.ts+++ b/src/server/billing/svix.test.ts@@ -3,28 +3,31 @@ import { verifySvixSignature } from "./svix";const SECRET_BYTES = "test-webhook-secret";const SECRET = `whsec_${Buffer.from(SECRET_BYTES).toString("base64")}`;+const payload = JSON.stringify({ type: "billing.updated" });describe("verifySvixSignature", () => {- it("accepts a valid Svix signature", async () => {- const payload = JSON.stringify({ type: "billing.updated" });- const headers = await signedHeaders({- id: "msg_123",- payload,- timestamp: 1_000,- });-- await expect(- verifySvixSignature({- headers,- nowSeconds: 1_000,+ it.each(["svix", "webhook"])(+ "accepts a valid signature under %s-prefixed headers",+ async (prefix) => {+ const headers = await signedHeaders({+ id: "msg_123",payload,- secret: SECRET,- }),- ).resolves.toBe(true);- });+ timestamp: 1_000,+ prefix,+ });++ await expect(+ verifySvixSignature({+ headers,+ nowSeconds: 1_000,+ payload,+ secret: SECRET,+ }),+ ).resolves.toBe(true);+ },+ );it("rejects tampered payloads", async () => {- const payload = JSON.stringify({ type: "billing.updated" });const headers = await signedHeaders({id: "msg_123",payload,@@ -42,7 +45,6 @@ describe("verifySvixSignature", () => {});it("rejects stale timestamps", async () => {- const payload = JSON.stringify({ type: "billing.updated" });const headers = await signedHeaders({id: "msg_123",payload,@@ -60,7 +62,6 @@ describe("verifySvixSignature", () => {});it("rejects malformed signatures without throwing", async () => {- const payload = JSON.stringify({ type: "billing.updated" });const headers = new Headers({"svix-id": "msg_123","svix-signature": "v1,not-base64!",@@ -76,40 +77,21 @@ describe("verifySvixSignature", () => {}),).resolves.toBe(false);});-- it("accepts Webhook-prefixed headers", async () => {- const payload = JSON.stringify({ type: "billing.updated" });- const timestamp = 1_000;- const id = "msg_123";- const signature = await sign(`${id}.${timestamp}.${payload}`);- const headers = new Headers({- "webhook-id": id,- "webhook-signature": `v1,${signature}`,- "webhook-timestamp": String(timestamp),- });-- await expect(- verifySvixSignature({- headers,- nowSeconds: timestamp,- payload,- secret: SECRET,- }),- ).resolves.toBe(true);- });});async function signedHeaders(args: {id: string;payload: string;timestamp: number;+ prefix?: string;}) {+ const prefix = args.prefix ?? "svix";const signature = await sign(`${args.id}.${args.timestamp}.${args.payload}`);return new Headers({- "svix-id": args.id,- "svix-signature": `v1,${signature}`,- "svix-timestamp": String(args.timestamp),+ [`${prefix}-id`]: args.id,+ [`${prefix}-signature`]: `v1,${signature}`,+ [`${prefix}-timestamp`]: String(args.timestamp),});}diff --git a/src/server/features/ai-search/safeUrl.test.ts b/src/server/features/ai-search/safeUrl.test.tsindex d6b24e5c..75138f89 100644--- a/src/server/features/ai-search/safeUrl.test.ts+++ b/src/server/features/ai-search/safeUrl.test.ts@@ -2,14 +2,12 @@ import { describe, expect, it } from "vitest";import { safeHostname, safeHttpUrl } from "./safeUrl";describe("safeHttpUrl", () => {- it.each([- "https://example.com",- "http://example.com",- "https://example.com/path?q=1#frag",- "https://sub.example.com",- ])("accepts %s", (input) => {- expect(safeHttpUrl(input)).toBe(input);- });+ it.each(["http://example.com", "https://example.com/path?q=1#frag"])(+ "accepts %s",+ (input) => {+ expect(safeHttpUrl(input)).toBe(input);+ },+ );it.each(["javascript:alert(1)",@@ -25,11 +23,6 @@ describe("safeHttpUrl", () => {])("rejects %s", (input) => {expect(safeHttpUrl(input)).toBeNull();});-- it("returns null for null/undefined", () => {- expect(safeHttpUrl(null)).toBeNull();- expect(safeHttpUrl(undefined)).toBeNull();- });});describe("safeHostname", () => {@@ -37,14 +30,4 @@ describe("safeHostname", () => {expect(safeHostname("https://www.example.com/path")).toBe("example.com");expect(safeHostname("http://sub.example.com")).toBe("sub.example.com");});-- it("returns null for unsafe schemes", () => {- expect(safeHostname("javascript:alert(1)")).toBeNull();- expect(safeHostname("data:text/html,foo")).toBeNull();- });-- it("returns null for invalid input", () => {- expect(safeHostname("not a url")).toBeNull();- expect(safeHostname(null)).toBeNull();- });});diff --git a/src/server/features/ai-search/services/brandLookup.test.ts b/src/server/features/ai-search/services/brandLookup.test.tsindex 9222eaf5..a1f65736 100644--- a/src/server/features/ai-search/services/brandLookup.test.ts+++ b/src/server/features/ai-search/services/brandLookup.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("cloudflare:workers", () => ({ waitUntil: vi.fn() }));@@ -45,8 +45,7 @@ vi.mock("@/server/lib/dataforseo", () => {vi.mock("@/server/lib/r2-cache", () => cacheMock);import { getBrandLookup } from "./brandLookup";-import { shapeResult, type ShapeArgs } from "./brandLookupShaping";-import { resolveCompetitorGroups } from "./shareOfVoice";+import { shapeResult } from "./brandLookupShaping";import { brandLookupSearchSchema } from "@/types/schemas/ai-search";import type {LlmMentionItem,@@ -60,138 +59,69 @@ const billingCustomer: BillingCustomerContext = {userEmail: "[email protected]",};-type PlatformBundle = {- aggregated: { platform?: Array<Record<string, unknown>> | null };- topPages: LlmTopPagesItem[];- mentions: LlmMentionItem[];- complete: boolean;-};--function platformBundle(- platform: "chat_gpt" | "google",- mentions: number | null,- aiSearchVolume: number | null,-): ShapeArgs["platformBundles"][number] {- return {- platform,- status: "success",- bundle: {- aggregated: {- platform: [- {- key: platform,- mentions,- ai_search_volume: aiSearchVolume,- // Deprecated field still present in upstream payloads; must be- // ignored end-to-end.- impressions: 999,- },- ],- },- topPages: [],- mentions: [],- complete: true,- } as PlatformBundle,- };-}--function baseArgs(overrides: Partial<ShapeArgs>): ShapeArgs {- return {- query: "acme",- detected: { type: "keyword", value: "acme" },- researchTarget: null,- platformBundles: [- platformBundle("chat_gpt", 10, 100),- platformBundle("google", 5, 50),- ],- crossOutcomes: [],- competitorKeys: [],- userLocationCode: 2840,- userLanguageCode: "en",- ...overrides,- };-}--function resetBrandLookupMocks(): void {- vi.clearAllMocks();- cacheMock.getCached.mockResolvedValue(null);- cacheMock.setCached.mockResolvedValue(undefined);- dataforseoClientMock.aiSearch.aggregatedMetrics.mockResolvedValue({- platform: [{ key: "google", mentions: 5, ai_search_volume: 50 }],- });- dataforseoClientMock.aiSearch.topPages.mockImplementation(- async ({ platform }: { platform: "chat_gpt" | "google" }) => [- topPage(`https://${platform}.example/source`, platform, 3, 300),- ],- );- dataforseoClientMock.aiSearch.mentionsSearch.mockImplementation(- async ({ platform }: { platform: "chat_gpt" | "google" }) => [- citedMention("best source", 100, [`https://${platform}.example/source`]),- ],- );- dataforseoClientMock.aiSearch.crossAggregatedMetrics.mockResolvedValue([]);-}+// A previously cached result for the same target, built through the real+// shaper so it passes the cache schema on read.+const cachedResult = shapeResult({+ query: "acme",+ detected: { type: "keyword", value: "acme" },+ researchTarget: null,+ platformBundles: [],+ crossOutcomes: [],+ competitorKeys: [],+ userLocationCode: 2840,+ userLanguageCode: "en",+});describe("getBrandLookup", () => {- it("fetches top_pages as part of the base lookup", async () => {- resetBrandLookupMocks();-- await getBrandLookup(- {- projectId: "project_123",- query: "acme.com",- competitors: [],- locationCode: 2840,- languageCode: "en",- },- billingCustomer,- );-- expect(dataforseoClientMock.aiSearch.topPages).toHaveBeenCalledTimes(2);- expect(dataforseoClientMock.aiSearch.topPages).toHaveBeenCalledWith(- expect.objectContaining({- platform: "chat_gpt",- itemsListLimit: 10,- }),+ beforeEach(() => {+ cacheMock.getCached.mockResolvedValue(null);+ cacheMock.setCached.mockResolvedValue(undefined);+ dataforseoClientMock.aiSearch.aggregatedMetrics.mockResolvedValue({+ platform: [{ key: "google", mentions: 5, ai_search_volume: 50 }],+ });+ dataforseoClientMock.aiSearch.topPages.mockImplementation(+ async ({ platform }: { platform: "chat_gpt" | "google" }) => [+ topPage(`https://${platform}.example/source`, platform, 3, 300),+ ],);- expect(dataforseoClientMock.aiSearch.topPages).toHaveBeenCalledWith(- expect.objectContaining({- platform: "google",- itemsListLimit: 10,- }),+ dataforseoClientMock.aiSearch.mentionsSearch.mockImplementation(+ async ({ platform }: { platform: "chat_gpt" | "google" }) => [+ citedMention("best source", 100, [+ `https://${platform}.example/source`,+ ]),+ ],);- expect(cacheMock.setCached).toHaveBeenCalledTimes(1);+ dataforseoClientMock.aiSearch.crossAggregatedMetrics.mockResolvedValue([]);});it("does not cache a renderable partial result when top_pages fails", async () => {- resetBrandLookupMocks();const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);+ const input = {+ projectId: "project_123",+ query: "acme.com",+ competitors: [],+ locationCode: 2840,+ languageCode: "en",+ };dataforseoClientMock.aiSearch.topPages.mockRejectedValueOnce(new Error("top pages failed"),);- const result = await getBrandLookup(- {- projectId: "project_123",- query: "acme.com",- competitors: [],- locationCode: 2840,- languageCode: "en",- },- billingCustomer,- );-- expect(result.hasData).toBe(true);+ const partial = await getBrandLookup(input, billingCustomer);+ expect(partial.hasData).toBe(true);expect(cacheMock.setCached).not.toHaveBeenCalled();++ // Positive control: the same lookup with every call succeeding is cached.+ await getBrandLookup(input, billingCustomer);+ expect(cacheMock.setCached).toHaveBeenCalledTimes(1);consoleError.mockRestore();});it("uses semantic cache keys and reapplies the current display query", async () => {- resetBrandLookupMocks();cacheMock.getCached.mockResolvedValueOnce({- ...shapeResult(baseArgs({})),+ ...cachedResult,query: "Nike",resolvedTarget: "Nike",});@@ -221,8 +151,6 @@ describe("getBrandLookup", () => {});it("drops subdomains and keys the cache on scope for a URL query", async () => {- resetBrandLookupMocks();-const result = await getBrandLookup({projectId: "project_123",@@ -252,36 +180,17 @@ describe("getBrandLookup", () => {});});-describe("resolveCompetitorGroups", () => {- it("dedupes case-insensitively and drops target collisions", () => {- // DataForSEO matches keyword targets case-insensitively, so "Nike" and- // "nike" would be two paid groups returning identical counts.- const groups = resolveCompetitorGroups("Nike", [- "nike",- "Adidas",- "ADIDAS",- "puma.com",- "www.PUMA.com",- ]);- expect(groups.map((g) => g.label)).toEqual(["Adidas", "puma.com"]);- });-});-describe("brandLookupSearchSchema — `c` competitor param", () => {- it("parses a raw comma-separated string from the URL", () => {- expect(brandLookupSearchSchema.parse({ c: "nike, adidas" }).c).toEqual([- "nike",- "adidas",- ]);- });-- it("accepts an already-parsed array (TanStack re-validates its own output)", () => {- // navigate() feeds the previous transformed output (a string[]) back through- // validateSearch — this must not throw "expected string, received array".- expect(brandLookupSearchSchema.parse({ c: ["nike", "adidas"] }).c).toEqual([- "nike",- "adidas",- ]);+ it.each([+ ["a raw comma-separated string from the URL", "nike, adidas"],+ // navigate() feeds the previous transformed output (a string[]) back+ // through validateSearch — this must not throw "expected string".+ [+ "an already-parsed array (TanStack re-validates its own output)",+ ["nike", "adidas"],+ ],+ ])("parses %s", (_form, c) => {+ expect(brandLookupSearchSchema.parse({ c }).c).toEqual(["nike", "adidas"]);});it("dedupes and caps at 5 regardless of input form", () => {@@ -294,10 +203,6 @@ describe("brandLookupSearchSchema — `c` competitor param", () => {"e",]);});-- it("leaves `c` undefined when absent", () => {- expect(brandLookupSearchSchema.parse({}).c).toBeUndefined();- });});function citedMention(diff --git a/src/server/features/ai-search/services/brandLookupShaping.test.ts b/src/server/features/ai-search/services/brandLookupShaping.test.tsindex 84e339f2..d90f20ae 100644--- a/src/server/features/ai-search/services/brandLookupShaping.test.ts+++ b/src/server/features/ai-search/services/brandLookupShaping.test.ts@@ -136,36 +136,6 @@ describe("shapeResult", () => {expect(result.topQueries[0].brandsMentioned[0]).toHaveLength(200);});- it("round-trips through the cache schema", () => {- const topPage: LlmTopPagesItem = {- key: "https://a.com",- platform: [{ key: "google", mentions: 3, ai_search_volume: 300 }],- };- const result = shapeResult(- baseArgs({- platformBundles: [- {- platform: "google",- status: "success",- bundle: {- aggregated: { platform: [] },- topPages: [topPage],- mentions: [],- complete: true,- },- },- ],- }),- );-- expect(result.topPages[0]).toMatchObject({- domain: "a.com",- mentions: 3,- capturedVolume: 300,- });- expect(brandLookupResultSchema.safeParse(result).success).toBe(true);- });-it("keeps only in-scope page rows and prompts under a subfolder scope", () => {const parsed = parseResearchTarget("acme.com/blog", "subfolder");if (!parsed.ok) throw new Error(parsed.message);@@ -209,6 +179,9 @@ describe("shapeResult", () => {expect(result.totalMentions).toBe(12);expect(result.aggregatesAreDomainLevel).toBe(true);expect(result.resolvedTarget).toBe("acme.com/blog");+ // A shape the cache schema rejects turns every cache read into a+ // re-charged lookup.+ expect(brandLookupResultSchema.safeParse(result).success).toBe(true);});});diff --git a/src/server/features/ai-search/services/citedSources.test.ts b/src/server/features/ai-search/services/citedSources.test.tsindex 01e7f0ad..c8ed22b8 100644--- a/src/server/features/ai-search/services/citedSources.test.ts+++ b/src/server/features/ai-search/services/citedSources.test.ts@@ -31,7 +31,7 @@ function topPage(}describe("deriveCitedSources", () => {- it("uses top_pages metrics and attaches matching prompt examples", () => {+ it("uses top_pages metrics and attaches deduped prompt examples", () => {const sources = deriveCitedSources([{@@ -45,7 +45,11 @@ describe("deriveCitedSources", () => {"https://a.com/x","https://b.com/y",]),- citedMention("cheap seo", 500, ["https://a.com/x"]),+ // The same page cited twice in one answer is one example.+ citedMention("cheap seo", 500, [+ "https://a.com/x",+ "https://a.com/x",+ ]),],},],@@ -64,37 +68,4 @@ describe("deriveCitedSources", () => {),).toEqual(["best seo tools", "cheap seo"]);});-- it("dedupes sampled prompt examples and derives domains from urls", () => {- const sources = deriveCitedSources(- [- {- platform: "google",- topPages: [topPage("https://evil.example/path", "google", 3, 300)],- mentions: [- {- question: "q",- ai_search_volume: 200,- sources: [- {- url: "https://evil.example/path",- domain: "customer.example",- },- { url: "https://evil.example/path" },- ],- },- ],- },- ],- { sourcesPerPlatform: 20, keywordsPerSource: 50 },- );-- expect(sources[0]).toMatchObject({- url: "https://evil.example/path",- domain: "evil.example",- });- expect(sources[0].keywords).toEqual([- { question: "q", aiSearchVolume: 200 },- ]);- });});diff --git a/src/server/features/ai-search/services/promptExplorer.test.ts b/src/server/features/ai-search/services/promptExplorer.test.tsindex 7d891226..1a43c142 100644--- a/src/server/features/ai-search/services/promptExplorer.test.ts+++ b/src/server/features/ai-search/services/promptExplorer.test.ts@@ -1,10 +1,9 @@import { describe, expect, it, vi } from "vitest";import type { LlmResponseResult } from "@/server/lib/dataforseoLlmSchemas";+import { extractCitations } from "./promptExplorer";vi.mock("cloudflare:workers", () => ({ waitUntil: vi.fn() }));-const { extractCitations } = await import("./promptExplorer");-// DataForSEO's LLM Responses payload nests references as untyped// `{ title, url }` objects under items[].sections[].annotations — mirroring the// SDK's AnnotationInfo, which has no citation-type discriminator.@@ -16,8 +15,15 @@ function response(web_search: true,items: [{+ // Annotations outside message items are never citations.type: "reasoning",- sections: [{ type: "summary_text", text: "thinking" }],+ sections: [+ {+ type: "summary_text",+ text: "thinking",+ annotations: [{ title: "x", url: "https://x.test/1" }],+ },+ ],},{type: "message",@@ -55,24 +61,4 @@ describe("extractCitations", () => {expect(citations).toHaveLength(1);expect(citations[0]?.url).toBe("https://example.com/a");});-- it("ignores annotations outside message items and returns [] when absent", () => {- expect(extractCitations({ items: [] })).toEqual([]);- expect(- extractCitations({- items: [- {- type: "reasoning",- sections: [- {- type: "summary_text",- text: "t",- annotations: [{ title: "x", url: "https://x.test/1" }],- },- ],- },- ],- }),- ).toEqual([]);- });});diff --git a/src/server/features/ai-search/services/shareOfVoice.test.ts b/src/server/features/ai-search/services/shareOfVoice.test.tsindex 791b79ed..9bb0df60 100644--- a/src/server/features/ai-search/services/shareOfVoice.test.ts+++ b/src/server/features/ai-search/services/shareOfVoice.test.ts@@ -49,20 +49,6 @@ describe("computeShareOfVoice", () => {expect(entries[1]).toMatchObject({ label: "rival", sharePct: 25 });expect(entries[2]).toMatchObject({ mentions: null, sharePct: null });});-- it("returns null with no competitors or no successful calls", () => {- expect(computeShareOfVoice([], "acme", [])).toBe(null);- expect(- computeShareOfVoice(- [- { platform: "chat_gpt", status: "error", items: [] },- { platform: "google", status: "error", items: [] },- ],- "acme",- ["rival"],- ),- ).toBe(null);- });});describe("resolveCompetitorGroups", () => {diff --git a/src/server/features/audit/AuditScratchpad.test.ts b/src/server/features/audit/AuditScratchpad.test.tsindex 381183d5..1b373068 100644--- a/src/server/features/audit/AuditScratchpad.test.ts+++ b/src/server/features/audit/AuditScratchpad.test.ts@@ -65,10 +65,15 @@ beforeEach(() => {});describe("broken internal links", () => {- it("reports a crawled-and-failed target once, with its status", () => {+ it("reports a crawled-and-failed target once, ignoring fine and uncrawled targets", () => {addPage("p1", START);addPage("p2", "https://site.test/gone", { status: 404 });- addLinks("p1", START, ["https://site.test/gone"]);+ addPage("p3", "https://site.test/ok");+ addLinks("p1", START, [+ "https://site.test/gone",+ "https://site.test/ok",+ "https://site.test/never-crawled",+ ]);expect(brokenLinks()).toEqual([{@@ -80,17 +85,6 @@ describe("broken internal links", () => {]);});- it("ignores targets that were never crawled and targets that are fine", () => {- addPage("p1", START);- addPage("p2", "https://site.test/ok");- addLinks("p1", START, [- "https://site.test/ok",- "https://site.test/never-crawled",- ]);-- expect(brokenLinks()).toEqual([]);- });-it("ignores WAF-blocked 4xx targets", () => {addPage("p1", START);addPage("p2", "https://site.test/waf", {@@ -134,10 +128,11 @@ describe("broken internal links", () => {});describe("orphan pages", () => {- it("flags a 2xx page nothing links to", () => {+ it("flags a 2xx page nothing links to, not the start URL or a linked page", () => {addPage("p1", START);addPage("p2", "https://site.test/lonely");- addLinks("p1", START, ["https://site.test/other"]);+ addPage("p3", "https://site.test/linked");+ addLinks("p1", START, ["https://site.test/linked"]);expect(orphanPages()).toEqual([{ page_id: "p2", url: "https://site.test/lonely" },@@ -154,14 +149,6 @@ describe("orphan pages", () => {]);});- it("does not flag a page linked from another page", () => {- addPage("p1", START);- addPage("p2", "https://site.test/linked");- addLinks("p1", START, ["https://site.test/linked"]);-- expect(orphanPages()).toEqual([]);- });-it("does not flag a page something redirects to", () => {addPage("p1", START);addPage("p2", "https://site.test/target");@@ -173,12 +160,6 @@ describe("orphan pages", () => {expect(orphanPages()).toEqual([]);});- it("never flags the start URL", () => {- addPage("p1", START);-- expect(orphanPages()).toEqual([]);- });-it("ignores non-2xx and blocked pages", () => {addPage("p1", START);addPage("p2", "https://site.test/gone", { status: 404 });diff --git a/src/server/features/audit/services/AuditService.crawlerAccess.test.ts b/src/server/features/audit/services/AuditService.crawlerAccess.test.tsindex 53d9f596..a2d8787c 100644--- a/src/server/features/audit/services/AuditService.crawlerAccess.test.ts+++ b/src/server/features/audit/services/AuditService.crawlerAccess.test.ts@@ -57,13 +57,10 @@ vi.mock("@/server/lib/audit/progress-kv", () => ({ AuditProgressKV: {} }));import { symmetricEncrypt } from "better-auth/crypto";import { AuditService } from "@/server/features/audit/services/AuditService";-async function credentialRow(- expiresAt: string | null,- host = "store.example.com",-) {+async function credentialRow(expiresAt: string | null) {return {id: "cred-1",- host,+ host: "store.example.com",signatureInput: await symmetricEncrypt({ key: SECRET, data: "sig1=(...)" }),signature: await symmetricEncrypt({ key: SECRET, data: "sig1=:abc:" }),expiresAt,@@ -120,6 +117,7 @@ describe("startAudit crawler access", () => {it("records the Shopify platform and keeps the signature encrypted at rest", async () => {await AuditService.startAudit(input);+ expect(probeSignature()).toBe("sig1=:abc:");const config = createAuditMock.mock.calls[0][0].config;expect(config.sitePlatform).toBe("shopify");expect(config.crawlerCredentialId).toBe("cred-1");@@ -130,22 +128,6 @@ describe("startAudit crawler access", () => {expect(params.access).toMatchObject({ host: "store.example.com" });});- it("starts the probe with the decrypted signature", async () => {- await AuditService.startAudit(input);-- expect(probeSignature()).toBe("sig1=:abc:");- });-- it("binds the signature to the domain it was created for", async () => {- findCredentialMock.mockResolvedValue([- await credentialRow(null, "www.store.example.com"),- ]);-- await AuditService.startAudit(input);-- expect(probeSignature()).toBeNull();- });-it("does not replay an expired signature", async () => {findCredentialMock.mockResolvedValue([await credentialRow("2020-01-01T00:00:00.000Z"),diff --git a/src/server/features/audit/services/AuditService.limitTier.test.ts b/src/server/features/audit/services/AuditService.limitTier.test.tsindex ff1c9183..b678fa46 100644--- a/src/server/features/audit/services/AuditService.limitTier.test.ts+++ b/src/server/features/audit/services/AuditService.limitTier.test.ts@@ -39,7 +39,6 @@ const customer = {describe("resolveAuditLimitTier", () => {beforeEach(() => {- vi.clearAllMocks();hasManagedAccessMock.mockResolvedValue(true);hasPaidPlanMock.mockResolvedValue(true);});diff --git a/src/server/features/audit/services/audit-capacity.test.ts b/src/server/features/audit/services/audit-capacity.test.tsindex f1078211..5258f74f 100644--- a/src/server/features/audit/services/audit-capacity.test.ts+++ b/src/server/features/audit/services/audit-capacity.test.ts@@ -13,47 +13,17 @@ describe("audit capacity helpers", () => {expect(clampAuditMaxPages(20_000)).toBe(10_000);});- it("estimates capacity for each lighthouse strategy", () => {- expect(- getEstimatedAuditCapacity({ maxPages: 100, lighthouseStrategy: "none" }),- ).toEqual({- pagesTotal: 100,- lighthouseTotal: 0,- total: 100,- });- expect(- getEstimatedAuditCapacity({ maxPages: 100, lighthouseStrategy: "auto" }),- ).toEqual({- pagesTotal: 100,- lighthouseTotal: 20,- total: 120,- });- });-- it("stays within the paid capacity limit for the maximum auto audit", () => {- expect(- getEstimatedAuditCapacity({- maxPages: 10_000,+ // If a tier's largest auto audit doesn't fit its own capacity budget, every+ // max-size audit on that tier is rejected right after insert.+ it.each(["free", "paid"] as const)(+ "fits the maximum %s auto audit within its capacity budget",+ (tier) => {+ const estimate = getEstimatedAuditCapacity({+ maxPages: AUDIT_LIMITS[tier].maxPagesPerAudit,lighthouseStrategy: "auto",- }).total,- ).toBeLessThan(AUDIT_LIMITS.paid.maxCapacityUnits);- });-- it("fits a maximum free audit within the free capacity budget", () => {- const freeAudit = getEstimatedAuditCapacity({- maxPages: AUDIT_LIMITS.free.maxPagesPerAudit,- lighthouseStrategy: "auto",- });- expect(freeAudit.pagesTotal).toBe(AUDIT_LIMITS.free.maxPagesPerAudit);- expect(freeAudit.total).toBeLessThan(AUDIT_LIMITS.free.maxCapacityUnits);- });-- it("lifts only the cumulative self-hosted cap", () => {- expect(AUDIT_LIMITS.self_hosted.maxCapacityUnits).toBe(- Number.POSITIVE_INFINITY,- );- expect(AUDIT_LIMITS.self_hosted.maxPagesPerAudit).toBe(- AUDIT_LIMITS.paid.maxPagesPerAudit,- );- });+ });+ expect(estimate.pagesTotal).toBe(AUDIT_LIMITS[tier].maxPagesPerAudit);+ expect(estimate.total).toBeLessThan(AUDIT_LIMITS[tier].maxCapacityUnits);+ },+ );});diff --git a/src/server/features/backlinks/services/BacklinksService.billing.test.ts b/src/server/features/backlinks/services/BacklinksService.billing.test.tsindex a235c32f..4842a58d 100644--- a/src/server/features/backlinks/services/BacklinksService.billing.test.ts+++ b/src/server/features/backlinks/services/BacklinksService.billing.test.ts@@ -72,37 +72,12 @@ const service = createBacklinksService({beforeEach(() => {cache.clear();- vi.clearAllMocks();});it("profiles only the summary and history for the overview and reuses cache on repeat", async () => {mockTarget();- backlinksSummaryMock.mockResolvedValue({- rank: 42,- backlinks: 1200,- referring_pages: 900,- referring_domains: 320,- broken_backlinks: 12,- broken_pages: 3,- backlinks_spam_score: 5,- info: { target_spam_score: 4 },- new_backlinks: 25,- lost_backlinks: 10,- new_referring_domains: 8,- lost_referring_domains: 2,- });- backlinksHistoryMock.mockResolvedValue([- {- date: "2026-02-01",- backlinks: 1100,- referring_domains: 300,- rank: 40,- new_backlinks: 20,- lost_backlinks: 5,- new_referring_domains: 3,- lost_referring_domains: 1,- },- ]);+ backlinksSummaryMock.mockResolvedValue({ backlinks: 1200 });+ backlinksHistoryMock.mockResolvedValue([{ date: "2026-02-01" }]);const first = await service.profileOverview({ target: "example.com" },@@ -126,27 +101,7 @@ it("profiles only the summary and history for the overview and reuses cache on rit("profiles backlink rows per page with offset and total count", async () => {mockTarget();backlinksRowsMock.mockResolvedValue({- items: [- {- domain_from: "source.example",- url_from: "https://source.example/post",- url_to: "https://example.com/",- anchor: "Example",- item_type: "content",- dofollow: true,- rank: 77,- domain_from_rank: 65,- page_from_rank: 54,- backlink_spam_score: 3,- first_seen: "2026-01-01",- last_visited: "2026-03-01",- lost_date: null,- is_lost: false,- is_broken: false,- links_count: 1,- rel_attributes: ["noopener"],- },- ],+ items: [{ url_from: "https://source.example/post" }],totalCount: 450,});@@ -156,11 +111,14 @@ it("profiles backlink rows per page with offset and total count", async () => {target: "example.com",page: 2,sortField: "rank",+ filters: { include: "blog" },},billingCustomer,{ hideSpam: false },);+ // The user's filters reach the paid call; their translation is owned by+ // backlinksApiFilters.test.ts.expect(backlinksRowsMock).toHaveBeenCalledWith(expect.objectContaining({target: "example.com",@@ -168,6 +126,7 @@ it("profiles backlink rows per page with offset and total count", async () => {offset: 100,orderBy: ["rank,desc"],hideSpam: false,+ filters: [["url_from", "ilike", "%blog%"]],}),);expect(result.rows).toHaveLength(1);@@ -176,112 +135,12 @@ it("profiles backlink rows per page with offset and total count", async () => {expect(result.page).toBe(2);});-it("translates filters into DataForSEO conditions for backlink rows", async () => {- mockTarget();- backlinksRowsMock.mockResolvedValue({ items: [], totalCount: 0 });-- await service.profileBacklinksPage(- {- ...pageInputDefaults,- target: "example.com",- sortField: "rank",- filters: {- include: "blog",- minDomainRank: 30,- linkType: "dofollow",- hideLost: true,- },- },- billingCustomer,- { hideSpam: false },- );-- expect(backlinksRowsMock).toHaveBeenCalledWith(- expect.objectContaining({- filters: [- ["url_from", "ilike", "%blog%"],- "and",- ["domain_from_rank", ">=", 30],- "and",- ["dofollow", "=", true],- "and",- ["is_lost", "=", false],- ],- }),- );-});--it("profiles referring domains and top pages pages separately", async () => {- mockTarget({- apiTarget: "https://example.com/foo",- displayTarget: "https://example.com/foo",- scope: "exact_url",- includeSubdomains: true,- });- referringDomainsMock.mockResolvedValue({- items: [- {- domain: "source.example",- backlinks: 4,- referring_pages: 2,- rank: 65,- first_seen: "2026-01-01",- broken_backlinks: 0,- broken_pages: 0,- backlinks_spam_score: 2,- target_spam_score: 4,- },- ],- totalCount: 1,- });- domainPagesMock.mockResolvedValue({- items: [- {- page: "https://example.com/foo",- backlinks: 100,- referring_domains: 20,- rank: 50,- broken_backlinks: 0,- },- ],- totalCount: 1,- });-- const domains = await service.profileReferringDomainsPage(- {- ...pageInputDefaults,- target: "https://example.com/foo",- sortField: "backlinks",- },- billingCustomer,- );- const pages = await service.profileTopPagesPage(- {- ...pageInputDefaults,- target: "https://example.com/foo",- sortField: "backlinks",- },- billingCustomer,- );-- expect(domains.rows).toHaveLength(1);- expect(domains.rows[0]?.spamScore).toBe(2);- expect(domains.hasMore).toBe(false);- expect(pages.rows).toHaveLength(1);-});-it("does not fall back to target spam score for referring domains", async () => {mockTarget();referringDomainsMock.mockResolvedValue({items: [{domain: "source.example",- backlinks: 4,- referring_pages: 2,- rank: 65,- first_seen: "2026-01-01",- broken_backlinks: 0,- broken_pages: 0,backlinks_spam_score: null,target_spam_score: 4,},@@ -371,17 +230,6 @@ it("builds subfolder overview totals from two filtered backlink counts", async (mode: "as_is",limit: 1,hideSpam: false,- filters: [- [- ["url_to", "like", "%://example.com/blog"],- "or",- ["url_to", "like", "%://example.com/blog/%"],- "or",- ["url_to", "like", "%://www.example.com/blog"],- "or",- ["url_to", "like", "%://www.example.com/blog/%"],- ],- ],}),);expect(backlinksRowsMock).toHaveBeenNthCalledWith(diff --git a/src/server/features/backlinks/services/backlinksApiFilters.test.ts b/src/server/features/backlinks/services/backlinksApiFilters.test.tsindex 60c819d2..8e141c04 100644--- a/src/server/features/backlinks/services/backlinksApiFilters.test.ts+++ b/src/server/features/backlinks/services/backlinksApiFilters.test.ts@@ -40,16 +40,6 @@ describe("buildBacklinksRowsApiFilters", () => {]);});- it("escapes LIKE wildcards in terms", () => {- expect(buildBacklinksRowsApiFilters({ include: "wp_content" })).toEqual([- ["url_from", "ilike", "%wp\\_content%"],- ]);- });-- it("returns no expressions for empty filters", () => {- expect(buildBacklinksRowsApiFilters({})).toEqual([]);- });-it("throws when the condition budget is exceeded", () => {expect(() =>buildBacklinksRowsApiFilters({@@ -60,33 +50,36 @@ describe("buildBacklinksRowsApiFilters", () => {});});-describe("buildReferringDomainsApiFilters", () => {- it("filters on referring-domain fields", () => {- expect(- buildReferringDomainsApiFilters({- include: "edu",- minBacklinks: 5,- maxSpamScore: 30,- }),- ).toEqual([- ["domain", "ilike", "%edu%"],- "and",- ["backlinks", ">=", 5],- "and",- ["backlinks_spam_score", "<=", 30],- ]);- });-});--describe("buildTopPagesApiFilters", () => {- it("filters on the url field", () => {- expect(- buildTopPagesApiFilters({ include: "/blog", minReferringDomains: 2 }),- ).toEqual([- ["url", "ilike", "%/blog%"],- "and",- ["referring_domains", ">=", 2],- ]);+describe("per-endpoint filter builders", () => {+ it.each([+ {+ name: "referring domains",+ build: () =>+ buildReferringDomainsApiFilters({+ include: "edu",+ minBacklinks: 5,+ maxSpamScore: 30,+ }),+ expected: [+ ["domain", "ilike", "%edu%"],+ "and",+ ["backlinks", ">=", 5],+ "and",+ ["backlinks_spam_score", "<=", 30],+ ],+ },+ {+ name: "top pages",+ build: () =>+ buildTopPagesApiFilters({ include: "/blog", minReferringDomains: 2 }),+ expected: [+ ["url", "ilike", "%/blog%"],+ "and",+ ["referring_domains", ">=", 2],+ ],+ },+ ])("$name uses its own field names", ({ build, expected }) => {+ expect(build()).toEqual(expected);});});@@ -111,7 +104,6 @@ describe("client condition count vs server condition budget", () => {}const cases: Array<[string, BacklinksTabFilterValues]> = [- ["empty", { ...EMPTY_BACKLINKS_FILTERS }],["terms and ranges",{diff --git a/src/server/features/domain/services/domainKeywordFilters.test.ts b/src/server/features/domain/services/domainKeywordFilters.test.tsindex cceedace..02e3d03b 100644--- a/src/server/features/domain/services/domainKeywordFilters.test.ts+++ b/src/server/features/domain/services/domainKeywordFilters.test.ts@@ -1,56 +1,27 @@import { describe, expect, it } from "vitest";-import {- buildKeywordFilters,- buildOrderBy,-} from "@/server/features/domain/services/domainKeywordFilters";--describe("buildOrderBy", () => {- it("maps sort modes to DataForSEO field paths", () => {- expect(buildOrderBy("rank", "asc")).toEqual([- "ranked_serp_element.serp_item.rank_absolute,asc",- ]);- expect(buildOrderBy("volume", "desc")).toEqual([- "keyword_data.keyword_info.search_volume,desc",- ]);- expect(buildOrderBy("score", "asc")).toEqual([- "keyword_data.keyword_properties.keyword_difficulty,asc",- ]);- });-});+import { buildKeywordFilters } from "@/server/features/domain/services/domainKeywordFilters";describe("buildKeywordFilters", () => {- it("returns an empty array when no filters are set", () => {- expect(buildKeywordFilters({})).toEqual([]);- });-- it("emits one ilike clause per include term and chains them with 'and'", () => {- expect(buildKeywordFilters({ include: "audit, checker" })).toEqual([+ // Include terms are ANDed here (every term must match), unlike the+ // backlinks filters where they're ORed.+ it("translates each filter kind and chains them with 'and'", () => {+ expect(+ buildKeywordFilters({+ include: "audit, checker",+ exclude: "jobs+salary",+ minVol: 100,+ maxVol: 5000,+ minCpc: 0.5,+ }),+ ).toEqual([["keyword_data.keyword", "ilike", "%audit%"],"and",["keyword_data.keyword", "ilike", "%checker%"],- ]);- });-- it("emits not_ilike clauses for exclude terms", () => {- expect(buildKeywordFilters({ exclude: "jobs+salary" })).toEqual([+ "and",["keyword_data.keyword", "not_ilike", "%jobs%"],"and",["keyword_data.keyword", "not_ilike", "%salary%"],- ]);- });-- it("escapes SQL LIKE wildcards in user-supplied terms", () => {- const result = buildKeywordFilters({ include: "100%" });- expect(result[0]).toEqual(["keyword_data.keyword", "ilike", "%100\\%%"]);- });-- it("includes numeric range conditions", () => {- const result = buildKeywordFilters({- minVol: 100,- maxVol: 5000,- minCpc: 0.5,- });- expect(result).toEqual([+ "and",["keyword_data.keyword_info.search_volume", ">=", 100],"and",["keyword_data.keyword_info.search_volume", "<=", 5000],@@ -59,15 +30,9 @@ describe("buildKeywordFilters", () => {]);});- it("emits an OR group matching keyword or url for the search term", () => {- const result = buildKeywordFilters({}, "audit");- expect(result).toEqual([- [- ["keyword_data.keyword", "ilike", "%audit%"],- "or",- ["ranked_serp_element.serp_item.url", "ilike", "%audit%"],- ],- ]);+ it("escapes SQL LIKE wildcards in user-supplied terms", () => {+ const result = buildKeywordFilters({ include: "100%" });+ expect(result[0]).toEqual(["keyword_data.keyword", "ilike", "%100\\%%"]);});it("ANDs the search OR-group after structured filters", () => {@@ -90,8 +55,7 @@ describe("buildKeywordFilters", () => {minVol: 1,maxVol: 2,});- const arrayClauses = result.filter((entry) => Array.isArray(entry));- expect(arrayClauses).toHaveLength(8);+ expect(result.filter((entry) => Array.isArray(entry))).toHaveLength(8);});it("throws when conditions exceed the 8-condition cap", () => {diff --git a/src/server/features/domain/services/pagination.test.ts b/src/server/features/domain/services/pagination.test.tsindex 9c47b556..6da4c0c7 100644--- a/src/server/features/domain/services/pagination.test.ts+++ b/src/server/features/domain/services/pagination.test.ts@@ -2,18 +2,22 @@ import { describe, expect, it } from "vitest";import { computeHasMore } from "@/server/features/domain/services/pagination";describe("computeHasMore", () => {- it("uses totalCount against the raw fetched offset when known", () => {- expect(computeHasMore(0, 100, 250, 100)).toBe(true);- expect(computeHasMore(200, 50, 250, 100)).toBe(false);- });-- it("returns false for a full page whose fetched count reaches totalCount", () => {- expect(computeHasMore(0, 100, 100, 100)).toBe(false);- });-- it("falls back to a full-page check when totalCount is unknown", () => {- expect(computeHasMore(0, 100, null, 100)).toBe(true);- expect(computeHasMore(0, 100, undefined, 100)).toBe(true);- expect(computeHasMore(100, 40, null, 100)).toBe(false);- });+ it.each([+ // offset, fetched, totalCount, pageSize+ [0, 100, 250, 100, true],+ [200, 50, 250, 100, false],+ // A full last page: fetched count reaches totalCount exactly.+ [0, 100, 100, 100, false],+ // Unknown total: fall back to "was the page full".+ [0, 100, null, 100, true],+ [0, 100, undefined, 100, true],+ [100, 40, null, 100, false],+ ])(+ "computeHasMore(%i, %i, %s, %i) is %s",+ (offset, fetched, totalCount, pageSize, expected) => {+ expect(computeHasMore(offset, fetched, totalCount, pageSize)).toBe(+ expected,+ );+ },+ );});diff --git a/src/server/features/ga4/repositories/Ga4ConnectionRepository.test.ts b/src/server/features/ga4/repositories/Ga4ConnectionRepository.test.tsdeleted file mode 100644index 0cdcfbc0..00000000--- a/src/server/features/ga4/repositories/Ga4ConnectionRepository.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import { DatabaseSync } from "node:sqlite";-import type { SQL } from "drizzle-orm";-import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { Ga4ConnectionRepository } from "./Ga4ConnectionRepository";--const mocks = vi.hoisted(() => ({- insert: vi.fn(),- connectedAccountEmail: undefined as SQL | undefined,-}));--vi.mock("cloudflare:workers", () => ({ env: {} }));-vi.mock("@/db", () => ({ db: { insert: mocks.insert } }));--function evaluateConnectedAccountEmail(expression: SQL): string | null {- const database = new DatabaseSync(":memory:");- database.exec(`- create table ga4_connections (- connected_by_user_id text not null,- ga4_account_id text not null,- connected_account_email text- );- insert into ga4_connections values ('old-user', 'old-account', '[email protected]');- `);- const query = new SQLiteSyncDialect().sqlToQuery(expression);- const params = query.params.map((value) => {- if (- value === null ||- typeof value === "string" ||- typeof value === "number" ||- typeof value === "bigint"- ) {- return value;- }- throw new Error("Unexpected SQL parameter type in repository test.");- });- const row: unknown = database- .prepare(`select ${query.sql} as email from ga4_connections`)- .get(...params);- database.close();- if (!row || typeof row !== "object" || !("email" in row)) {- throw new Error("Repository test query did not return an email column.");- }- if (row.email !== null && typeof row.email !== "string") {- throw new Error("Repository test query returned an invalid email value.");- }- return row.email;-}--describe("Ga4ConnectionRepository", () => {- beforeEach(() => {- mocks.connectedAccountEmail = undefined;- mocks.insert.mockImplementation(() => {- const builder = {- values: vi.fn(),- onConflictDoUpdate: vi.fn(),- returning: vi.fn().mockResolvedValue([{ id: "connection-1" }]),- };- builder.values.mockReturnValue(builder);- builder.onConflictDoUpdate.mockImplementation(- (input: { set: { connectedAccountEmail: SQL } }) => {- mocks.connectedAccountEmail = input.set.connectedAccountEmail;- return builder;- },- );- return builder;- });- });-- it.each([- ["old-user", "old-account", "[email protected]"],- ["new-user", "old-account", null],- ["old-user", "new-account", null],- ] as const)(- "preserves a missing email only for the same user and account",- async (connectedByUserId, ga4AccountId, expectedEmail) => {- await Ga4ConnectionRepository.upsert({- projectId: "project-1",- organizationId: "organization-1",- propertyId: "properties/11",- propertyDisplayName: "Site",- propertyTimeZone: "America/New_York",- propertyCurrencyCode: "USD",- connectedByUserId,- ga4AccountId,- connectedAccountEmail: null,- });-- expect(mocks.connectedAccountEmail).toBeDefined();- expect(evaluateConnectedAccountEmail(mocks.connectedAccountEmail!)).toBe(- expectedEmail,- );- },- );-});diff --git a/src/server/features/ga4/services/Ga4MeasurementHealthService.test.ts b/src/server/features/ga4/services/Ga4MeasurementHealthService.test.tsindex e7284f43..9cd75c7c 100644--- a/src/server/features/ga4/services/Ga4MeasurementHealthService.test.ts+++ b/src/server/features/ga4/services/Ga4MeasurementHealthService.test.ts@@ -40,15 +40,7 @@ describe("Ga4MeasurementHealthService", () => {]);mocks.getEnhancedMeasurementSettings.mockResolvedValue({streamEnabled: true,- scrollsEnabled: true,- outboundClicksEnabled: true,siteSearchEnabled: false,- videoEngagementEnabled: true,- fileDownloadsEnabled: true,- pageChangesEnabled: true,- formInteractionsEnabled: false,- searchQueryParameter: "q",- uriQueryParameter: "",});mocks.listKeyEvents.mockResolvedValue([{@@ -65,14 +57,6 @@ describe("Ga4MeasurementHealthService", () => {const result =await Ga4MeasurementHealthService.getMeasurementHealth("project_1");- expect(result.summary).toEqual({- dataStreamCount: 1,- webStreamCount: 1,- keyEventCount: 1,- customDimensionCount: 0,- customMetricCount: 0,- issueCount: 1,- });expect(result.issues).toEqual(["site_search_measurement_disabled"]);expect(result.webStreams[0]).toMatchObject({streamId: "456",@@ -80,12 +64,4 @@ describe("Ga4MeasurementHealthService", () => {enhancedMeasurement: { siteSearchEnabled: false },});});-- it("returns a stable not-connected error before calling Google", async () => {- mocks.getByProjectId.mockResolvedValue(null);- await expect(- Ga4MeasurementHealthService.getMeasurementHealth("project_1"),- ).rejects.toMatchObject({ code: "ga4_not_connected" });- expect(mocks.listDataStreams).not.toHaveBeenCalled();- });});diff --git a/src/server/features/ga4/services/Ga4OrganicOverviewService.test.ts b/src/server/features/ga4/services/Ga4OrganicOverviewService.test.tsindex 25959f5d..acded002 100644--- a/src/server/features/ga4/services/Ga4OrganicOverviewService.test.ts+++ b/src/server/features/ga4/services/Ga4OrganicOverviewService.test.ts@@ -31,6 +31,17 @@ function metricValues(values: string[]) {return values.map((value) => ({ value }));}+// One row of the seven overview metrics, in header order.+const overviewRow = [+ { value: "100" },+ { value: "80" },+ { value: "70" },+ { value: "0.7" },+ { value: "10" },+ { value: "4" },+ { value: "500" },+];+describe("Ga4OrganicOverviewService", () => {beforeEach(() => {mocks.getByProjectId.mockResolvedValue(connection);@@ -41,20 +52,7 @@ describe("Ga4OrganicOverviewService", () => {.mockResolvedValueOnce({dimensionHeaders: [],metricHeaders,- rows: [- {- dimensionValues: [],- metricValues: metricValues([- "100",- "80",- "70",- "0.7",- "10",- "4",- "500",- ]),- },- ],+ rows: [{ dimensionValues: [], metricValues: overviewRow }],rowCount: 1,}).mockResolvedValueOnce({@@ -80,18 +78,7 @@ describe("Ga4OrganicOverviewService", () => {dimensionHeaders: [{ name: "yearWeek" }],metricHeaders,rows: [- {- dimensionValues: [{ value: "202631" }],- metricValues: metricValues([- "100",- "80",- "70",- "0.7",- "10",- "4",- "500",- ]),- },+ { dimensionValues: [{ value: "202631" }], metricValues: overviewRow },],rowCount: 1200,});@@ -124,50 +111,6 @@ describe("Ga4OrganicOverviewService", () => {expect(mocks.runReport).toHaveBeenCalledTimes(3);});- it("treats a headerless previous-period response as empty instead of malformed", async () => {- mocks.runReport- .mockResolvedValueOnce({- dimensionHeaders: [],- metricHeaders,- rows: [- {- dimensionValues: [],- metricValues: metricValues([- "100",- "80",- "70",- "0.7",- "10",- "4",- "500",- ]),- },- ],- rowCount: 1,- })- // GA4 omits headers and rows entirely when the previous-period window- // falls before the property's creation date.- .mockResolvedValueOnce({})- .mockResolvedValueOnce({- dimensionHeaders: [{ name: "date" }],- metricHeaders,- rows: [],- rowCount: 0,- });- const result = await Ga4OrganicOverviewService.getOrganicOverview(- { projectId: "project_1", trend: "daily" },- { now: new Date("2026-08-06T15:00:00Z") },- );- expect(result.previous).toBeNull();- expect(result.comparison.sessions).toEqual({- current: 100,- previous: null,- absoluteChange: null,- percentChange: null,- });- expect(result.diagnostics).toEqual([]);- });-it("flags a material key-event decline with explicit evidence", async () => {const report = (keyEvents: string) => ({dimensionHeaders: [],diff --git a/src/server/features/ga4/services/Ga4ReportEnhancements.test.ts b/src/server/features/ga4/services/Ga4ReportEnhancements.test.tsindex 3b2507e1..de536cdf 100644--- a/src/server/features/ga4/services/Ga4ReportEnhancements.test.ts+++ b/src/server/features/ga4/services/Ga4ReportEnhancements.test.ts@@ -1,11 +1,7 @@import { describe, expect, it } from "vitest";-import { buildGa4ReportRequest } from "./Ga4ReportDefinitions";import {- buildEcommerceActivity,buildReportComparison,buildReportSpecificEnhancements,- buildSiteSearchActivity,- previousPeriod,supportsComparison,} from "./Ga4ReportEnhancements";import type { NormalizedGa4Report } from "./Ga4ReportNormalization";@@ -27,43 +23,7 @@ function report(}describe("GA4 report enhancements", () => {- it("filters key events and optional transaction-only landing pages", () => {- const keyEvents = buildGa4ReportRequest({- kind: "key_events",- startDate: "2026-07-09",- endDate: "2026-08-05",- channel: "organic_search",- limit: 100,- offset: 0,- });- const ecommerce = buildGa4ReportRequest({- kind: "ecommerce_performance",- ecommerceBreakdown: "landing_page",- ecommerceOnlyWithTransactions: true,- startDate: "2026-07-09",- endDate: "2026-08-05",- channel: "organic_search",- limit: 100,- offset: 0,- });- expect(keyEvents.metricFilter).toMatchObject({- filter: {- fieldName: "keyEvents",- numericFilter: { operation: "GREATER_THAN" },- },- });- expect(ecommerce.metricFilter).toMatchObject({- filter: {- fieldName: "transactions",- numericFilter: { operation: "GREATER_THAN" },- },- });- });-it("compares an equal prior period using the union of row keys", () => {- expect(- previousPeriod({ startDate: "2026-07-09", endDate: "2026-08-05" }),- ).toEqual({ startDate: "2026-06-11", endDate: "2026-07-08" });const comparison = buildReportComparison({current: report([{ eventName: "form_submit", keyEvents: 3 }]),previous: report([@@ -169,7 +129,7 @@ describe("GA4 report enhancements", () => {},{ startDate: "2026-07-09", endDate: "2026-08-05" },);- const ecommerce = buildEcommerceActivity(+ const ecommerce = buildReportSpecificEnhancements(report([{ itemName: "Example", itemsViewed: 1 }], 2),{projectId: "project_1",@@ -179,11 +139,14 @@ describe("GA4 report enhancements", () => {{ startDate: "2026-07-09", endDate: "2026-08-05" },);expect(diagnostics.diagnostics).toEqual([]);- expect(ecommerce.status).toBe("unknown");+ expect(ecommerce).toMatchObject({+ diagnostics: [],+ ecommerceActivity: { status: "unknown" },+ });});it("reports scoped ecommerce and site-search activity states", () => {- const ecommerce = buildEcommerceActivity(+ const ecommerce = buildReportSpecificEnhancements(report([]),{projectId: "project_1",@@ -193,20 +156,27 @@ describe("GA4 report enhancements", () => {},{ startDate: "2026-07-09", endDate: "2026-08-05" },);- const search = buildSiteSearchActivity(+ const search = buildReportSpecificEnhancements(report([{ searchTerm: "seo", eventCount: 4 }]),+ { projectId: "project_1", kind: "site_search" },{ startDate: "2026-07-09", endDate: "2026-08-05" },);expect(ecommerce).toMatchObject({- status: "none",- channel: "organic_search",- breakdown: "landing_page",- evidence: { transactions: 0, purchaseRevenue: 0 },+ diagnostics: [{ code: "no_ecommerce_activity" }],+ ecommerceActivity: {+ status: "none",+ channel: "organic_search",+ breakdown: "landing_page",+ evidence: { transactions: 0, purchaseRevenue: 0 },+ },});expect(search).toMatchObject({- status: "detected",- searchTermCount: 1,- searchEventCount: 4,+ diagnostics: [],+ siteSearchActivity: {+ status: "detected",+ searchTermCount: 1,+ searchEventCount: 4,+ },});});});diff --git a/src/server/features/ga4/services/Ga4ReportEnhancements.ts b/src/server/features/ga4/services/Ga4ReportEnhancements.tsindex b9d2274d..d4d74bf5 100644--- a/src/server/features/ga4/services/Ga4ReportEnhancements.ts+++ b/src/server/features/ga4/services/Ga4ReportEnhancements.ts@@ -247,7 +247,7 @@ function activityStatus(return detected ? "detected" : "none";}-export function buildEcommerceActivity(+function buildEcommerceActivity(report: NormalizedGa4Report,input: Ga4ReportInput,dateRange: DateRange,@@ -283,7 +283,7 @@ export function buildEcommerceActivity(};}-export function buildSiteSearchActivity(+function buildSiteSearchActivity(report: NormalizedGa4Report,dateRange: DateRange,) {diff --git a/src/server/features/ga4/services/Ga4ReportingService.comparison.test.ts b/src/server/features/ga4/services/Ga4ReportingService.comparison.test.tsdeleted file mode 100644index 3ca9fc89..00000000--- a/src/server/features/ga4/services/Ga4ReportingService.comparison.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import type {- Ga4RunReportRequest,- Ga4RunReportResponse,-} from "@/server/lib/ga4Client";-import { makeGa4Connection } from "./ga4-test-fixtures";-import { Ga4ReportingService } from "./Ga4ReportingService";--const mocks = vi.hoisted(() => ({- getByProjectId: vi.fn(),- runReport:- vi.fn<(request: Ga4RunReportRequest) => Promise<Ga4RunReportResponse>>(),-}));--vi.mock("@/server/features/ga4/repositories/Ga4ConnectionRepository", () => ({- Ga4ConnectionRepository: { getByProjectId: mocks.getByProjectId },-}));--vi.mock("@/server/lib/ga4Client", () => ({- createGa4DataClient: () => ({ runReport: mocks.runReport }),-}));--const connection = makeGa4Connection();--function noComparison() {- return {- current: null,- previous: null,- absoluteChange: null,- percentChange: null,- };-}--describe("Ga4ReportingService previous-period comparison", () => {- beforeEach(() => {- mocks.getByProjectId.mockResolvedValue(connection);- });-- it("treats a headerless previous-period response as empty instead of malformed", async () => {- mocks.runReport- .mockResolvedValueOnce({- dimensionHeaders: [{ name: "deviceCategory" }],- metricHeaders: [- "activeUsers",- "sessions",- "engagementRate",- "keyEvents",- ].map((name) => ({ name })),- rows: [- {- dimensionValues: [{ value: "mobile" }],- metricValues: ["10", "12", "0.5", "2"].map((value) => ({ value })),- },- ],- rowCount: 1,- })- // GA4 omits headers and rows entirely when the previous-period window- // falls before the property's creation date.- .mockResolvedValueOnce({});-- const result = await Ga4ReportingService.runReport(- {- projectId: "project_1",- kind: "audience_breakdown",- audienceBreakdown: "device",- comparePreviousPeriod: true,- },- { now: new Date("2026-08-06T15:00:00Z") },- );-- expect(result.comparison?.rows).toEqual([- {- dimensions: { deviceCategory: "mobile" },- metrics: {- activeUsers: { ...noComparison(), current: 10 },- sessions: { ...noComparison(), current: 12 },- engagementRate: { ...noComparison(), current: 0.5 },- keyEvents: { ...noComparison(), current: 2 },- },- },- ]);- expect(result.comparison?.coverage.previous).toEqual({- fetchedRowCount: 0,- totalRowCount: 0,- });- });-});diff --git a/src/server/features/ga4/services/Ga4ReportingService.test.ts b/src/server/features/ga4/services/Ga4ReportingService.test.tsindex b7455fe7..e184b254 100644--- a/src/server/features/ga4/services/Ga4ReportingService.test.ts+++ b/src/server/features/ga4/services/Ga4ReportingService.test.ts@@ -62,6 +62,13 @@ function acquisitionResponse(};}+const noComparison = {+ current: null,+ previous: null,+ absoluteChange: null,+ percentChange: null,+};+describe("Ga4ReportingService", () => {beforeEach(() => {mocks.getByProjectId.mockResolvedValue(connection);@@ -175,42 +182,6 @@ describe("Ga4ReportingService", () => {expect(result.rows[0]?.purchaseRevenue).toBeNull();});- it("uses the all-channel page report and optional date dimension", async () => {- mocks.runReport.mockResolvedValue({- dimensionHeaders: [- { name: "hostName" },- { name: "pagePath" },- { name: "date" },- ],- metricHeaders: [- "screenPageViews",- "activeUsers",- "userEngagementDuration",- "keyEvents",- ].map((name) => ({ name })),- rowCount: 0,- });- await Ga4ReportingService.runReport(- {- projectId: "project_1",- kind: "page_performance",- channel: "all",- includeDate: true,- },- { now: new Date("2026-08-06T15:00:00Z") },- );- expect(mocks.runReport).toHaveBeenCalledWith(- expect.objectContaining({- dimensions: [- { name: "hostName" },- { name: "pagePath" },- { name: "date" },- ],- dimensionFilter: undefined,- }),- );- });-it("returns stable connection and quota errors", async () => {mocks.getByProjectId.mockResolvedValueOnce(null);await expect(@@ -253,65 +224,14 @@ describe("Ga4ReportingService", () => {expect(mocks.runReport).not.toHaveBeenCalled();});+ // The plain metric/dimension lists restate Ga4ReportDefinitions; these rows+ // cover the non-obvious request shapes each report kind adds.it.each([- [- "traffic_acquisition",- { acquisitionBreakdown: "source_medium", channel: "all" },- "sessionSourceMedium",- [- "sessions",- "activeUsers",- "engagedSessions",- "engagementRate",- "keyEvents",- "transactions",- "purchaseRevenue",- ],- ],- [- "ecommerce_performance",- { ecommerceBreakdown: "item", channel: "organic_search" },- "itemName",- ["itemsViewed", "itemsAddedToCart", "itemsPurchased", "itemRevenue"],- ],- [- "site_search",- { channel: "all" },- "searchTerm",- [- "eventCount",- "activeUsers",- "sessions",- "engagedSessions",- "engagementRate",- ],- ],- [- "audience_breakdown",- { audienceBreakdown: "new_vs_returning", channel: "organic_search" },- "newVsReturning",- ["activeUsers", "sessions", "engagementRate", "keyEvents"],- ],- ] as const)(- "builds the fixed %s report",- async (kind, options, dimension, metrics) => {- mocks.runReport.mockResolvedValue({- dimensionHeaders:- kind === "ecommerce_performance"- ? [{ name: "itemName" }, { name: "itemId" }]- : [{ name: dimension }],- metricHeaders: metrics.map((name) => ({ name })),- rowCount: 0,- });- await Ga4ReportingService.runReport(- { projectId: "project_1", kind, ...options },- { now: new Date("2026-08-06T15:00:00Z") },- );- const request = mocks.runReport.mock.calls[0]?.[0];- expect(request?.dimensions[0]?.name).toBe(dimension);- expect(request?.metrics).toEqual(metrics.map((name) => ({ name })));- if (kind === "site_search") {- expect(request?.dimensionFilter).toEqual({+ {+ name: "site_search keeps only real search terms",+ input: { kind: "site_search", channel: "all" },+ request: {+ dimensionFilter: {andGroup: {expressions: [{@@ -327,19 +247,115 @@ describe("Ga4ReportingService", () => {notExpression: {filter: {fieldName: "searchTerm",- stringFilter: {- matchType: "EXACT",- value: "(not set)",- },+ stringFilter: { matchType: "EXACT", value: "(not set)" },},},},],},- });- }+ },+ },},- );+ {+ name: "page_performance over all channels adds the date dimension",+ input: { kind: "page_performance", channel: "all", includeDate: true },+ request: {+ dimensions: [+ { name: "hostName" },+ { name: "pagePath" },+ { name: "date" },+ ],+ dimensionFilter: undefined,+ },+ },+ {+ name: "key_events drops events that never fired",+ input: { kind: "key_events", channel: "organic_search" },+ request: {+ metricFilter: {+ filter: {+ fieldName: "keyEvents",+ numericFilter: { operation: "GREATER_THAN" },+ },+ },+ },+ },+ {+ name: "ecommerce landing pages can be limited to those with transactions",+ input: {+ kind: "ecommerce_performance",+ ecommerceBreakdown: "landing_page",+ ecommerceOnlyWithTransactions: true,+ channel: "organic_search",+ },+ request: {+ dimensions: [{ name: "hostName" }, { name: "landingPage" }],+ metricFilter: {+ filter: {+ fieldName: "transactions",+ numericFilter: { operation: "GREATER_THAN" },+ },+ },+ },+ },+ ] as const)("builds the request: $name", async ({ input, request }) => {+ // A headerless response is a legitimately empty report.+ mocks.runReport.mockResolvedValue({});+ await Ga4ReportingService.runReport(+ { projectId: "project_1", ...input },+ { now: new Date("2026-08-06T15:00:00Z") },+ );+ expect(mocks.runReport.mock.calls[0]?.[0]).toMatchObject(request);+ });++ it("treats a headerless previous-period response as empty instead of malformed", async () => {+ mocks.runReport+ .mockResolvedValueOnce({+ dimensionHeaders: [{ name: "deviceCategory" }],+ metricHeaders: [+ "activeUsers",+ "sessions",+ "engagementRate",+ "keyEvents",+ ].map((name) => ({ name })),+ rows: [+ {+ dimensionValues: [{ value: "mobile" }],+ metricValues: ["10", "12", "0.5", "2"].map((value) => ({ value })),+ },+ ],+ rowCount: 1,+ })+ // GA4 omits headers and rows entirely when the previous-period window+ // falls before the property's creation date.+ .mockResolvedValueOnce({});++ const result = await Ga4ReportingService.runReport(+ {+ projectId: "project_1",+ kind: "audience_breakdown",+ audienceBreakdown: "device",+ comparePreviousPeriod: true,+ },+ { now: new Date("2026-08-06T15:00:00Z") },+ );++ expect(result.comparison?.rows).toEqual([+ {+ dimensions: { deviceCategory: "mobile" },+ metrics: {+ activeUsers: { ...noComparison, current: 10 },+ sessions: { ...noComparison, current: 12 },+ engagementRate: { ...noComparison, current: 0.5 },+ keyEvents: { ...noComparison, current: 2 },+ },+ },+ ]);+ expect(result.comparison?.coverage.previous).toEqual({+ fetchedRowCount: 0,+ totalRowCount: 0,+ });+ });describe("diagnostic pagination", () => {it.each([diff --git a/src/server/features/ga4/services/Ga4Service.test.ts b/src/server/features/ga4/services/Ga4Service.test.tsindex 756179b8..7f0cc85f 100644--- a/src/server/features/ga4/services/Ga4Service.test.ts+++ b/src/server/features/ga4/services/Ga4Service.test.ts@@ -1,4 +1,3 @@-import type { SQL } from "drizzle-orm";import { beforeEach, describe, expect, it, vi } from "vitest";import { Ga4AdminApiError, Ga4TokenError } from "@/server/lib/ga4Errors";import { Ga4Service } from "./Ga4Service";@@ -10,9 +9,6 @@ const mocks = vi.hoisted(() => {const listProperties = vi.fn();const getProperty = vi.fn();const getUserInfoEmail = vi.fn();- const deleteWhere = vi- .fn<(condition: SQL) => Promise<void>>()- .mockResolvedValue(undefined);return {state,listProperties,@@ -33,18 +29,13 @@ const mocks = vi.hoisted(() => {}),})),})),- dbDelete: vi.fn(() => ({ where: deleteWhere })),- deleteWhere,upsert: vi.fn(),getByProjectId: vi.fn(),- deleteByProjectId: vi.fn(),};});vi.mock("cloudflare:workers", () => ({ env: {} }));-vi.mock("@/db", () => ({- db: { select: mocks.dbSelect, delete: mocks.dbDelete },-}));+vi.mock("@/db", () => ({ db: { select: mocks.dbSelect } }));vi.mock("@/server/lib/ga4Client", () => ({createGa4AdminClient: mocks.createGa4AdminClient,}));@@ -52,14 +43,12 @@ vi.mock("@/server/features/ga4/repositories/Ga4ConnectionRepository", () => ({Ga4ConnectionRepository: {upsert: mocks.upsert,getByProjectId: mocks.getByProjectId,- deleteByProjectId: mocks.deleteByProjectId,},}));describe("Ga4Service", () => {beforeEach(() => {mocks.state.grants = [{ id: "grant-a", accountId: "sub-a" }];- mocks.deleteByProjectId.mockResolvedValue(undefined);});it("verifies a freshly discovered property before persisting metadata", async () => {@@ -78,14 +67,15 @@ describe("Ga4Service", () => {});mocks.getUserInfoEmail.mockResolvedValue("[email protected]");mocks.upsert.mockResolvedValue({ propertyId: "properties/11" });-- await Ga4Service.setProperty({+ const input = {projectId: "p1",organizationId: "org1",propertyId: "properties/11",accountId: "sub-a",userId: "u1",- });+ };++ await Ga4Service.setProperty(input);expect(mocks.upsert).toHaveBeenCalledWith({projectId: "p1",@@ -98,40 +88,12 @@ describe("Ga4Service", () => {ga4AccountId: "sub-a",connectedAccountEmail: "[email protected]",});- });- it("passes a null email through when userinfo fails on an account switch", async () => {- mocks.state.grants = [{ id: "grant-b", accountId: "sub-b" }];- mocks.listProperties.mockResolvedValue([- {- propertyId: "properties/22",- displayName: "Site B",- accountDisplayName: "Client",- },- ]);- mocks.getProperty.mockResolvedValue({- name: "properties/22",- displayName: "Site B",- timeZone: "America/Los_Angeles",- currencyCode: "USD",- });+ // A userinfo failure is non-fatal: the email is passed through as null.mocks.getUserInfoEmail.mockRejectedValue(new Error("userinfo unavailable"));- mocks.upsert.mockResolvedValue({ propertyId: "properties/22" });-- await Ga4Service.setProperty({- projectId: "p1",- organizationId: "org1",- propertyId: "properties/22",- accountId: "sub-b",- userId: "u2",- });-- expect(mocks.upsert).toHaveBeenCalledWith(- expect.objectContaining({- connectedByUserId: "u2",- ga4AccountId: "sub-b",- connectedAccountEmail: null,- }),+ await Ga4Service.setProperty(input);+ expect(mocks.upsert).toHaveBeenLastCalledWith(+ expect.objectContaining({ connectedAccountEmail: null }),);});@@ -198,11 +160,4 @@ describe("Ga4Service", () => {});consoleError.mockRestore();});-- it("disconnects only this project and leaves linked Google accounts intact", async () => {- mocks.dbDelete.mockClear();- await Ga4Service.disconnect({ projectId: "p1" });- expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");- expect(mocks.dbDelete).not.toHaveBeenCalled();- });});diff --git a/src/server/features/ga4/services/SearchOpportunityService.test.ts b/src/server/features/ga4/services/SearchOpportunityService.test.tsindex 4795e6df..1b2e2719 100644--- a/src/server/features/ga4/services/SearchOpportunityService.test.ts+++ b/src/server/features/ga4/services/SearchOpportunityService.test.ts@@ -1,5 +1,4 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { GscNotConnectedError } from "@/server/lib/gscErrors";import { makeGa4ReportResult } from "./ga4-test-fixtures";import { SearchOpportunityService } from "./SearchOpportunityService";@@ -25,21 +24,6 @@ vi.mock("@/server/features/ga4/services/Ga4ReportingService", () => ({}));const ga4Result = makeGa4ReportResult({- status: "ok" as const,- source: {- provider: "google_analytics" as const,- propertyId: "properties/123",- propertyDisplayName: "Example",- },- request: {- requestedDateRange: { startDate: "2026-07-07", endDate: "2026-08-03" },- resolvedDateRange: { startDate: "2026-07-07", endDate: "2026-08-03" },- propertyTimeZone: "America/New_York",- currencyCode: "USD",- channel: "organic_search" as const,- limit: 1_000,- offset: 0,- },rows: [{hostName: "example.com",@@ -68,17 +52,6 @@ const ga4Result = makeGa4ReportResult({],rowCount: 2,totalRowCount: 2,- pageInfo: { offset: 0, limit: 1_000, hasMore: false, nextOffset: null },- reportMetadata: {- dataLossFromOtherRow: false,- subjectToThresholding: false,- sampling: [],- restrictedMetrics: [],- emptyReason: null,- hasLimitedData: false,- },- quota: null,- warnings: [],});describe("SearchOpportunityService", () => {@@ -226,13 +199,4 @@ describe("SearchOpportunityService", () => {}),);});-- it("fails before querying GA4 when Search Console is not connected", async () => {- mocks.getGscConnection.mockResolvedValue(null);- await expect(- SearchOpportunityService.getOpportunities({ projectId: "project_1" }),- ).rejects.toBeInstanceOf(GscNotConnectedError);- expect(mocks.getPerformance).not.toHaveBeenCalled();- expect(mocks.runGa4Report).not.toHaveBeenCalled();- });});diff --git a/src/server/features/google/GoogleAccountService.test.ts b/src/server/features/google/GoogleAccountService.test.tsindex 94b56ed0..178a1bf2 100644--- a/src/server/features/google/GoogleAccountService.test.ts+++ b/src/server/features/google/GoogleAccountService.test.ts@@ -128,23 +128,6 @@ for (const provider of ["gsc", "ga4"] as const) {const table = provider === "gsc" ? "gsc_connections" : "ga4_connections";const input = { provider, accountId: "google-a", userId: "u1" };- it("deletes the authorization row so another OpenSEO user can claim the identity", async () => {- await grant(providerId);- await mapping(provider, "p1");- expect((await rows("account"))[0]?.user_id).toBe("u1");- await service.remove(input);- expect(await rows("account")).toEqual([]);- expect(await rows(table)).toEqual([]);- // Better Auth's link callback looks up this pair across all users.- const existing = await client.execute({- sql: "SELECT user_id FROM account WHERE provider_id = ? AND account_id = ?",- args: [providerId, "google-a"],- });- expect(existing.rows).toEqual([]);- await grant(providerId, "google-a", "u2");- expect((await rows("account"))[0]?.user_id).toBe("u2");- });-it("removes all dependent mappings including archived and other-workspace projects", async () => {await grant(providerId);await mapping(provider, "p1");@@ -184,16 +167,6 @@ for (const provider of ["gsc", "ga4"] as const) {expect(await rows(table)).toHaveLength(1);});- it("a repeated old-user removal does not delete the new owner's grant", async () => {- await grant(providerId);- await service.remove(input);- await grant(providerId, "google-a", "u2");- await mapping(provider, "p1", "google-a", "u2");- await service.remove(input);- expect((await rows("account"))[0]?.user_id).toBe("u2");- expect(await rows(table)).toHaveLength(1);- });-it("rolls project deletion back if deleting the authorization fails", async () => {await grant(providerId);await mapping(provider, "p1");@@ -223,6 +196,35 @@ it("includes legacy GSC mappings in removal without touching another user's lega]);});+it.each(["same-account", "other-account", "other-user"] as const)(+ "GA4 preserves a missing email only for the same connection identity: %s",+ async (change) => {+ const { Ga4ConnectionRepository } =+ await import("@/server/features/ga4/repositories/Ga4ConnectionRepository");+ const base = {+ projectId: "p1",+ organizationId: "org1",+ propertyId: "properties/11",+ propertyDisplayName: "Site",+ propertyTimeZone: "America/New_York",+ propertyCurrencyCode: "USD",+ connectedByUserId: "u1",+ ga4AccountId: "google-a",+ connectedAccountEmail: "[email protected]",+ };+ await Ga4ConnectionRepository.upsert(base);+ const saved = await Ga4ConnectionRepository.upsert({+ ...base,+ connectedByUserId: change === "other-user" ? "u2" : "u1",+ ga4AccountId: change === "other-account" ? "google-b" : "google-a",+ connectedAccountEmail: null,+ });+ expect(saved.connectedAccountEmail).toBe(+ change === "same-account" ? "[email protected]" : null,+ );+ },+);+it.each(["same-account", "other-account", "other-user"] as const)("GSC preserves a missing email only for the same connection identity: %s",async (change) => {diff --git a/src/server/features/gsc/searchAnalytics.test.ts b/src/server/features/gsc/searchAnalytics.test.tsindex 2785826f..7ca3aef1 100644--- a/src/server/features/gsc/searchAnalytics.test.ts+++ b/src/server/features/gsc/searchAnalytics.test.ts@@ -7,11 +7,6 @@ import {const TODAY = new Date("2026-05-28T00:00:00Z");describe("resolveDateRange", () => {- it("ends convenience ranges 3 days back for GSC data lag", () => {- const { endDate } = resolveDateRange({ dateRange: "last_28_days" }, TODAY);- expect(endDate).toBe("2026-05-25");- });-it("computes a 28-day window from the lagged end", () => {const { startDate, endDate } = resolveDateRange({ dateRange: "last_28_days" },@@ -30,39 +25,42 @@ describe("resolveDateRange", () => {expect(startDate).toBe("2025-01-28");});- it("passes explicit dates through, clamping start to the floor", () => {- const { startDate, endDate } = resolveDateRange(- { startDate: "2020-01-01", endDate: "2026-05-01" },- TODAY,- );- expect(startDate).toBe("2025-01-28"); // clamped- expect(endDate).toBe("2026-05-01");- });-- it("leaves an in-range explicit start untouched", () => {- const { startDate } = resolveDateRange(- { startDate: "2026-01-01", endDate: "2026-05-01" },- TODAY,- );- expect(startDate).toBe("2026-01-01");- });-- it("subtracts calendar months without overflowing short months", () => {- const { startDate, endDate } = resolveDateRange(- { dateRange: "last_3_months" },- new Date("2026-06-03T00:00:00Z"),- );- expect(startDate).toBe("2026-02-28");- expect(endDate).toBe("2026-05-31");+ it("passes explicit dates through, clamping only a start below the floor", () => {+ expect(+ resolveDateRange(+ { startDate: "2020-01-01", endDate: "2026-05-01" },+ TODAY,+ ),+ ).toEqual({ startDate: "2025-01-28", endDate: "2026-05-01" });+ expect(+ resolveDateRange(+ { startDate: "2026-01-01", endDate: "2026-05-01" },+ TODAY,+ ).startDate,+ ).toBe("2026-01-01");});- it("clamps the 16-month floor to the last valid day of a short month", () => {- const { startDate } = resolveDateRange(- { dateRange: "last_16_months" },- new Date("2026-06-30T00:00:00Z"),- );- expect(startDate).toBe("2025-02-28");- });+ it.each([+ {+ dateRange: "last_3_months" as const,+ today: "2026-06-03",+ startDate: "2026-02-28",+ endDate: "2026-05-31",+ },+ {+ dateRange: "last_16_months" as const,+ today: "2026-06-30",+ startDate: "2025-02-28",+ endDate: "2026-06-27",+ },+ ])(+ "subtracts calendar months without overflowing short months ($dateRange from $today)",+ ({ dateRange, today, startDate, endDate }) => {+ expect(+ resolveDateRange({ dateRange }, new Date(`${today}T00:00:00Z`)),+ ).toEqual({ startDate, endDate });+ },+ );});describe("buildSearchAnalyticsRequest", () => {@@ -97,19 +95,6 @@ describe("buildSearchAnalyticsRequest", () => {]);});- it("omits dimensionFilterGroups when no filters are given", () => {- const request = buildSearchAnalyticsRequest({ projectId: "p1" }, TODAY);- expect(request.dimensionFilterGroups).toBeUndefined();- });-- it("defaults dimensions, type, dataState, and rowLimit", () => {- const request = buildSearchAnalyticsRequest({ projectId: "p1" }, TODAY);- expect(request.dimensions).toEqual(["query"]);- expect(request.type).toBe("web");- expect(request.dataState).toBe("all");- expect(request.rowLimit).toBe(250);- });-it("clamps rowLimit to the 1000 ceiling", () => {expect(buildSearchAnalyticsRequest({ projectId: "p1", rowLimit: 99999 }, TODAY)@@ -120,14 +105,4 @@ describe("buildSearchAnalyticsRequest", () => {.rowLimit,).toBe(1);});-- it("only includes startRow when positive", () => {- expect(- buildSearchAnalyticsRequest({ projectId: "p1" }, TODAY).startRow,- ).toBeUndefined();- expect(- buildSearchAnalyticsRequest({ projectId: "p1", startRow: 1000 }, TODAY)- .startRow,- ).toBe(1000);- });});diff --git a/src/server/features/gsc/searchPerformanceReport.test.ts b/src/server/features/gsc/searchPerformanceReport.test.tsindex 28b37301..f8e211cf 100644--- a/src/server/features/gsc/searchPerformanceReport.test.ts+++ b/src/server/features/gsc/searchPerformanceReport.test.ts@@ -3,7 +3,6 @@ import {buildStrikingDistanceRows,previousPeriod,sumSearchTotals,- toDimensionRows,} from "@/server/features/gsc/searchPerformanceReport";describe("sumSearchTotals", () => {@@ -29,30 +28,6 @@ describe("sumSearchTotals", () => {});});-describe("toDimensionRows", () => {- it("keeps the first key and drops keyless rows", () => {- const rows = toDimensionRows([- {- keys: ["magento agency"],- clicks: 3,- impressions: 40,- ctr: 0.075,- position: 6.2,- },- { clicks: 1, impressions: 5, ctr: 0.2, position: 1 },- ]);- expect(rows).toEqual([- {- key: "magento agency",- clicks: 3,- impressions: 40,- ctr: 0.075,- position: 6.2,- },- ]);- });-});-const row = (query: string, position: number, impressions: number) => ({keys: [query, `https://example.com/${query}`],clicks: 1,@@ -70,36 +45,21 @@ const pageRow = () => ({ keys: [query, page], clicks: 1, impressions, ctr: 0.01, position });describe("buildStrikingDistanceRows", () => {- it("keeps only positions 5..20 and sorts by impressions desc", () => {+ it("keeps positions 5..20 inclusive and sorts by impressions desc", () => {const rows = buildStrikingDistanceRows([row("top-spot", 2, 900),+ row("low-edge", 5, 10),row("close", 6.4, 100),row("closer", 11, 400),+ row("high-edge", 20, 20),row("page-3", 24, 800),]);- expect(rows.map((r) => r.query)).toEqual(["closer", "close"]);- });-- it("includes the boundary positions and respects the limit", () => {- const rows = buildStrikingDistanceRows(- [row("low-edge", 5, 10), row("high-edge", 20, 20)],- 1,- );- expect(rows).toHaveLength(1);- expect(rows[0].query).toBe("high-edge");- });-- it("drops rows without both query and page keys", () => {- const rows = buildStrikingDistanceRows([- {- keys: ["only-query"],- clicks: 1,- impressions: 50,- ctr: 0.02,- position: 8,- },+ expect(rows.map((r) => r.query)).toEqual([+ "closer",+ "close",+ "high-edge",+ "low-edge",]);- expect(rows).toHaveLength(0);});it("drops a query whose top page already ranks above the band", () => {@@ -124,17 +84,16 @@ describe("buildStrikingDistanceRows", () => {});describe("previousPeriod", () => {- it("returns the same-length window ending the day before the start", () => {- expect(previousPeriod("2026-06-01", "2026-06-28")).toEqual({- startDate: "2026-05-04",- endDate: "2026-05-31",- });- });-- it("handles a single-day range", () => {- expect(previousPeriod("2026-06-10", "2026-06-10")).toEqual({- startDate: "2026-06-09",- endDate: "2026-06-09",- });- });+ it.each([+ ["2026-06-01", "2026-06-28", "2026-05-04", "2026-05-31"],+ ["2026-06-10", "2026-06-10", "2026-06-09", "2026-06-09"],+ ])(+ "returns the same-length window ending the day before %s..%s",+ (startDate, endDate, prevStart, prevEnd) => {+ expect(previousPeriod(startDate, endDate)).toEqual({+ startDate: prevStart,+ endDate: prevEnd,+ });+ },+ );});diff --git a/src/server/features/gsc/services/GscService.test.ts b/src/server/features/gsc/services/GscService.test.tsindex 603e3897..5c6b8721 100644--- a/src/server/features/gsc/services/GscService.test.ts+++ b/src/server/features/gsc/services/GscService.test.ts@@ -1,5 +1,3 @@-/* eslint-disable max-lines */-import type { SQL } from "drizzle-orm";import { beforeEach, describe, expect, it, vi } from "vitest";import { GscApiError, GscTokenError } from "@/server/lib/gscErrors";import { GscService } from "./GscService";@@ -15,9 +13,6 @@ const mocks = vi.hoisted(() => {vi.fn<(opts: GscClientOptions) => Promise<string | null>>();const querySearchAnalytics =vi.fn<(opts: GscClientOptions) => Promise<never[]>>();- const deleteWhere = vi- .fn<(condition: SQL) => Promise<void>>()- .mockResolvedValue(undefined);const dbSelect = vi.fn(() => ({from: vi.fn(() => ({where: vi.fn(() => {@@ -32,8 +27,6 @@ const mocks = vi.hoisted(() => {return {state,dbSelect,- deleteWhere,- dbDelete: vi.fn(() => ({ where: deleteWhere })),listSites,getUserInfoEmail,querySearchAnalytics,@@ -44,13 +37,12 @@ const mocks = vi.hoisted(() => {})),upsert: vi.fn(),getByProjectId: vi.fn(),- deleteByProjectId: vi.fn(),};});vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/db", () => ({- db: { select: mocks.dbSelect, delete: mocks.dbDelete },+ db: { select: mocks.dbSelect },}));vi.mock("@/server/lib/gscClient", () => ({createGscClient: mocks.createGscClient,@@ -59,7 +51,6 @@ vi.mock("@/server/features/gsc/repositories/GscConnectionRepository", () => ({GscConnectionRepository: {upsert: mocks.upsert,getByProjectId: mocks.getByProjectId,- deleteByProjectId: mocks.deleteByProjectId,},}));@@ -73,10 +64,6 @@ const baseInput = {describe("GscService.setSite", () => {beforeEach(() => {mocks.state.selectRows = [{ id: "grant-a", accountId: "sub-a" }];- mocks.listSites.mockReset();- mocks.getUserInfoEmail.mockReset();- mocks.createGscClient.mockClear();- mocks.upsert.mockReset();});it("upserts a verified property with the selected grant and userinfo email", async () => {@@ -101,29 +88,13 @@ describe("GscService.setSite", () => {connectedAccountEmail: "[email protected]",}),);- });- it("re-saves with a null email when userinfo is unavailable", async () => {- mocks.listSites.mockResolvedValue([- { siteUrl: "https://x/", permissionLevel: "siteOwner" },- ]);+ // A userinfo failure is non-fatal: the email is passed through as null.mocks.getUserInfoEmail.mockRejectedValue(new Error("userinfo unavailable"));- mocks.upsert.mockResolvedValue({- siteUrl: "https://x/",- connectedAccountEmail: "[email protected]",- });-- const result = await GscService.setSite({- ...baseInput,- siteUrl: "https://x/",- });-- expect(mocks.upsert).toHaveBeenCalledWith(+ await GscService.setSite({ ...baseInput, siteUrl: "https://x/" });+ expect(mocks.upsert).toHaveBeenLastCalledWith(expect.objectContaining({ connectedAccountEmail: null }),);- expect(result).toMatchObject({- connectedAccountEmail: "[email protected]",- });});it("rejects a Google sub that is not one of the caller's grants", async () => {@@ -167,71 +138,51 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {{ id: "grant-a", accountId: "sub-a" },{ id: "grant-b", accountId: "sub-b" },];- mocks.listSites.mockReset();- mocks.getUserInfoEmail.mockReset();- mocks.createGscClient.mockClear();- mocks.dbDelete.mockClear();});- it("lists grants independently and never deletes a dead grant", async () => {- mocks.getUserInfoEmail.mockImplementation(- async ({ gscAccountId }: { gscAccountId?: string }) =>- `${gscAccountId}@example.com`,- );- mocks.listSites.mockImplementation(- async ({ gscAccountId }: { gscAccountId?: string }) => {- if (gscAccountId === "sub-b") throw new GscTokenError("revoked");- return [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }];- },- );-- await expect(- GscService.listSitesForUserWithGrantStatus("u1"),- ).resolves.toEqual({- accounts: [- {- accountId: "sub-a",- email: "[email protected]",- requiresReconnect: false,- propertiesUnavailable: false,- sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],- },- {- accountId: "sub-b",- email: null,- requiresReconnect: true,- propertiesUnavailable: false,- sites: [],+ it.each([+ ["a revoked token", new GscTokenError("revoked")],+ ["a 403", new GscApiError(403, "Search Console denied access")],+ ])(+ "marks only the grant that failed with %s for reconnect",+ async (_label, failure) => {+ mocks.getUserInfoEmail.mockImplementation(+ async ({ gscAccountId }: { gscAccountId?: string }) =>+ `${gscAccountId}@example.com`,+ );+ mocks.listSites.mockImplementation(+ async ({ gscAccountId }: { gscAccountId?: string }) => {+ if (gscAccountId === "sub-b") throw failure;+ return [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }];},- ],- });- expect(mocks.createGscClient).toHaveBeenCalledTimes(2);- expect(mocks.getUserInfoEmail).not.toHaveBeenCalledWith(- expect.objectContaining({ gscAccountId: "sub-b" }),- );- expect(mocks.dbDelete).not.toHaveBeenCalled();- });-- it("keeps healthy accounts usable when another account hits a temporary API error", async () => {- mocks.getUserInfoEmail.mockResolvedValue("[email protected]");- mocks.listSites.mockImplementation(async ({ gscAccountId }) => {- if (gscAccountId === "sub-b")- throw new GscApiError(503, "Temporarily unavailable");- return [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }];- });- const result = await GscService.listSitesForUserWithGrantStatus("u1");- expect(result.accounts[0]).toMatchObject({- requiresReconnect: false,- propertiesUnavailable: false,- sites: [{ siteUrl: "https://x/" }],- });- expect(result.accounts[1]).toMatchObject({- requiresReconnect: false,- propertiesUnavailable: true,- sites: [],- });- expect(mocks.dbDelete).not.toHaveBeenCalled();- });+ );++ await expect(+ GscService.listSitesForUserWithGrantStatus("u1"),+ ).resolves.toEqual({+ accounts: [+ {+ accountId: "sub-a",+ email: "[email protected]",+ requiresReconnect: false,+ propertiesUnavailable: false,+ sites: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],+ },+ {+ accountId: "sub-b",+ email: null,+ requiresReconnect: true,+ propertiesUnavailable: false,+ sites: [],+ },+ ],+ });+ expect(mocks.createGscClient).toHaveBeenCalledTimes(2);+ expect(mocks.getUserInfoEmail).not.toHaveBeenCalledWith(+ expect.objectContaining({ gscAccountId: "sub-b" }),+ );+ },+ );it("keeps userinfo failures non-fatal", async () => {mocks.state.selectRows = [{ id: "grant-a", accountId: "sub-a" }];@@ -255,30 +206,6 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {});});- it("marks a grant for reconnect on a GSC 403 without deleting it", async () => {- mocks.state.selectRows = [{ id: "grant-a", accountId: "sub-a" }];- mocks.getUserInfoEmail.mockResolvedValue("[email protected]");- mocks.listSites.mockRejectedValue(- new GscApiError(403, "Search Console denied access"),- );-- await expect(- GscService.listSitesForUserWithGrantStatus("u1"),- ).resolves.toEqual({- accounts: [- {- accountId: "sub-a",- email: null,- requiresReconnect: true,- propertiesUnavailable: false,- sites: [],- },- ],- });- expect(mocks.getUserInfoEmail).not.toHaveBeenCalled();- expect(mocks.dbDelete).not.toHaveBeenCalled();- });-it("keeps non-auth GSC API errors reportable", async () => {mocks.getUserInfoEmail.mockImplementation(async ({ gscAccountId }: { gscAccountId?: string }) =>@@ -320,64 +247,38 @@ describe("GscService.listSitesForUserWithGrantStatus", () => {"sub-b",rateLimit,);- expect(mocks.dbDelete).not.toHaveBeenCalled();consoleError.mockRestore();});});describe("GscService.getPerformance", () => {beforeEach(() => {- mocks.getByProjectId.mockReset();- mocks.querySearchAnalytics.mockReset().mockResolvedValue([]);- mocks.createGscClient.mockClear();+ mocks.querySearchAnalytics.mockResolvedValue([]);});- it("uses the grant stored on the project connection", async () => {- mocks.getByProjectId.mockResolvedValue({- connectedByUserId: "u1",- connectedAccountEmail: "[email protected]",- gscAccountId: "sub-a",- siteUrl: "https://x/",- });-- await GscService.getPerformance({- projectId: "p1",- startDate: "2026-01-01",- endDate: "2026-01-31",- });-- expect(mocks.createGscClient).toHaveBeenCalledWith({- userId: "u1",- gscAccountId: "sub-a",- });- });-- it("passes undefined for the legacy null-account fallback", async () => {- mocks.getByProjectId.mockResolvedValue({- connectedByUserId: "u1",- connectedAccountEmail: null,- gscAccountId: null,- siteUrl: "https://x/",- });-- await GscService.getPerformance({- projectId: "p1",- startDate: "2026-01-01",- endDate: "2026-01-31",- });-- expect(mocks.createGscClient).toHaveBeenCalledWith({- userId: "u1",- gscAccountId: undefined,- });- });-});+ it.each([+ ["sub-a", "sub-a"],+ [null, undefined],+ ])(+ "uses the grant stored on the project connection (%s)",+ async (stored, forwarded) => {+ mocks.getByProjectId.mockResolvedValue({+ connectedByUserId: "u1",+ connectedAccountEmail: null,+ gscAccountId: stored,+ siteUrl: "https://x/",+ });-describe("GscService.disconnect", () => {- it("disconnects only this project and leaves linked Google accounts intact", async () => {- mocks.dbDelete.mockClear();- await GscService.disconnect({ projectId: "p1" });- expect(mocks.deleteByProjectId).toHaveBeenCalledWith("p1");- expect(mocks.dbDelete).not.toHaveBeenCalled();- });+ await GscService.getPerformance({+ projectId: "p1",+ startDate: "2026-01-01",+ endDate: "2026-01-31",+ });++ expect(mocks.createGscClient).toHaveBeenCalledWith({+ userId: "u1",+ gscAccountId: forwarded,+ });+ },+ );});diff --git a/src/server/features/keywords/services/research/helpers.test.ts b/src/server/features/keywords/services/research/helpers.test.tsindex fbbd2423..2f2d1c9c 100644--- a/src/server/features/keywords/services/research/helpers.test.ts+++ b/src/server/features/keywords/services/research/helpers.test.ts@@ -1,10 +1,7 @@import { describe, expect, it } from "vitest";import { interleaveRows, type EnrichedKeyword } from "./helpers";-const row = (- keyword: string,- overrides: Partial<EnrichedKeyword> = {},-): EnrichedKeyword => ({+const row = (keyword: string): EnrichedKeyword => ({keyword,searchVolume: 1000,trend: [{ year: 2026, month: 7, searchVolume: 1000 }],@@ -12,21 +9,26 @@ const row = (competition: 0.4,keywordDifficulty: 20,intent: "informational",- ...overrides,});describe("interleaveRows", () => {- it("alternates sources, dedupes by keyword, and respects the limit", () => {- const rows = interleaveRows(- [row("a"), row("b"), row("c")],- [row("x"), row("a"), row("y")],- 4,- );- expect(rows.map((r) => r.keyword)).toEqual(["a", "x", "b", "c"]);- });-- it("drains the longer source when the other runs out", () => {- const rows = interleaveRows([row("a")], [row("x"), row("y"), row("z")], 10);- expect(rows.map((r) => r.keyword)).toEqual(["a", "x", "y", "z"]);+ it.each([+ {+ name: "alternates sources, dedupes by keyword, and respects the limit",+ first: ["a", "b", "c"],+ second: ["x", "a", "y"],+ limit: 4,+ expected: ["a", "x", "b", "c"],+ },+ {+ name: "drains the longer source when the other runs out",+ first: ["a"],+ second: ["x", "y", "z"],+ limit: 10,+ expected: ["a", "x", "y", "z"],+ },+ ])("$name", ({ first, second, limit, expected }) => {+ const rows = interleaveRows(first.map(row), second.map(row), limit);+ expect(rows.map((r) => r.keyword)).toEqual(expected);});});diff --git a/src/server/features/keywords/services/research/research-data.test.ts b/src/server/features/keywords/services/research/research-data.test.tsindex 4da634f0..ddcd8726 100644--- a/src/server/features/keywords/services/research/research-data.test.ts+++ b/src/server/features/keywords/services/research/research-data.test.ts@@ -8,31 +8,6 @@ import type { AdsKeywordIdeaItem } from "@/server/lib/dataforseo";import { mapAdsKeywordItems } from "./research-data";describe("mapAdsKeywordItems", () => {- it("maps Google Ads items to research rows without KD/intent", () => {- const rows = mapAdsKeywordItems([- {- keyword: "Hotel Reykjavik",- search_volume: 1300,- cpc: 2.54,- competition: "HIGH",- competition_index: 42,- monthly_searches: [{ year: 2026, month: 5, search_volume: 1300 }],- },- ]);-- expect(rows).toEqual([- {- keyword: "hotel reykjavik",- searchVolume: 1300,- trend: [{ year: 2026, month: 5, searchVolume: 1300 }],- cpc: 2.54,- competition: 0.42,- keywordDifficulty: null,- intent: "unknown",- },- ]);- });-it("dedupes case-variant keywords and skips empty ones", () => {const items: AdsKeywordIdeaItem[] = [{ keyword: "northern lights tour", search_volume: 320 },diff --git a/src/server/features/keywords/services/research/saved-keywords.test.ts b/src/server/features/keywords/services/research/saved-keywords.test.tsindex e323a926..f398918f 100644--- a/src/server/features/keywords/services/research/saved-keywords.test.ts+++ b/src/server/features/keywords/services/research/saved-keywords.test.ts@@ -1,14 +1,10 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";+import { saveKeywords } from "./saved-keywords";const mocks = vi.hoisted(() => ({addTagsToSavedKeywords: vi.fn(),- listSavedKeywordsByProject: vi.fn(),- removeAllTagsFromSavedKeywords: vi.fn(),- removeSavedKeywords: vi.fn(),- removeTagsFromSavedKeywords: vi.fn(),replaceTagsForSavedKeywords: vi.fn(),saveKeywordsToProject: vi.fn(),- upsertKeywordMetric: vi.fn(),}));vi.mock(@@ -28,11 +24,6 @@ const savedKeywordRow = {};describe("saved keyword service", () => {- beforeEach(() => {- vi.resetModules();- for (const mock of Object.values(mocks)) mock.mockReset();- });-it("attaches tags to saved keyword rows after saving", async () => {mocks.saveKeywordsToProject.mockResolvedValue([savedKeywordRow,@@ -42,7 +33,6 @@ describe("saved keyword service", () => {savedKeywordCount: 2,tags: [],});- const { saveKeywords } = await import("./saved-keywords");await saveKeywords({projectId: "project_1",@@ -66,141 +56,6 @@ describe("saved keyword service", () => {});});- it("does not call tag assignment when no tags are provided", async () => {- mocks.saveKeywordsToProject.mockResolvedValue([savedKeywordRow]);- const { saveKeywords } = await import("./saved-keywords");-- await saveKeywords({- projectId: "project_1",- keywords: ["technical seo"],- locationCode: 2840,- languageCode: "en",- tagMode: "append",- });-- expect(mocks.addTagsToSavedKeywords).not.toHaveBeenCalled();- });-- it("maps paged saved keyword rows with attached tags", async () => {- mocks.listSavedKeywordsByProject.mockResolvedValue({- totalCount: 1,- tags: [- {- id: "tag_1",- projectId: "project_1",- name: "Content",- normalizedName: "content",- color: null,- createdAt: "2026-05-11T00:00:00.000Z",- keywordCount: 1,- },- ],- rows: [- {- row: savedKeywordRow,- metric: {- id: 1,- projectId: "project_1",- keyword: "technical seo",- locationCode: 2840,- languageCode: "en",- searchVolume: 120,- cpc: 2.5,- competition: 0.2,- keywordDifficulty: 18,- intent: "informational",- monthlySearches: null,- fetchedAt: "2026-05-10T00:00:00.000Z",- },- tags: [- {- id: "tag_1",- projectId: "project_1",- name: "Content",- normalizedName: "content",- color: null,- createdAt: "2026-05-11T00:00:00.000Z",- },- ],- },- ],- });- const { getSavedKeywords } = await import("./saved-keywords");-- const result = await getSavedKeywords({- projectId: "project_1",- tagIds: ["tag_1"],- page: 1,- pageSize: 50,- sort: "createdAt",- order: "desc",- });-- expect(mocks.listSavedKeywordsByProject).toHaveBeenCalledWith({- projectId: "project_1",- search: undefined,- tagIds: ["tag_1"],- tagNames: undefined,- page: 1,- pageSize: 50,- sort: "createdAt",- order: "desc",- });- expect(result.rows[0]?.tags).toEqual([- { id: "tag_1", name: "Content", normalizedName: "content", color: null },- ]);- expect(result.tags).toEqual([- {- id: "tag_1",- name: "Content",- normalizedName: "content",- color: null,- keywordCount: 1,- },- ]);- });-- it("updates saved keyword tags through add and remove operations", async () => {- mocks.addTagsToSavedKeywords.mockResolvedValue({- savedKeywordCount: 2,- tags: [- {- id: "tag_1",- name: "Content",- normalizedName: "content",- },- ],- });- mocks.removeTagsFromSavedKeywords.mockResolvedValue({- savedKeywordCount: 2,- removedCount: 2,- tags: [{ id: "tag_2" }],- });- const { updateSavedKeywordTags } = await import("./saved-keywords");-- const result = await updateSavedKeywordTags({- projectId: "project_1",- savedKeywordIds: ["saved_1", "saved_2"],- addTags: ["Content"],- removeTagIds: ["tag_2"],- });-- expect(result).toMatchObject({- success: true,- taggedCount: 2,- addedTags: [- {- id: "tag_1",- name: "Content",- normalizedName: "content",- color: null,- },- ],- removedTagIds: ["tag_2"],- removedAssignments: 2,- });- });-it("replaces tags only for the exact saved keyword rows returned by save", async () => {mocks.saveKeywordsToProject.mockResolvedValue([{ ...savedKeywordRow, id: "saved_us", keyword: "technical seo" },@@ -210,7 +65,6 @@ describe("saved keyword service", () => {removedCount: 1,tags: [{ id: "tag_new", name: "US", normalizedName: "us" }],});- const { saveKeywords } = await import("./saved-keywords");const result = await saveKeywords({projectId: "project_1",@@ -232,7 +86,6 @@ describe("saved keyword service", () => {it("rejects replace mode without replacement tags", async () => {mocks.saveKeywordsToProject.mockResolvedValue([savedKeywordRow]);- const { saveKeywords } = await import("./saved-keywords");await expect(saveKeywords({diff --git a/src/server/features/lighthouse/services/lighthouse-export.test.ts b/src/server/features/lighthouse/services/lighthouse-export.test.tsdeleted file mode 100644index 0140047c..00000000--- a/src/server/features/lighthouse/services/lighthouse-export.test.ts+++ /dev/null@@ -1,170 +0,0 @@-import { z } from "zod";-import { describe, expect, it } from "vitest";-import { buildLighthouseExportFile } from "@/server/lib/lighthousePayload";--const storedPayloadJson = JSON.stringify({- version: 2,- source: "dataforseo-lighthouse",- hasIssueDetails: true,- metadata: {- requestedUrl: "https://everyapp.dev/blog/enable-mfa-rdp-ssh",- finalUrl: "https://everyapp.dev/blog/enable-mfa-rdp-ssh",- strategy: "mobile",- fetchedAt: "2026-03-23T19:27:33.000Z",- lighthouseVersion: "12.2.0",- taskId: "task-1",- cost: 0.00425,- },- scores: {- performance: 89,- accessibility: 93,- "best-practices": 92,- seo: 91,- },- metrics: {- firstContentfulPaint: {- score: 47,- displayValue: "3.1 s",- numericValue: 3100,- },- largestContentfulPaint: {- score: 12,- displayValue: "6.4 s",- numericValue: 6400,- },- totalBlockingTime: {- score: 79,- displayValue: "290 ms",- numericValue: 290,- },- cumulativeLayoutShift: {- score: 92,- displayValue: "0.03",- numericValue: 0.03,- },- speedIndex: {- score: 86,- displayValue: "3.7 s",- numericValue: 3700,- },- timeToInteractive: {- score: 13,- displayValue: "12.8 s",- numericValue: 12800,- },- interactionToNextPaint: {- score: null,- displayValue: null,- numericValue: null,- },- serverResponseTime: {- score: 90,- displayValue: "52 ms",- numericValue: 52,- },- },- issues: [- {- category: "performance",- auditKey: "unused-javascript",- title: "Reduce unused JavaScript",- description: "Trim dead code.",- score: 50,- scoreDisplayMode: "metricSavings",- displayValue: "Potential savings of 227 KiB",- impactMs: 0,- impactBytes: 232886,- severity: "critical",- items: [],- },- {- category: "accessibility",- auditKey: "color-contrast",- title:- "Background and foreground colors do not have a sufficient contrast ratio.",- description: "Improve contrast.",- score: 0,- scoreDisplayMode: "binary",- displayValue: null,- impactMs: null,- impactBytes: null,- severity: "critical",- items: [],- },- ],-});--const issuesExportSchema = z.object({- resultId: z.string(),- category: z.string(),- issues: z.array(- z.object({- auditKey: z.string(),- category: z.string(),- }),- ),-});--describe("buildLighthouseExportFile", () => {- it("exports the stored payload unchanged for full mode", () => {- const exported = buildLighthouseExportFile({- idField: "resultId",- idValue: "result-1",- finalUrl: "https://everyapp.dev/blog/enable-mfa-rdp-ssh",- strategy: "mobile",- createdAt: "2026-03-23T19:27:33.000Z",- payloadJson: storedPayloadJson,- mode: "full",- });-- expect(exported.filename).toContain("-payload.json");- expect(exported.content).toBe(storedPayloadJson);- });-- it("exports only actionable issues for issues mode", () => {- const exported = buildLighthouseExportFile({- idField: "resultId",- idValue: "result-1",- finalUrl: "https://everyapp.dev/blog/enable-mfa-rdp-ssh",- strategy: "mobile",- createdAt: "2026-03-23T19:27:33.000Z",- payloadJson: storedPayloadJson,- mode: "issues",- });-- const content = issuesExportSchema.parse(JSON.parse(exported.content));-- expect(exported.filename).toContain("-issues.json");- expect(content.resultId).toBe("result-1");- expect(content.category).toBe("all");- expect(content.issues.map((issue) => issue.auditKey)).toEqual([- "unused-javascript",- "color-contrast",- ]);- expect(exported.content).not.toContain("timeToInteractive");- });-- it("exports only the selected category for category mode", () => {- const exported = buildLighthouseExportFile({- idField: "resultId",- idValue: "result-1",- finalUrl: "https://everyapp.dev/blog/enable-mfa-rdp-ssh",- strategy: "mobile",- createdAt: "2026-03-23T19:27:33.000Z",- payloadJson: storedPayloadJson,- mode: "category",- category: "accessibility",- });-- const content = issuesExportSchema.parse(JSON.parse(exported.content));-- expect(exported.filename).toContain("-accessibility-issues.json");- expect(content.category).toBe("accessibility");- expect(content.issues).toEqual([- expect.objectContaining({- auditKey: "color-contrast",- category: "accessibility",- }),- ]);- });-});diff --git a/src/server/features/project-context/services/ProjectContextService.test.ts b/src/server/features/project-context/services/ProjectContextService.test.tsindex 5b1a0720..253b382c 100644--- a/src/server/features/project-context/services/ProjectContextService.test.ts+++ b/src/server/features/project-context/services/ProjectContextService.test.ts@@ -197,19 +197,6 @@ describe("project context service", () => {domain: `competitor${index}.com`,}));- it("rejects a new competitor once the project is at the cap", async () => {- mocks.listCompetitors.mockResolvedValue(fullCompetitorList);-- await expect(- applyContextUpdates(- "project_1",- [{ addCompetitors: [{ domain: "newcomer.com" }] }],- "user",- ),- ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });- expect(mocks.upsertCompetitors).not.toHaveBeenCalled();- });-it("still updates a competitor it already stores at the cap", async () => {mocks.listCompetitors.mockResolvedValue(fullCompetitorList);@@ -314,31 +301,6 @@ describe("project context service", () => {});});- it("renders empty typed sections as missing in the digest", () => {- const markdown = renderProjectContextMarkdown({- sections: [- {- key: "business_overview",- content: "We sell paint.",- updatedAt: "2026-08-15T10:00:00.000Z",- updatedBy: "user",- },- ],- missingSections: ["current_goal", "positioning", "writing_preferences"],- customSections: [],- competitors: [],- keyPages: [],- researchLog: [],- reportTemplates: [],- });-- expect(markdown).toContain("## Business overview\n\nWe sell paint.");- expect(markdown).toContain("## Current goal\n\n_Empty_");- expect(markdown).toContain(- "Missing sections: current_goal, positioning, writing_preferences",- );- });-// A full log is a truncated log, and an agent judging whether research is// stale must not read the newest 20 entries as the whole 90-day window.it("says so when the research log is rendered at its limit", () => {diff --git a/src/server/features/projects/services/projects.test.ts b/src/server/features/projects/services/projects.test.tsindex 00faff49..75027090 100644--- a/src/server/features/projects/services/projects.test.ts+++ b/src/server/features/projects/services/projects.test.ts@@ -1,4 +1,12 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ archiveProject,+ createProject,+ listProjectsEnsuringOne,+ restoreProject,+ setProjectWebsite,+ updateProject,+} from "./projects";const mocks = vi.hoisted(() => ({createProject: vi.fn(),@@ -7,9 +15,7 @@ const mocks = vi.hoisted(() => ({archiveProject: vi.fn(),restoreProject: vi.fn(),countProjects: vi.fn(),- getProjectForOrganization: vi.fn(),listProjects: vi.fn(),- listArchivedProjects: vi.fn(),tryCreateDefaultProject: vi.fn(),}));@@ -33,14 +39,13 @@ const namedProject = {describe("project service", () => {beforeEach(() => {- vi.resetModules();- for (const mock of Object.values(mocks)) mock.mockReset();+ // The create "Default conflict" test sets a persistent rejection.+ mocks.createProject.mockResolvedValue(namedProject);});describe("listProjectsEnsuringOne", () => {it("returns existing projects without creating a Default", async () => {mocks.listProjects.mockResolvedValue([namedProject]);- const { listProjectsEnsuringOne } = await import("./projects");await expect(listProjectsEnsuringOne("org_1")).resolves.toEqual([namedProject,@@ -54,7 +59,6 @@ describe("project service", () => {.mockResolvedValueOnce([]).mockResolvedValueOnce([defaultProject]);mocks.tryCreateDefaultProject.mockResolvedValue("project_default");- const { listProjectsEnsuringOne } = await import("./projects");await expect(listProjectsEnsuringOne("org_1")).resolves.toEqual([defaultProject,@@ -62,26 +66,11 @@ describe("project service", () => {expect(mocks.tryCreateDefaultProject).toHaveBeenCalledWith("org_1");expect(mocks.listProjects).toHaveBeenCalledTimes(2);});-- it("recovers from the Default creation race", async () => {- mocks.listProjects- .mockResolvedValueOnce([])- .mockResolvedValueOnce([defaultProject]);- // A racing request won the insert, so this call's onConflictDoNothing- // returns null — but the re-list still finds the Default.- mocks.tryCreateDefaultProject.mockResolvedValue(null);- const { listProjectsEnsuringOne } = await import("./projects");-- await expect(listProjectsEnsuringOne("org_1")).resolves.toEqual([- defaultProject,- ]);- });});describe("setProjectWebsite", () => {it("saves normalized domain and market in one write without changing the name", async () => {mocks.updateProjectWebsite.mockResolvedValue(namedProject);- const { setProjectWebsite } = await import("./projects");await setProjectWebsite("org_1", {projectId: "project_acme",domain: "https://www.acme.com/about",@@ -96,51 +85,11 @@ describe("project service", () => {);expect(mocks.updateProject).not.toHaveBeenCalled();});- it("rejects an invalid website before writing", async () => {- const { setProjectWebsite } = await import("./projects");- await expect(- setProjectWebsite("org_1", {- projectId: "project_acme",- domain: "not a domain",- locationCode: 2840,- languageCode: "en",- }),- ).rejects.toThrow();- expect(mocks.updateProjectWebsite).not.toHaveBeenCalled();- });- it("rejects a mismatched market before writing the website", async () => {- const { setProjectWebsite } = await import("./projects");- await expect(- setProjectWebsite("org_1", {- projectId: "project_acme",- domain: "acme.com",- locationCode: 2826,- languageCode: "fr",- }),- ).rejects.toThrow();- expect(mocks.updateProjectWebsite).not.toHaveBeenCalled();- });});describe("createProject", () => {- it("returns the full created project", async () => {- mocks.createProject.mockResolvedValue(namedProject);- const { createProject } = await import("./projects");-- await expect(- createProject("org_1", { name: "Acme", domain: "acme.com" }),- ).resolves.toEqual(namedProject);- expect(mocks.createProject).toHaveBeenCalledWith(- "org_1",- "Acme",- "acme.com",- undefined,- );- });-it("derives the native language when only the location is given", async () => {mocks.createProject.mockResolvedValue(namedProject);- const { createProject } = await import("./projects");await createProject("org_1", {name: "Acme",@@ -156,8 +105,6 @@ describe("project service", () => {});it("rejects a language DataForSEO does not serve for the location", async () => {- const { createProject } = await import("./projects");-await expect(createProject("org_1", {name: "Acme",@@ -174,7 +121,6 @@ describe("project service", () => {"UNIQUE constraint failed: projects.projects_one_default_per_organization_idx",),);- const { createProject } = await import("./projects");await expect(createProject("org_1", { name: "Default", domain: undefined }),@@ -183,79 +129,7 @@ describe("project service", () => {});describe("updateProject", () => {- it("leaves the market columns untouched when neither half is given", async () => {- mocks.updateProject.mockResolvedValue(namedProject);- const { updateProject } = await import("./projects");-- await updateProject("org_1", { projectId: "project_acme", name: "Acme" });- expect(mocks.updateProject).toHaveBeenCalledWith(- "project_acme",- "org_1",- expect.objectContaining({ market: undefined }),- );- });-- it("snaps the language on a location-only change without reading the stored row", async () => {- mocks.updateProject.mockResolvedValue(namedProject);- const { updateProject } = await import("./projects");-- await updateProject("org_1", {- projectId: "project_acme",- name: "Acme",- locationCode: 2276,- });- expect(mocks.getProjectForOrganization).not.toHaveBeenCalled();- expect(mocks.updateProject).toHaveBeenCalledWith(- "project_acme",- "org_1",- expect.objectContaining({- market: { locationCode: 2276, languageCode: "de" },- }),- );- });-- it("returns the updated project", async () => {- mocks.updateProject.mockResolvedValue(namedProject);- const { updateProject } = await import("./projects");-- await expect(- updateProject("org_1", {- projectId: "project_acme",- name: "Acme",- domain: "acme.com",- }),- ).resolves.toEqual(namedProject);- expect(mocks.updateProject).toHaveBeenCalledWith(- "project_acme",- "org_1",- { name: "Acme", domain: "acme.com" },- );- });-- it("clears the domain when none is provided", async () => {- const cleared = { ...namedProject, domain: null };- mocks.updateProject.mockResolvedValue(cleared);- const { updateProject } = await import("./projects");-- await expect(- updateProject("org_1", {- projectId: "project_acme",- name: "Acme",- domain: undefined,- }),- ).resolves.toEqual(cleared);- expect(mocks.updateProject).toHaveBeenCalledWith(- "project_acme",- "org_1",- { name: "Acme", domain: undefined },- );- });- });-- describe("updateProject domain validation", () => {it("rejects a junk domain instead of storing it", async () => {- const { updateProject } = await import("./projects");-await expect(updateProject("org_1", {projectId: "project_acme",@@ -268,21 +142,15 @@ describe("project service", () => {});describe("archiveProject", () => {- it("refuses to archive the org's only project", async () => {+ it("refuses to archive the org's only project and allows it with two", async () => {mocks.countProjects.mockResolvedValue(1);- const { archiveProject } = await import("./projects");-await expect(archiveProject("org_1", { projectId: "project_default" }),).rejects.toMatchObject({ code: "CONFLICT" });expect(mocks.archiveProject).not.toHaveBeenCalled();- });- it("archives when more than one project remains", async () => {mocks.countProjects.mockResolvedValue(2);mocks.archiveProject.mockResolvedValue(undefined);- const { archiveProject } = await import("./projects");-await expect(archiveProject("org_1", { projectId: "project_acme" }),).resolves.toEqual({ success: true });@@ -294,26 +162,12 @@ describe("project service", () => {});describe("restoreProject", () => {- it("restores an archived project", async () => {- mocks.restoreProject.mockResolvedValue(undefined);- const { restoreProject } = await import("./projects");-- await expect(- restoreProject("org_1", { archivedProjectId: "project_acme" }),- ).resolves.toEqual({ success: true });- expect(mocks.restoreProject).toHaveBeenCalledWith(- "project_acme",- "org_1",- );- });-it("maps the Default singleton conflict to a friendly CONFLICT", async () => {mocks.restoreProject.mockRejectedValue(new Error("UNIQUE constraint failed: projects.projects_one_default_per_organization_idx",),);- const { restoreProject } = await import("./projects");await expect(restoreProject("org_1", { archivedProjectId: "project_default" }),diff --git a/src/server/features/rank-tracking/repositories/snapshotQueries.test.ts b/src/server/features/rank-tracking/rankTrackingTimestamps.test.tssimilarity index 62%rename from src/server/features/rank-tracking/repositories/snapshotQueries.test.tsrename to src/server/features/rank-tracking/rankTrackingTimestamps.test.tsindex 2451a65d..90254382 100644--- a/src/server/features/rank-tracking/repositories/snapshotQueries.test.ts+++ b/src/server/features/rank-tracking/rankTrackingTimestamps.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";-import { toSqliteTimestamp } from "@/server/features/rank-tracking/rankTrackingTimestamps";+import { toSqliteTimestamp } from "./rankTrackingTimestamps";-describe("rank tracking snapshot queries", () => {+describe("toSqliteTimestamp", () => {it("formats comparison cutoffs like SQLite current_timestamp", () => {expect(toSqliteTimestamp(new Date("2026-06-09T12:34:56.789Z"))).toBe("2026-06-09 12:34:56",diff --git a/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts b/src/server/features/rank-tracking/services/RankTrackingService.management.test.tsindex 37062d63..781e884d 100644--- a/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts+++ b/src/server/features/rank-tracking/services/RankTrackingService.management.test.ts@@ -61,6 +61,10 @@ describe("RankTrackingService management invariants", () => {{ id: "kw_1", keyword: "seo" },{ id: "kw_2", keyword: "audit" },]);+ // Persistent implementations survive clearMocks, so the billing gates get+ // explicit defaults; the plan tests override them per case.+ mocks.isHostedServerAuthMode.mockResolvedValue(true);+ mocks.customerHasPaidPlan.mockResolvedValue(true);});it("reports only keyword rows actually inserted", async () => {@@ -196,41 +200,6 @@ describe("RankTrackingService management invariants", () => {expect(mocks.getKeywordCountForConfig).not.toHaveBeenCalled();});- it("deduplicates removal IDs and reports only owned rows deleted", async () => {- mocks.removeKeywordsFromConfig.mockResolvedValue(["owned_id"]);-- const result = await RankTrackingService.removeKeywords(- "config_1",- "project_1",- ["owned_id", "foreign_id", "missing_id", "owned_id"],- );-- expect(mocks.removeKeywordsFromConfig).toHaveBeenCalledWith(- ["owned_id", "foreign_id", "missing_id"],- "config_1",- );- expect(result).toEqual({ removed: 1, removedIds: ["owned_id"] });- });-- it("uses the same live cost invariant exposed to the browser", async () => {- mocks.getKeywordCountForConfig.mockResolvedValue(5);-- await expect(- RankTrackingService.estimateCost("config_1", "project_1"),- ).resolves.toMatchObject({- keywordCount: 5,- devicesCount: 2,- totalChecks: 10,- method: "live",- existingKeywordCount: 5,- additionalKeywordCount: 0,- scheduledEstimate: {- scheduleInterval: "weekly",- checksPerMonth: 4,- },- });- });-it("rejects a hosted unpaid run before keyword or workflow work", async () => {mocks.isHostedServerAuthMode.mockResolvedValue(true);mocks.customerHasPaidPlan.mockResolvedValue(false);@@ -276,11 +245,16 @@ describe("RankTrackingService management invariants", () => {expect(mocks.customerHasPaidPlan).not.toHaveBeenCalled();});- it("rejects a run above its approved credit ceiling", async () => {- const error: unknown = await RankTrackingService.triggerCheck({+ it("starts a run only at or below its approved credit ceiling", async () => {+ mocks.beginRankCheckRun.mockResolvedValue({ ok: true, runId: "run_1" });+ const run = {configId: "config_1",projectId: "project_1",billingCustomer,+ };++ const error: unknown = await RankTrackingService.triggerCheck({+ ...run,maxCostCredits: 11,}).catch((cause: unknown) => cause);expect(error).toBeInstanceOf(Error);@@ -288,21 +262,9 @@ describe("RankTrackingService management invariants", () => {expect(error.code).toBe("VALIDATION_ERROR");expect(error.message).toContain("costs 12 credits");expect(mocks.beginRankCheckRun).not.toHaveBeenCalled();- });-- it("starts a run at or below its approved credit ceiling", async () => {- mocks.beginRankCheckRun.mockResolvedValue({- ok: true,- runId: "run_1",- });await expect(- RankTrackingService.triggerCheck({- configId: "config_1",- projectId: "project_1",- billingCustomer,- maxCostCredits: 12,- }),+ RankTrackingService.triggerCheck({ ...run, maxCostCredits: 12 }),).resolves.toEqual({ ok: true, runId: "run_1" });expect(mocks.beginRankCheckRun).toHaveBeenCalledWith(expect.objectContaining({ maxCostCredits: 12 }),@@ -324,22 +286,6 @@ describe("RankTrackingService management invariants", () => {expect(mocks.fetchKeywordMetricsForList).not.toHaveBeenCalled();});- it("allows self-hosted metrics refresh without a plan check", async () => {- mocks.isHostedServerAuthMode.mockResolvedValue(false);- mocks.createDataforseoClient.mockReturnValue({});- mocks.fetchKeywordMetricsForList.mockResolvedValue([]);-- await expect(- RankTrackingService.refreshKeywordMetrics(- "config_1",- "project_1",- billingCustomer,- ),- ).resolves.toEqual({ updated: 0 });- expect(mocks.customerHasPaidPlan).not.toHaveBeenCalled();- expect(mocks.fetchKeywordMetricsForList).toHaveBeenCalledTimes(1);- });-it("matches metrics back to a cased keyword and its lowercase twin", async () => {mocks.isHostedServerAuthMode.mockResolvedValue(false);mocks.createDataforseoClient.mockReturnValue({});diff --git a/src/server/features/rank-tracking/services/RankTrackingService.test.ts b/src/server/features/rank-tracking/services/RankTrackingService.test.tsindex 1927bd9d..2cb54944 100644--- a/src/server/features/rank-tracking/services/RankTrackingService.test.ts+++ b/src/server/features/rank-tracking/services/RankTrackingService.test.ts@@ -174,62 +174,35 @@ describe("RankTrackingService.createConfig", () => {expect(mocks.createConfig).not.toHaveBeenCalled();});- it("creates a new config when none exists for the domain + location", async () => {- mocks.getConfigByProjectDomainLocation.mockResolvedValue(null);- mocks.getConfigsForProject.mockResolvedValue([]);- mocks.createConfig.mockResolvedValue(undefined);-- const result = await RankTrackingService.createConfig(baseInput);-- expect(result.id).toBeTruthy();- expect(mocks.createConfig).toHaveBeenCalledTimes(1);- expect(mocks.updateConfig).not.toHaveBeenCalled();- expect(mocks.createConfig).toHaveBeenCalledWith(- expect.objectContaining({- id: result.id,+ // Omitted fields fall back to the project market; a location alone snaps+ // the language to that location, not to the project's.+ it.each([+ ["the project's market", {}, { locationCode: 2704, languageCode: "vi" }],+ [+ "the location's language",+ { locationCode: 2276 },+ { locationCode: 2276, languageCode: "de" },+ ],+ ])(+ "resolves an omitted language to %s",+ async (_case, overrides, expected) => {+ mocks.getConfigByProjectDomainLocation.mockResolvedValue(null);+ mocks.getConfigsForProject.mockResolvedValue([]);+ mocks.createConfig.mockResolvedValue(undefined);++ await RankTrackingService.createConfig({projectId: "project_1",+ projectMarket: { locationCode: 2704, languageCode: "vi" },domain: "acme.com",- devices: "desktop",serpDepth: 40,- scheduleInterval: "daily",- }),- );- });+ ...overrides,+ });- it("uses the project's market when location and language are omitted", async () => {- mocks.getConfigByProjectDomainLocation.mockResolvedValue(null);- mocks.getConfigsForProject.mockResolvedValue([]);- mocks.createConfig.mockResolvedValue(undefined);-- await RankTrackingService.createConfig({- projectId: "project_1",- projectMarket: { locationCode: 2704, languageCode: "vi" },- domain: "acme.com",- serpDepth: 40,- });-- expect(mocks.createConfig).toHaveBeenCalledWith(- expect.objectContaining({ locationCode: 2704, languageCode: "vi" }),- );- });-- it("snaps the language when only location overrides the project market", async () => {- mocks.getConfigByProjectDomainLocation.mockResolvedValue(null);- mocks.getConfigsForProject.mockResolvedValue([]);- mocks.createConfig.mockResolvedValue(undefined);-- await RankTrackingService.createConfig({- projectId: "project_1",- projectMarket: { locationCode: 2704, languageCode: "vi" },- domain: "acme.com",- locationCode: 2276,- serpDepth: 40,- });-- expect(mocks.createConfig).toHaveBeenCalledWith(- expect.objectContaining({ locationCode: 2276, languageCode: "de" }),- );- });+ expect(mocks.createConfig).toHaveBeenCalledWith(+ expect.objectContaining(expected),+ );+ },+ );it("rejects a locationName the sandbox refuses, pointing at search_serp_locations", async () => {stubSandbox(40501, "Invalid Field: 'location_name'.");@@ -282,21 +255,21 @@ describe("RankTrackingService.updateConfig schedule", () => {);});- it("rejects a weekly time without a weekday", async () => {- await expect(- RankTrackingService.updateConfig("config_archived", "project_1", {+ it.each([+ [+ "a weekly time without a weekday",+ { scheduleTime: { hour: 9, minute: 30 } },+ ],+ [+ "a chosen time on a manual schedule",+ {+ scheduleInterval: "manual" as const,scheduleTime: { hour: 9, minute: 30 },- }),- ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });- expect(mocks.updateConfig).not.toHaveBeenCalled();- });-- it("rejects a chosen time on a manual schedule", async () => {+ },+ ],+ ])("rejects %s", async (_case, input) => {await expect(- RankTrackingService.updateConfig("config_archived", "project_1", {- scheduleInterval: "manual",- scheduleTime: { hour: 9, minute: 30 },- }),+ RankTrackingService.updateConfig("config_archived", "project_1", input),).rejects.toMatchObject({ code: "VALIDATION_ERROR" });expect(mocks.updateConfig).not.toHaveBeenCalled();});diff --git a/src/server/features/rank-tracking/services/rankCheckRunGuards.test.ts b/src/server/features/rank-tracking/services/rankCheckRunGuards.test.tsindex 0f4ebac1..d1f0f234 100644--- a/src/server/features/rank-tracking/services/rankCheckRunGuards.test.ts+++ b/src/server/features/rank-tracking/services/rankCheckRunGuards.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { beginRankCheckRun } from "./rankCheckRunGuards";const mocks = vi.hoisted(() => ({@@ -19,19 +19,6 @@ vi.mock(() => ({ RankTrackingRepository: mocks }),);-const run = {- id: "run_1",- configId: "config_1",- projectId: "project_1",- status: "pending" as const,- keywordsTotal: 2,- keywordsChecked: 0,- isSubsetRun: false,- errorMessage: null,- startedAt: new Date().toISOString(),- completedAt: null,-};-const input = {config: {id: "config_1",@@ -55,44 +42,39 @@ const input = {};describe("beginRankCheckRun", () => {- beforeEach(() => {});-- it("returns the locally generated run ID without a fallible post-start read", async () => {- mocks.tryCreateRun.mockResolvedValue(true);- const create = vi- .fn<(input: { params: { maxCostCredits?: number } }) => Promise<void>>()- .mockResolvedValue(undefined);- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only create is exercised by this unit test- const workflow = { create } as unknown as Env["RANK_CHECK_WORKFLOW"];+ // The workflow enforces the ceiling, so forwarding it (or its absence) is the+ // billing contract.+ it.each([undefined, 12])(+ "starts one workflow with the approved credit ceiling %s",+ async (maxCostCredits) => {+ mocks.tryCreateRun.mockResolvedValue(true);+ const create = vi+ .fn<(input: { params: { maxCostCredits?: number } }) => Promise<void>>()+ .mockResolvedValue(undefined);+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only create is exercised by this unit test+ const workflow = { create } as unknown as Env["RANK_CHECK_WORKFLOW"];- const result = await beginRankCheckRun({ ...input, workflow });- expect(result.ok).toBe(true);- if (!result.ok) throw new Error("expected a created run");- expect(result.runId).toEqual(expect.any(String));- expect(create).toHaveBeenCalledTimes(1);- expect(create.mock.calls[0]?.[0].params.maxCostCredits).toBeUndefined();- expect(mocks.getRunById).not.toHaveBeenCalled();- });-- it("passes the approved credit ceiling into the workflow payload", async () => {- mocks.tryCreateRun.mockResolvedValue(true);- const create = vi- .fn<(input: { params: { maxCostCredits?: number } }) => Promise<void>>()- .mockResolvedValue(undefined);- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only create is exercised by this unit test- const workflow = { create } as unknown as Env["RANK_CHECK_WORKFLOW"];+ const result = await beginRankCheckRun({+ ...input,+ workflow,+ maxCostCredits,+ });- await beginRankCheckRun({- ...input,- workflow,- maxCostCredits: 12,- });-- expect(create.mock.calls[0]?.[0].params.maxCostCredits).toBe(12);- });+ if (!result.ok) throw new Error("expected the run to start");+ expect(result.runId).toEqual(expect.any(String));+ expect(create).toHaveBeenCalledTimes(1);+ expect(create.mock.calls[0]?.[0].params.maxCostCredits).toBe(+ maxCostCredits,+ );+ },+ );it("does not create another workflow when a run is already active", async () => {- const blocker = { ...run, id: "run_0", status: "running" as const };+ const blocker = {+ id: "run_0",+ status: "running" as const,+ startedAt: new Date().toISOString(),+ };mocks.tryCreateRun.mockResolvedValue(false);mocks.getActiveRunForConfig.mockResolvedValue(blocker);mocks.getWorkflow.mockResolvedValue({diff --git a/src/server/features/rank-tracking/services/rankTrackingResults.test.ts b/src/server/features/rank-tracking/services/rankTrackingResults.test.tsindex 321f4e8b..b77dc13f 100644--- a/src/server/features/rank-tracking/services/rankTrackingResults.test.ts+++ b/src/server/features/rank-tracking/services/rankTrackingResults.test.ts@@ -62,23 +62,4 @@ describe("getLatestResults", () => {},});});-- it("surfaces the latest failed run and its error message", async () => {- mocks.getLatestRunForConfig.mockResolvedValue({- id: "run_1",- status: "failed",- errorMessage: "Provider request timed out",- });-- await expect(- getLatestResults("config_1", "project_1"),- ).resolves.toMatchObject({- run: {- id: "run_1",- lastCheckedAt: null,- status: "failed",- errorMessage: "Provider request timed out",- },- });- });});diff --git a/src/server/features/rank-tracking/services/scheduledRankChecks.test.ts b/src/server/features/rank-tracking/services/scheduledRankChecks.test.tsindex 345e1ab4..cec4ddd9 100644--- a/src/server/features/rank-tracking/services/scheduledRankChecks.test.ts+++ b/src/server/features/rank-tracking/services/scheduledRankChecks.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { MAX_KEYWORDS_PER_CONFIG } from "@/shared/rank-tracking";+import { runScheduledRankChecks } from "./scheduledRankChecks";type DueConfigRow = {id: string;@@ -88,15 +89,8 @@ function dueConfig(overrides: Partial<DueConfigRow> = {}): DueConfigRow {};}-async function runTick() {- const { runScheduledRankChecks } = await import("./scheduledRankChecks");- await runScheduledRankChecks(testEnv);-}-describe("runScheduledRankChecks", () => {beforeEach(() => {- vi.resetModules();- vi.resetAllMocks();mocks.isHostedServerAuthMode.mockResolvedValue(true);mocks.customerHasPaidPlan.mockResolvedValue(true);mocks.claimDueConfig.mockResolvedValue(true);@@ -110,7 +104,7 @@ describe("runScheduledRankChecks", () => {it("advances a free config with plan_required instead of starting a workflow", async () => {mocks.customerHasPaidPlan.mockResolvedValue(false);- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.claimDueConfig).toHaveBeenCalledTimes(1);expect(mocks.claimDueConfig).toHaveBeenCalledWith(@@ -135,7 +129,7 @@ describe("runScheduledRankChecks", () => {new Map([["config_2", 5]]),);- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.claimDueConfig).toHaveBeenCalledWith(expect.objectContaining({@@ -153,7 +147,7 @@ describe("runScheduledRankChecks", () => {it("claims a paid config and starts its workflow", async () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.claimDueConfig).toHaveBeenCalledTimes(1);expect(mocks.claimDueConfig).toHaveBeenCalledWith(@@ -194,7 +188,7 @@ describe("runScheduledRankChecks", () => {const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.beginRankCheckRun).toHaveBeenCalledTimes(1);expect(mocks.claimDueConfig).toHaveBeenCalledTimes(1);@@ -221,7 +215,7 @@ describe("runScheduledRankChecks", () => {mocks.claimDueConfig.mockResolvedValueOnce(false);const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.beginRankCheckRun).toHaveBeenCalledTimes(1);expect(mocks.beginRankCheckRun.mock.calls[0][0].config.id).toBe("config_2");@@ -245,7 +239,7 @@ describe("runScheduledRankChecks", () => {// A tick with errors logs its summary at error level.const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.beginRankCheckRun).toHaveBeenCalledTimes(1);expect(mocks.beginRankCheckRun.mock.calls[0][0].config.id).toBe(@@ -272,7 +266,7 @@ describe("runScheduledRankChecks", () => {);const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.beginRankCheckRun).toHaveBeenCalledTimes(1);expect(mocks.beginRankCheckRun.mock.calls[0][0].config.id).toBe(@@ -294,7 +288,7 @@ describe("runScheduledRankChecks", () => {.mockReturnValue(start + 4 * 60_000); // every later check is past itconst logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.beginRankCheckRun).not.toHaveBeenCalled();expect(mocks.claimDueConfig).not.toHaveBeenCalled();@@ -311,7 +305,7 @@ describe("runScheduledRankChecks", () => {});const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.claimDueConfig).toHaveBeenCalledTimes(2);const [advance] = mocks.claimDueConfig.mock.calls[0];@@ -358,7 +352,7 @@ describe("runScheduledRankChecks", () => {});vi.spyOn(console, "error").mockImplementation(() => {});- await runTick();+ await runScheduledRankChecks(testEnv);// One Autumn call per org per tick — org_a's rejection is memoized.expect(mocks.customerHasPaidPlan).toHaveBeenCalledTimes(2);@@ -372,7 +366,7 @@ describe("runScheduledRankChecks", () => {it("makes no billing calls in self-hosted mode", async () => {mocks.isHostedServerAuthMode.mockResolvedValue(false);- await runTick();+ await runScheduledRankChecks(testEnv);expect(mocks.customerHasPaidPlan).not.toHaveBeenCalled();expect(mocks.beginRankCheckRun).toHaveBeenCalledTimes(1);diff --git a/src/server/features/reports/services/ReportService.test.ts b/src/server/features/reports/services/ReportService.test.tsindex 529b6568..72cf2af5 100644--- a/src/server/features/reports/services/ReportService.test.ts+++ b/src/server/features/reports/services/ReportService.test.ts@@ -5,12 +5,7 @@ import {REPORT_MAX_BYTES_PER_ORG,REPORT_MAX_PER_PROJECT,} from "@/types/schemas/reports";-import {- deleteReport,- getReport,- ReportService,- saveReport,-} from "./ReportService";+import { ReportService } from "./ReportService";const mocks = vi.hoisted(() => ({listReports: vi.fn(),@@ -34,8 +29,10 @@ vi.mock("@/server/lib/runtime-env", () => ({const html = "<!doctype html><html><body>Hi</body></html>";-const save = (overrides: Partial<Parameters<typeof saveReport>[0]> = {}) =>- saveReport({+const save = (+ overrides: Partial<Parameters<typeof ReportService.saveReport>[0]> = {},+) =>+ ReportService.saveReport({projectId: "project_1",organizationId: "org_1",title: "badseo.dev SEO audit, Sep 2026",@@ -102,18 +99,22 @@ describe("saveReport", () => {expect(mocks.updateReportContent).not.toHaveBeenCalled();});- it("refuses an over-long title and writes nothing", async () => {- await expect(save({ title: "T".repeat(143) })).rejects.toThrow(+ it.each([+ [+ { title: "T".repeat(143) },"Title is 143 characters; the limit is 120. Shorten it and save again.",- );- expect(mocks.insertReport).not.toHaveBeenCalled();- });-- it("refuses an over-long summary", async () => {- await expect(save({ summary: "s".repeat(2720) })).rejects.toThrow(+ ],+ [+ { summary: "s".repeat(2720) },"Summary is 2,720 characters; the limit is 2,500. Shorten it and save again.",- );- });+ ],+ ])(+ "refuses over-long text and writes nothing: %o",+ async (input, message) => {+ await expect(save(input)).rejects.toThrow(message);+ expect(mocks.insertReport).not.toHaveBeenCalled();+ },+ );it("measures the byte cap in UTF-8, not code units", async () => {// 320,000 two-byte characters: under the cap by String.length, over it by@@ -187,22 +188,13 @@ describe("saveReport", () => {});});-describe("reads and deletes", () => {- it("scopes a read to the project and refuses an unknown id", async () => {- mocks.getReport.mockResolvedValue(null);-- await expect(getReport("project_1", "report_gone")).rejects.toThrow(- "No report report_gone in this project. Call list_reports to see what exists.",- );- expect(mocks.getReport).toHaveBeenCalledWith("project_1", "report_gone");- });-+describe("deleteReport", () => {it("refuses a delete whose id is not in this project", async () => {mocks.deleteReport.mockResolvedValue(false);- await expect(deleteReport("project_1", "report_gone")).rejects.toThrow(- "No report report_gone in this project.",- );+ await expect(+ ReportService.deleteReport("project_1", "report_gone"),+ ).rejects.toThrow("No report report_gone in this project.");expect(mocks.deleteReport).toHaveBeenCalledWith("project_1", "report_gone");});});diff --git a/src/server/features/reports/services/ReportService.ts b/src/server/features/reports/services/ReportService.tsindex 7425bde2..aac5c052 100644--- a/src/server/features/reports/services/ReportService.ts+++ b/src/server/features/reports/services/ReportService.ts@@ -52,7 +52,7 @@ type SaveReportParams = {* written, so a rejected save leaves the stored report untouched — there is no* version history, and a half-written overwrite is unrecoverable.*/-export async function saveReport(params: SaveReportParams): Promise<{+async function saveReport(params: SaveReportParams): Promise<{reportId: string;title: string;created: boolean;@@ -204,7 +204,7 @@ async function listReports(params: {};}-export async function getReport(+async function getReport(projectId: string,reportId: string,): Promise<ReportMetadata> {@@ -224,7 +224,7 @@ async function getReportWithHtml(return { report, html };}-export async function deleteReport(+async function deleteReport(projectId: string,reportId: string,): Promise<void> {diff --git a/src/server/features/reports/services/ReportTemplateService.test.ts b/src/server/features/reports/services/ReportTemplateService.test.tsindex de1b0755..55f6c79b 100644--- a/src/server/features/reports/services/ReportTemplateService.test.ts+++ b/src/server/features/reports/services/ReportTemplateService.test.ts@@ -1,8 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import {- deleteReportTemplate,- saveReportTemplate,-} from "./ReportTemplateService";+import { ReportTemplateService } from "./ReportTemplateService";import {REPORT_TEMPLATE_MAX_PER_PROJECT,type ReportTemplate,@@ -35,9 +32,11 @@ const stored = (overrides: Partial<ReportTemplate> = {}): ReportTemplate => ({});const save = (- overrides: Partial<Parameters<typeof saveReportTemplate>[0]> = {},+ overrides: Partial<+ Parameters<typeof ReportTemplateService.saveReportTemplate>[0]+ > = {},) =>- saveReportTemplate({+ ReportTemplateService.saveReportTemplate({projectId: "project_1",name: "Client-ready audit summary",description: "For the site owner, non-technical.",@@ -52,15 +51,6 @@ beforeEach(() => {});describe("saveReportTemplate", () => {- it("creates a template in the project", async () => {- const result = await save();-- expect(result.created).toBe(true);- expect(mocks.insertTemplate).toHaveBeenCalledWith(- expect.objectContaining({ projectId: "project_1" }),- );- });-it("updates by id instead of inserting", async () => {mocks.listTemplates.mockResolvedValue([stored()]);@@ -115,7 +105,7 @@ describe("deleteReportTemplate", () => {mocks.deleteTemplate.mockResolvedValue(false);await expect(- deleteReportTemplate("project_1", "template_x"),+ ReportTemplateService.deleteReportTemplate("project_1", "template_x"),).rejects.toThrow(/No report template template_x/);expect(mocks.deleteTemplate).toHaveBeenCalledWith("project_1",diff --git a/src/server/features/reports/services/ReportTemplateService.ts b/src/server/features/reports/services/ReportTemplateService.tsindex 2a6278e4..db347804 100644--- a/src/server/features/reports/services/ReportTemplateService.ts+++ b/src/server/features/reports/services/ReportTemplateService.ts@@ -61,7 +61,7 @@ type SaveParams = {* Create-or-update in one call. Everything is validated before anything is* written, so a rejected save leaves the stored template untouched.*/-export async function saveReportTemplate(params: SaveParams): Promise<{+async function saveReportTemplate(params: SaveParams): Promise<{templateId: string;name: string;created: boolean;@@ -165,7 +165,7 @@ export async function saveReportTemplate(params: SaveParams): Promise<{return { templateId: id, name, created: true };}-export async function deleteReportTemplate(+async function deleteReportTemplate(projectId: string,templateId: string,): Promise<void> {diff --git a/src/server/features/reports/shareImageRoute.test.ts b/src/server/features/reports/shareImageRoute.test.tsindex 2b1f7a37..607f1a97 100644--- a/src/server/features/reports/shareImageRoute.test.ts+++ b/src/server/features/reports/shareImageRoute.test.ts@@ -57,10 +57,6 @@ describe("report social image access", () => {error,);expect(await (await handleReportSocialImage(TOKEN)).text()).toBe("image");- mocks.getSharedReportByToken.mockResolvedValue(null);- const revoked = await handleReportSocialImage(TOKEN);- expect(revoked.status).toBe(404);- expect(revoked.headers.get("Location")).toBeNull();});it("does not hide report lookup failures behind the fallback", async () => {@@ -100,11 +96,4 @@ describe("report social image access", () => {expect(mocks.renderReportSocialImage).not.toHaveBeenCalled();},);-- it("checks access again after revocation", async () => {- await handleReportSocialImage(TOKEN);- mocks.getSharedReportByToken.mockResolvedValue(null);- expect((await handleReportSocialImage(TOKEN)).status).toBe(404);- expect(mocks.renderReportSocialImage).toHaveBeenCalledTimes(1);- });});diff --git a/src/server/features/reports/sharePage.test.ts b/src/server/features/reports/sharePage.test.tsindex e590d96a..eac5ae0d 100644--- a/src/server/features/reports/sharePage.test.ts+++ b/src/server/features/reports/sharePage.test.ts@@ -28,14 +28,6 @@ const SHARED_REPORT = {archived: false,};-async function renderedImageUrl(): Promise<string> {- const response = await renderSharePage(TOKEN, request());- return (- load(await response.text())('meta[property="og:image"]').attr("content") ??- ""- );-}-beforeEach(() => {mocks.env.AUTH_MODE = "hosted";mocks.getSharedReportByToken.mockResolvedValue(SHARED_REPORT);@@ -78,50 +70,6 @@ describe("renderSharePage", () => {expect(html).not.toContain("/assets/");});- it.each([- ["old.example.com", "new.example.com"],- ["old.example.com", null],- [null, "new.example.com"],- ])(- "changes the image URL when the website changes from %s to %s",- async (before, after) => {- mocks.getSharedReportByToken.mockResolvedValue({- ...SHARED_REPORT,- projectDomain: before,- });- const original = await renderedImageUrl();- mocks.getSharedReportByToken.mockResolvedValue({- ...SHARED_REPORT,- projectDomain: after,- });- const updated = await renderedImageUrl();- expect(new URL(updated).searchParams.get("v")).toBe(- new URL(original).searchParams.get("v"),- );- expect(updated).not.toBe(original);- expect(new URL(updated).searchParams.get("domain")).toBe(after ?? "");- },- );-- it("versions by the displayed hostname, not URL formatting", async () => {- const original = await renderedImageUrl();- mocks.getSharedReportByToken.mockResolvedValue({- ...SHARED_REPORT,- projectDomain: "https://www.badseo.dev/path?query=value",- });- expect(await renderedImageUrl()).toBe(original);- });-- it("changes the image URL when a report is saved again", async () => {- const original = await renderedImageUrl();- mocks.getSharedReportByToken.mockResolvedValue({- ...SHARED_REPORT,- title: "Updated audit",- updatedAt: "2026-09-02T10:00:00.000Z",- });- expect(await renderedImageUrl()).not.toBe(original);- });-// The reader is told the project is archived; the report's own title is// content the link no longer grants access to.it("names the archived state without naming the report", async () => {@@ -145,32 +93,32 @@ describe("renderSharePage", () => {it.each([["an unknown or revoked token",+ TOKEN,() => mocks.getSharedReportByToken.mockResolvedValue(null),],+ // A token of the wrong shape is refused before the database is asked.+ ["a malformed token", "nope", () => {}],// Sharing is hosted-only: a self-hosted deployment answers as if the// link had never existed.["a deployment that is not hosted",+ TOKEN,() => {mocks.env.AUTH_MODE = "cloudflare_access";},],- ])("answers not shared for %s", async (_case, arrange) => {+ ])("answers not shared for %s", async (_case, token, arrange) => {arrange();- const response = await renderSharePage(TOKEN, request());+ const response = await renderSharePage(token, request());expect(response.status).toBe(404);const html = await response.text();expect(html).toContain("This report isn't shared.");expect(html).not.toContain("og:image");expect(html).not.toContain("twitter:image");- });-- it("answers a malformed token without querying", async () => {- const response = await renderSharePage("nope", request());-- expect(response.status).toBe(404);- expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();+ if (token !== TOKEN) {+ expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();+ }});});diff --git a/src/server/features/reports/shareRawRoute.test.ts b/src/server/features/reports/shareRawRoute.test.tsindex 9399b0f2..d013559b 100644--- a/src/server/features/reports/shareRawRoute.test.ts+++ b/src/server/features/reports/shareRawRoute.test.ts@@ -117,12 +117,16 @@ describe("handleSharedReportRequest", () => {it.each([["an unknown or revoked token",+ TOKEN,() => mocks.getSharedReportByToken.mockResolvedValue(null),],+ // A token of the wrong shape is refused before the database is asked.+ ["a malformed token", "nope", () => {}],// Restoring the project brings the link back, so this is not a 404 body// that says anything different.["an archived project",+ TOKEN,() =>mocks.getSharedReportByToken.mockResolvedValue({...SHARED_REPORT,@@ -132,25 +136,22 @@ describe("handleSharedReportRequest", () => {// Sharing is hosted-only.["a deployment that is not hosted",+ TOKEN,() => {mocks.env.AUTH_MODE = "cloudflare_access";},],- ])("answers the same 404 for %s", async (_case, arrange) => {+ ])("answers the same 404 for %s", async (_case, token, arrange) => {arrange();- const response = await handleSharedReportRequest(TOKEN, framed());+ const response = await handleSharedReportRequest(token, framed());expect(response.status).toBe(404);expect(await response.text()).toBe(NOT_SHARED_BODY);expect(response.headers.get("cache-control")).toBe("private, no-store");expect(mocks.getReportHtml).not.toHaveBeenCalled();- });-- it("answers a malformed token without querying", async () => {- const response = await handleSharedReportRequest("nope", framed());-- expect(response.status).toBe(404);- expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();+ if (token !== TOKEN) {+ expect(mocks.getSharedReportByToken).not.toHaveBeenCalled();+ }});});diff --git a/src/server/features/sam/samToolOutput.test.ts b/src/server/features/sam/samToolOutput.test.tsindex 2700685b..bd63aa23 100644--- a/src/server/features/sam/samToolOutput.test.ts+++ b/src/server/features/sam/samToolOutput.test.ts@@ -7,11 +7,6 @@ const row = (i: number) => ({ keyword: `keyword ${i}`, volume: i * 10 });const capped = z.object({ truncated: z.string() }).loose();describe("capToolOutput", () => {- it("returns small results untouched", () => {- const value = { summary: "ok", data: { rows: [row(1)] } };- expect(capToolOutput(value)).toBe(value);- });-it("halves the largest array until the result fits and says so", () => {const rows = Array.from({ length: 800 }, (_, i) => row(i));const value = { summary: "800 keywords", data: { rows } };diff --git a/src/server/features/sam/samTurnTelemetry.test.ts b/src/server/features/sam/samTurnTelemetry.test.tsindex 493c55bf..24a47e96 100644--- a/src/server/features/sam/samTurnTelemetry.test.ts+++ b/src/server/features/sam/samTurnTelemetry.test.ts@@ -39,7 +39,12 @@ const toolCall = (overrides: Record<string, unknown> = {}) =>describe("SamTurnStats", () => {it("sums steps and tool calls into the turn event, counting {error} outputs as failures", () => {const stats = new SamTurnStats();- stats.recordStep(step(), 0.01);+ // Each generation is linked to the turn as its trace.+ expect(stats.recordStep(step(), 0.01)).toMatchObject({+ $ai_trace_id: stats.turnId,+ $ai_parent_id: stats.turnId,+ $ai_model: "openai/gpt-5.6-luna",+ });stats.recordStep(step({ toolCalls: [], finishReason: "stop" }), 0.02);stats.recordSpend(0.03);stats.recordToolCall(toolCall());@@ -63,19 +68,6 @@ describe("SamTurnStats", () => {tools: ["research_keywords", "read_pages"],tool_ms: 360,});- });-- it("links each generation to the turn as its trace", () => {- const stats = new SamTurnStats();- const generation = stats.recordStep(step(), 0.01);- expect(generation).toMatchObject({- $ai_trace_id: stats.turnId,- $ai_parent_id: stats.turnId,- $ai_model: "openai/gpt-5.6-luna",- $ai_input_tokens: 1000,- $ai_total_cost_usd: 0.01,- $ai_tools_called: "research_keywords",- });expect(stats.traceProperties("error", "boom")).toMatchObject({$ai_trace_id: stats.turnId,$ai_is_error: true,diff --git a/src/server/lib/audit/crawl-window.test.ts b/src/server/lib/audit/crawl-window.test.tsindex 587096ff..af3d2ba5 100644--- a/src/server/lib/audit/crawl-window.test.ts+++ b/src/server/lib/audit/crawl-window.test.ts@@ -1,8 +1,5 @@import { describe, expect, it } from "vitest";-import {- adjustCrawlWindow,- RETRY_CRAWL_WINDOW,-} from "@/server/lib/audit/crawl-window";+import { adjustCrawlWindow } from "@/server/lib/audit/crawl-window";import type { CrawledPageResult } from "@/server/lib/audit/types";import type { PageFetchClass } from "@/shared/audit-fetch-class";@@ -56,19 +53,12 @@ describe("adjustCrawlWindow", () => {expect(adjustCrawlWindow(2, [])).toBe(2);});- it.each(["error", "blocked", "rate_limited"] as const)(- "reduces concurrency on %s",- (fetchClass) => {- const recent = Array.from({ length: 10 }, () => page(fetchClass, 300));- expect(adjustCrawlWindow(2, recent)).toBe(1);- },- );-- it("treats recovered 429s as trouble", () => {- const recent = Array.from({ length: 10 }, () => ({- ...page("ok", 300),- rateLimited: true,- }));+ // A 429 the retries recovered from still counts as trouble.+ it.each([+ ["a failed fetch", page("error", 300)],+ ["a recovered 429", { ...page("ok", 300), rateLimited: true }],+ ])("reduces concurrency on %s", (_case, troubled) => {+ const recent = Array.from({ length: 10 }, () => troubled);expect(adjustCrawlWindow(2, recent)).toBe(1);});@@ -82,11 +72,6 @@ describe("adjustCrawlWindow", () => {expect(adjustCrawlWindow(1, recent)).toBe(2);});- it("keeps retry chunks at one concurrent request", () => {- const recent = Array.from({ length: 25 }, () => page("ok", 400));- expect(adjustCrawlWindow(1, recent, RETRY_CRAWL_WINDOW)).toBe(1);- });-it("preserves the byte budget if page sizes increase", () => {const recent = Array.from({ length: 25 }, () =>page("ok", 300, 5 * 1024 * 1024),diff --git a/src/server/lib/audit/issues/page-reporters.test.ts b/src/server/lib/audit/issues/page-reporters.test.tsindex 32cd1d26..6405759d 100644--- a/src/server/lib/audit/issues/page-reporters.test.ts+++ b/src/server/lib/audit/issues/page-reporters.test.ts@@ -66,22 +66,14 @@ describe("runPageReporters", () => {expect(issueTypes(makePage({}))).toEqual([]);});- it("reports only blocked-page for a blocked fetch", () => {- expect(- issueTypes(makePage({ fetchClass: "blocked", statusCode: 403 })),- ).toEqual(["blocked-page"]);- });-- it("reports only rate-limited-page for a fetch the site kept 429ing", () => {- expect(- issueTypes(makePage({ fetchClass: "rate_limited", statusCode: 429 })),- ).toEqual(["rate-limited-page"]);- });-- it("reports nothing for a fetch error", () => {- expect(- issueTypes(makePage({ fetchClass: "error", statusCode: 0 })),- ).toEqual([]);+ // A fetch that never produced a page yields exactly its fetch issue, and+ // none of the content checks.+ it.each([+ [{ fetchClass: "blocked", statusCode: 403 }, ["blocked-page"]],+ [{ fetchClass: "rate_limited", statusCode: 429 }, ["rate-limited-page"]],+ [{ fetchClass: "error", statusCode: 0 }, []],+ ] as const)("reports %o as %j", (overrides, expected) => {+ expect(issueTypes(makePage(overrides))).toEqual(expected);});it("classifies error statuses by range", () => {@@ -97,26 +89,37 @@ describe("runPageReporters", () => {).toEqual([]);});- it("checks titles and meta descriptions", () => {- expect(issueTypes(makePage({ title: "" }))).toContain("missing-title");- expect(issueTypes(makePage({ title: "x".repeat(70) }))).toContain(- "title-too-long",- );- expect(issueTypes(makePage({ title: "Tiny" }))).toContain(- "title-too-short",- );- expect(issueTypes(makePage({ metaDescription: "" }))).toContain(- "missing-meta-description",- );- expect(- issueTypes(makePage({ metaDescription: "x".repeat(200) })),- ).toContain("meta-description-too-long");- expect(issueTypes(makePage({ metaDescription: "x".repeat(69) }))).toContain(- "meta-description-too-short",- );- expect(- issueTypes(makePage({ metaDescription: "x".repeat(70) })),- ).not.toContain("meta-description-too-short");+ it.each<[Partial<CrawledPageResult>, string]>([+ [{ title: "" }, "missing-title"],+ [{ title: "x".repeat(70) }, "title-too-long"],+ [{ title: "Tiny" }, "title-too-short"],+ [{ metaDescription: "" }, "missing-meta-description"],+ [{ metaDescription: "x".repeat(200) }, "meta-description-too-long"],+ [{ metaDescription: "x".repeat(69) }, "meta-description-too-short"],+ [{ h1Count: 0 }, "missing-h1"],+ [{ h1Count: 3 }, "multiple-h1"],+ [{ headingOrder: [1, 2, 4] }, "heading-order-skip"],+ [{ wordCount: 50 }, "thin-content"],+ [{ responseTimeMs: 3000 }, "slow-response"],+ [{ crawlDepth: 6 }, "deep-page"],+ [{ links: [] }, "no-outgoing-links"],+ ])("flags %o as %s", (overrides, issueType) => {+ expect(issueTypes(makePage(overrides))).toContain(issueType);+ });++ it.each<[Partial<CrawledPageResult>, string]>([+ [{ metaDescription: "x".repeat(70) }, "meta-description-too-short"],+ [+ { wordCount: 50, isIndexable: false, robotsMeta: "noindex" },+ "thin-content",+ ],+ [{ crawlDepth: null }, "deep-page"],+ [{ links: [], isIndexable: false }, "no-outgoing-links"],+ ])("does not flag %o as %s", (overrides, issueType) => {+ expect(issueTypes(makePage(overrides))).not.toContain(issueType);+ });++ it("reports the measured length with a short meta description", () => {expect(runPageReporters(makePage({ metaDescription: "x".repeat(69) })).find((issue) => issue.issueType === "meta-description-too-short",@@ -124,41 +127,32 @@ describe("runPageReporters", () => {).toEqual({ length: 69 });});- it("checks headings", () => {- expect(issueTypes(makePage({ h1Count: 0 }))).toContain("missing-h1");- expect(issueTypes(makePage({ h1Count: 3 }))).toContain("multiple-h1");- expect(issueTypes(makePage({ headingOrder: [1, 2, 4] }))).toContain(- "heading-order-skip",- );- });-- it("skips content checks for non-HTML responses", () => {- const nonHtml = makePage({- isHtml: false,- title: "",- metaDescription: "",- h1Count: 0,- headingOrder: [],- wordCount: 0,- contentHash: null,- });- expect(issueTypes(nonHtml)).toEqual([]);- });-- it("still checks empty-shell HTML pages", () => {- const shell = makePage({- isHtml: true,- title: "",- metaDescription: "",- h1Count: 0,- headingOrder: [],- wordCount: 0,- contentHash: null,- });- const types = issueTypes(shell);- expect(types).toContain("missing-title");- expect(types).toContain("missing-h1");- expect(types).toContain("thin-content");+ // The same empty shell: a PDF gets no content checks, an HTML page all of them.+ it.each([+ [false, []],+ [+ true,+ [+ "missing-title",+ "missing-meta-description",+ "missing-h1",+ "thin-content",+ ],+ ],+ ])("with isHtml %s an empty shell reports %j", (isHtml, expected) => {+ expect(+ issueTypes(+ makePage({+ isHtml,+ title: "",+ metaDescription: "",+ h1Count: 0,+ headingOrder: [],+ wordCount: 0,+ contentHash: null,+ }),+ ),+ ).toEqual(expected);});it("flags indexability and canonical signals", () => {@@ -179,35 +173,6 @@ describe("runPageReporters", () => {issueTypes(makePage({ canonicalUrl: "https://example.com/a" })),).not.toContain("canonicalized-page");});-- it("flags thin content only on indexable pages", () => {- expect(issueTypes(makePage({ wordCount: 50 }))).toContain("thin-content");- expect(- issueTypes(- makePage({ wordCount: 50, isIndexable: false, robotsMeta: "noindex" }),- ),- ).not.toContain("thin-content");- });-- it("flags slow responses and deep pages", () => {- expect(issueTypes(makePage({ responseTimeMs: 3000 }))).toContain(- "slow-response",- );- expect(issueTypes(makePage({ crawlDepth: 6 }))).toContain("deep-page");- expect(issueTypes(makePage({ crawlDepth: null }))).not.toContain(- "deep-page",- );- });-- it("flags indexable pages with no outgoing links", () => {- expect(issueTypes(makePage({ links: [] }))).toContain("no-outgoing-links");- expect(- issueTypes(makePage({ links: [], isIndexable: false })),- ).not.toContain("no-outgoing-links");- expect(issueTypes(makePage({ links: [HEALTHY_LINK] }))).not.toContain(- "no-outgoing-links",- );- });});function makeSlimPage(overrides: Partial<SlimPage>): SlimPage {@@ -244,7 +209,7 @@ describe("findDuplicates", () => {]);});- it("excludes noindexed and canonicalized pages from duplicate groups", () => {+ it("excludes noindexed, canonicalized, and blocked pages from duplicate groups", () => {const issues = findDuplicates([makeSlimPage({ url: "https://example.com/a", title: "Same" }),makeSlimPage({@@ -257,15 +222,8 @@ describe("findDuplicates", () => {title: "Same",isIndexable: false,}),- ]);- expect(issues).toHaveLength(0);- });-- it("ignores non-2xx and blocked pages", () => {- const issues = findDuplicates([- makeSlimPage({ url: "https://example.com/a", title: "Same" }),makeSlimPage({- url: "https://example.com/b",+ url: "https://example.com/d",title: "Same",fetchClass: "blocked",statusCode: 403,@@ -324,20 +282,20 @@ describe("findRedirectChainsAndLoops", () => {]);});- it("flags loops", () => {- const issues = findRedirectChainsAndLoops([- redirect("https://example.com/a", "https://example.com/b"),- redirect("https://example.com/b", "https://example.com/a"),- ]);- expect(- issues.filter((issue) => issue.issueType === "redirect-loop").length,- ).toBeGreaterThan(0);- });-- it("flags self-loops", () => {- const issues = findRedirectChainsAndLoops([- redirect("https://example.com/a", "https://example.com/a"),- ]);+ it.each([+ [+ "a two-page loop",+ [+ redirect("https://example.com/a", "https://example.com/b"),+ redirect("https://example.com/b", "https://example.com/a"),+ ],+ ],+ [+ "a self-loop",+ [redirect("https://example.com/a", "https://example.com/a")],+ ],+ ])("flags %s once", (_case, pages) => {+ const issues = findRedirectChainsAndLoops(pages);expect(issues).toHaveLength(1);expect(issues[0].issueType).toBe("redirect-loop");});diff --git a/src/server/lib/audit/lighthouse.test.ts b/src/server/lib/audit/lighthouse.test.tsindex 89c19c30..2c21a03b 100644--- a/src/server/lib/audit/lighthouse.test.ts+++ b/src/server/lib/audit/lighthouse.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";const createDataforseoClientMock = vi.hoisted(() => vi.fn());@@ -12,10 +12,6 @@ vi.mock("@/server/lib/r2", () => ({import { fetchLighthouseResult, selectLighthouseSample } from "./lighthouse";-afterEach(() => {- vi.clearAllMocks();-});-describe("selectLighthouseSample", () => {it("includes a start page reached through a trailing-slash redirect", () => {const pages = [diff --git a/src/server/lib/audit/url-policy.test.ts b/src/server/lib/audit/url-policy.test.tsindex f09c43f6..d1d436cd 100644--- a/src/server/lib/audit/url-policy.test.ts+++ b/src/server/lib/audit/url-policy.test.ts@@ -27,29 +27,14 @@ describe("normalizeAndValidateStartUrl", () => {).resolves.toBe("https://example.com/path");});- it("blocks localhost-like targets", async () => {- await expect(- normalizeAndValidateStartUrl("http://localhost:3000"),- ).rejects.toMatchObject({- code: "CRAWL_TARGET_BLOCKED",- } satisfies Partial<AppError>);- });-- it("blocks private ip targets", async () => {- await expect(- normalizeAndValidateStartUrl("http://192.168.0.10"),- ).rejects.toMatchObject({- code: "CRAWL_TARGET_BLOCKED",- } satisfies Partial<AppError>);- });-- it("rejects invalid URL input", async () => {- await expect(- normalizeAndValidateStartUrl("not a url"),- ).rejects.toMatchObject({- code: "VALIDATION_ERROR",- } satisfies Partial<AppError>);- });+ it.each(["http://localhost:3000", "http://192.168.0.10"])(+ "blocks %s",+ async (url) => {+ await expect(normalizeAndValidateStartUrl(url)).rejects.toMatchObject({+ code: "CRAWL_TARGET_BLOCKED",+ } satisfies Partial<AppError>);+ },+ );});const dnsOk = () =>@@ -90,22 +75,6 @@ describe("resolveStartUrlRedirects", () => {).resolves.toMatchObject({ url: "https://example.com/" });});- it("follows an apex-to-www redirect chain", async () => {- stubFetch({- "https://example.com/": () => redirect("https://www.example.com/"),- });- await expect(- resolveStartUrlRedirects("https://example.com/"),- ).resolves.toMatchObject({ url: "https://www.example.com/" });- });-- it("returns the original URL when the site does not redirect", async () => {- stubFetch({});- await expect(- resolveStartUrlRedirects("https://example.com/"),- ).resolves.toMatchObject({ url: "https://example.com/" });- });-it("returns the last URL when the probe fails", async () => {vi.mocked(fetch).mockRejectedValue(new Error("network down"));await expect(diff --git a/src/server/lib/audit/url-utils.test.ts b/src/server/lib/audit/url-utils.test.tsindex 09367a57..082a6801 100644--- a/src/server/lib/audit/url-utils.test.ts+++ b/src/server/lib/audit/url-utils.test.ts@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";import {canonicalUrlKey,detectUrlTemplate,- getOrigin,isSameOrigin,normalizeUrl,} from "@/server/lib/audit/url-utils";@@ -25,54 +24,29 @@ describe("normalizeUrl", () => {);});- it("preserves the absence of a trailing slash", () => {- expect(normalizeUrl("https://example.com/services")).toBe(- "https://example.com/services",- );- });-it("returns null for unsupported protocol", () => {expect(normalizeUrl("mailto:[email protected]")).toBeNull();});});describe("canonicalUrlKey", () => {- it("treats www and non-www as equal", () => {- expect(canonicalUrlKey("https://www.example.com/")).toBe(- canonicalUrlKey("https://example.com/"),- );- });-- it("treats http and https as equal", () => {- expect(canonicalUrlKey("http://example.com/")).toBe(- canonicalUrlKey("https://example.com/"),- );- });-- it("keeps the trailing-slash distinction in the path", () => {- expect(canonicalUrlKey("https://example.com/services")).not.toBe(- canonicalUrlKey("https://example.com/services/"),- );- });+ it.each(["https://www.example.com/", "http://example.com/"])(+ "treats %s as equal to https://example.com/",+ (url) => {+ expect(canonicalUrlKey(url)).toBe(+ canonicalUrlKey("https://example.com/"),+ );+ },+ );});describe("isSameOrigin", () => {- it("accepts www host equivalence", () => {- expect(- isSameOrigin("https://www.example.com/products", "https://example.com"),- ).toBe(true);- });-- it("allows http to https upgrade on default ports", () => {- expect(isSameOrigin("https://example.com/page", "http://example.com")).toBe(- true,- );- });-- it("rejects mismatched hosts", () => {- expect(isSameOrigin("https://example.org", "https://example.com")).toBe(- false,- );+ it.each([+ ["https://www.example.com/products", "https://example.com", true],+ ["https://example.com/page", "http://example.com", true],+ ["https://example.org", "https://example.com", false],+ ])("isSameOrigin(%s, %s) is %s", (url, origin, expected) => {+ expect(isSameOrigin(url, origin)).toBe(expected);});});@@ -82,16 +56,4 @@ describe("detectUrlTemplate", () => {"/blog/:date/:slug",);});-- it("maps numeric id segments", () => {- expect(detectUrlTemplate("/products/12345")).toBe("/products/:id");- });-});--describe("getOrigin", () => {- it("returns URL origin", () => {- expect(getOrigin("https://example.com:8080/path?q=1")).toBe(- "https://example.com:8080",- );- });});diff --git a/src/server/lib/dataforseo/backlinks.test.ts b/src/server/lib/dataforseo/backlinks.test.tsindex 86961f3b..c6fd682a 100644--- a/src/server/lib/dataforseo/backlinks.test.ts+++ b/src/server/lib/dataforseo/backlinks.test.ts@@ -1,22 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { AppError } from "@/server/lib/errors";vi.mock("@/server/lib/runtime-env", () => ({getRequiredEnvValue: vi.fn(async () => "test-api-key"),}));-const { classifyBacklinksError } = vi.hoisted(() => ({- classifyBacklinksError: vi.fn(),-}));--// The classifier is built inside backlinks.ts via createDataforseoBillingClassifier;-// returning our hoisted mock lets the test drive classification.-vi.mock("@/server/lib/dataforseoBillingClassification", () => ({- createDataforseoBillingClassifier: () => classifyBacklinksError,-}));-import {- fetchBacklinksHistory,fetchBacklinksRows,fetchBacklinksSummary,} from "@/server/lib/dataforseo/backlinks";@@ -41,77 +29,59 @@ function okResponse(result: unknown[]) {}describe("normalizeBacklinksTarget", () => {- it("defaults inputs with a path to a subfolder lookup", () => {- expect(- normalizeBacklinksTarget("https://github.com/every-app/open-seo/"),- ).toEqual({- apiTarget: "github.com",- displayTarget: "github.com/every-app/open-seo",- scope: "subfolder",- includeSubdomains: false,- path: "/every-app/open-seo",- });- });-- it("strips query strings and fragments for subfolder lookups", () => {- expect(- normalizeBacklinksTarget("example.com/blog?utm_source=x#hero", {+ it.each([+ {+ input: "Example.com",+ options: undefined,+ expected: {+ apiTarget: "example.com",+ displayTarget: "example.com",+ scope: "subdomains",+ includeSubdomains: true,+ path: "",+ },+ },+ {+ input: "https://github.com/every-app/open-seo/",+ options: undefined,+ expected: {+ apiTarget: "github.com",+ displayTarget: "github.com/every-app/open-seo",scope: "subfolder",- }).path,- ).toBe("/blog");- });-- it("rejects subfolder scope without a path", () => {- expectValidationError(() =>- normalizeBacklinksTarget("example.com", { scope: "subfolder" }),- );- });-- it("defaults bare hostnames to subdomains scope", () => {- expect(normalizeBacklinksTarget("Example.com")).toEqual({- apiTarget: "example.com",- displayTarget: "example.com",- scope: "subdomains",- includeSubdomains: true,- path: "",- });- });-- it("includes subdomains only for subdomains scope", () => {- expect(- normalizeBacklinksTarget("https://Example.com/pricing", {+ includeSubdomains: false,+ path: "/every-app/open-seo",+ },+ },+ {+ input: "https://Example.com/pricing",+ options: { scope: "subdomains" },+ expected: {+ apiTarget: "example.com",+ displayTarget: "example.com",scope: "subdomains",- }),- ).toEqual({- apiTarget: "example.com",- displayTarget: "example.com",- scope: "subdomains",- includeSubdomains: true,- path: "",- });- });-- it("lets callers force a page lookup for bare hostnames", () => {- expect(- normalizeBacklinksTarget("Example.com", { scope: "exact_url" }),- ).toEqual({- apiTarget: "https://example.com/",- displayTarget: "https://example.com/",- scope: "exact_url",- includeSubdomains: true,- path: "",- });- });+ includeSubdomains: true,+ path: "",+ },+ },+ ] as const)(+ "maps $input with scope $options.scope onto includeSubdomains/path",+ ({ input, options, expected }) => {+ expect(normalizeBacklinksTarget(input, options)).toEqual(expected);+ },+ );- it("maps the legacy page scope onto exact_url", () => {- expect(normalizeBacklinksTarget("Example.com", { scope: "page" })).toEqual({- apiTarget: "https://example.com/",- displayTarget: "https://example.com/",- scope: "exact_url",- includeSubdomains: true,- path: "",- });- });+ it.each(["exact_url", "page"] as const)(+ "builds an absolute page URL for bare hostnames with scope %s",+ (scope) => {+ expect(normalizeBacklinksTarget("Example.com", { scope })).toEqual({+ apiTarget: "https://example.com/",+ displayTarget: "https://example.com/",+ scope: "exact_url",+ includeSubdomains: true,+ path: "",+ });+ },+ );it("rejects exact-url targets with query strings or fragments", () => {expectValidationError(() =>@@ -121,16 +91,6 @@ describe("normalizeBacklinksTarget", () => {),);});-- it("rejects page targets with embedded credentials", () => {- expectValidationError(() =>- normalizeBacklinksTarget("https://user:[email protected]/private"),- );- });-- it("rejects hostnames with unrecognized public suffixes before provider calls", () => {- expectValidationError(() => normalizeBacklinksTarget("example.invalidtld"));- });});describe("fetchBacklinksSummary", () => {@@ -140,7 +100,6 @@ describe("fetchBacklinksSummary", () => {afterEach(() => {vi.unstubAllGlobals();- vi.clearAllMocks();});it("classifies top-level DataForSEO body errors using status_code", async () => {@@ -154,48 +113,24 @@ describe("fetchBacklinksSummary", () => {{ status: 200, headers: { "Content-Type": "application/json" } },),);- classifyBacklinksError.mockImplementation((status: number | undefined) => {- if (status === 40200) {- return new AppError(- "BACKLINKS_BILLING_ISSUE",- "The connected DataForSEO account has a billing or balance issue",- );- }- return null;- });-await expect(fetchBacklinksSummary({ target: "example.com" }),).rejects.toMatchObject({ code: "BACKLINKS_BILLING_ISSUE" });-- expect(classifyBacklinksError).toHaveBeenCalledWith(- 40200,- expect.stringContaining("Account balance is too low"),- "/v3/backlinks/summary/live",- );});- it("treats null summary results as a valid zero-data response", async () => {- vi.mocked(fetch).mockResolvedValue(okResponse([null]));- classifyBacklinksError.mockReturnValue(null);+ it.each([[[null]], [[]]])(+ "treats a %j summary result as a valid zero-data response",+ async (result) => {+ vi.mocked(fetch).mockResolvedValue(okResponse(result));- await expect(- fetchBacklinksSummary({ target: "not-a-real-input.example" }),- ).resolves.toMatchObject({ data: {} });- });-- it("treats empty summary results as a valid zero-data response", async () => {- vi.mocked(fetch).mockResolvedValue(okResponse([]));- classifyBacklinksError.mockReturnValue(null);-- await expect(- fetchBacklinksSummary({ target: "example.com" }),- ).resolves.toMatchObject({ data: {} });- });+ await expect(+ fetchBacklinksSummary({ target: "example.com" }),+ ).resolves.toMatchObject({ data: {} });+ },+ );it("asks DataForSEO to exclude subdomains for a domain-scoped target", async () => {vi.mocked(fetch).mockResolvedValue(okResponse([]));- classifyBacklinksError.mockReturnValue(null);await fetchBacklinksSummary({target: "example.com",@@ -211,34 +146,11 @@ describe("fetchBacklinksSummary", () => {]);});- it("treats empty backlinks rows and history results as valid empty arrays", async () => {- vi.mocked(fetch)- .mockResolvedValueOnce(okResponse([]))- .mockResolvedValueOnce(okResponse([]));- classifyBacklinksError.mockReturnValue(null);-- await expect(- fetchBacklinksRows({ target: "example.com" }),- ).resolves.toMatchObject({ data: { items: [], totalCount: null } });- await expect(- fetchBacklinksHistory({- target: "example.com",- dateFrom: "2025-01-01",- dateTo: "2025-12-31",- }),- ).resolves.toMatchObject({ data: [] });- });-- it.each([- ["as_is", undefined],- ["one_per_domain", undefined],- ["as_is", false],- ["one_per_domain", false],- ] as const)(- "preserves user filters and pagination for %s with hideSpam=%s",- async (mode, hideSpam) => {+ it.each([undefined, false])(+ "preserves user filters and pagination with hideSpam=%s",+ async (hideSpam) => {+ const mode = "as_is";vi.mocked(fetch).mockResolvedValue(okResponse([]));- classifyBacklinksError.mockReturnValue(null);const filters = [["domain_from", "=", "openseo.so"]];await fetchBacklinksRows({diff --git a/src/server/lib/dataforseo/business.test.ts b/src/server/lib/dataforseo/business.test.tsindex 6d0f0958..cdb91f0a 100644--- a/src/server/lib/dataforseo/business.test.ts+++ b/src/server/lib/dataforseo/business.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";vi.mock("@/server/lib/runtime-env", () => ({getRequiredEnvValue: vi.fn(async () => "test-api-key"),@@ -7,7 +7,6 @@ vi.mock("@/server/lib/runtime-env", () => ({import {fetchBusinessDataTaskResult,fetchBusinessListingsCategories,- fetchBusinessListingsSearch,fetchMyBusinessInfo,postGoogleReviewsTask,} from "@/server/lib/dataforseo/business";@@ -36,10 +35,6 @@ const okTask = (path: string[], result: unknown[]) => ({});describe("Google business_data fetchers", () => {- beforeEach(() => {- vi.restoreAllMocks();- });-it("sends a coordinate for my_business_info and returns the single item", async () => {const fetchMock = stubDataforseo(okTask(@@ -102,102 +97,50 @@ describe("Google business_data fetchers", () => {expect(result.billing.costUsd).toBe(0.002);});- it("posts regular reviews with sort_by and bills from the post entry", async () => {- const fetchMock = stubDataforseo({- status_code: 20000,- tasks: [- {- id: "task-1",- status_code: 20100,- cost: 0.00375,- path: ["v3", "business_data", "google", "reviews", "task_post"],- },- ],- });-- const result = await postGoogleReviewsTask({- cid: "123",- locationCode: 2840,- languageCode: "en",- depth: 20,- sortBy: "newest",+ it.each([+ {includeOtherSources: false,- });-- const { url, body } = requestOf(fetchMock);- expect(url).toBe(- "https://api.dataforseo.com/v3/business_data/google/reviews/task_post",- );- expect(body).toEqual([- {+ endpoint: "reviews",+ // The extended endpoint has no sort_by; the fetcher drops it.+ sortBy: { sort_by: "newest" },+ },+ { includeOtherSources: true, endpoint: "extended_reviews", sortBy: {} },+ ])(+ "posts reviews to $endpoint when includeOtherSources=$includeOtherSources and bills from the post entry",+ async ({ includeOtherSources, endpoint, sortBy }) => {+ const path = ["v3", "business_data", "google", endpoint, "task_post"];+ const fetchMock = stubDataforseo({+ status_code: 20000,+ tasks: [{ id: "task-1", status_code: 20100, cost: 0.00375, path }],+ });++ const result = await postGoogleReviewsTask({cid: "123",- location_code: 2840,- language_code: "en",+ locationCode: 2840,+ languageCode: "en",depth: 20,- sort_by: "newest",- priority: 2,- },- ]);- expect(result).toEqual({- data: "task-1",- billing: {- path: ["v3", "business_data", "google", "reviews", "task_post"],- costUsd: 0.00375,- },- });- });+ sortBy: "newest",+ includeOtherSources,+ });- it("posts to the extended_reviews endpoint when other sources are requested", async () => {- const fetchMock = stubDataforseo({- status_code: 20000,- tasks: [+ const { url, body } = requestOf(fetchMock);+ expect(url).toBe(`https://api.dataforseo.com/${path.join("/")}`);+ expect(body).toEqual([{- id: "task-2",- status_code: 20100,- cost: 0.01,- path: [- "v3",- "business_data",- "google",- "extended_reviews",- "task_post",- ],+ cid: "123",+ location_code: 2840,+ language_code: "en",+ depth: 20,+ priority: 2,+ ...sortBy,},- ],- });-- const result = await postGoogleReviewsTask({- cid: "123",- locationCode: 2840,- languageCode: "en",- depth: 20,- // The extended endpoint has no sort_by; the fetcher drops it.- sortBy: "newest",- includeOtherSources: true,- });-- const { url, body } = requestOf(fetchMock);- expect(url).toBe(- "https://api.dataforseo.com/v3/business_data/google/extended_reviews/task_post",- );- expect(body).toEqual([- {- cid: "123",- location_code: 2840,- language_code: "en",- depth: 20,- priority: 2,- },- ]);- expect(result.data).toBe("task-2");- expect(result.billing.path).toEqual([- "v3",- "business_data",- "google",- "extended_reviews",- "task_post",- ]);- });+ ]);+ expect(result).toEqual({+ data: "task-1",+ billing: { path, costUsd: 0.00375 },+ });+ },+ );it("never replays a task_post on a 5xx (a retry could double-charge)", async () => {const fetchMock = vi@@ -229,28 +172,6 @@ describe("Google business_data fetchers", () => {).resolves.toEqual({ status: "pending", result: null });});- it("returns the first result once the task completed", async () => {- const fetchMock = stubDataforseo(- okTask(- ["v3", "business_data", "google", "extended_reviews", "task_get"],- [{ reviews_count: 12, items: [{ review_text: "Great" }] }],- ),- );-- const outcome = await fetchBusinessDataTaskResult({- endpoint: "extended_reviews",- taskId: "task-9",- });-- expect(requestOf(fetchMock).url).toBe(- "https://api.dataforseo.com/v3/business_data/google/extended_reviews/task_get/task-9",- );- expect(outcome).toEqual({- status: "completed",- result: { reviews_count: 12, items: [{ review_text: "Great" }] },- });- });-it("maps the free categories list onto category/businessCount rows", async () => {stubDataforseo(okTask(@@ -269,33 +190,4 @@ describe("Google business_data fetchers", () => {{ category: "plumber", businessCount: null },]);});-- it("forwards business-listing filters, claim status, and offset", async () => {- const fetchMock = stubDataforseo(- okTask(- ["v3", "business_data", "business_listings", "search", "live"],- [{ items: [] }],- ),- );-- await fetchBusinessListingsSearch({- locationCoordinate: "33.1,-84.9,5",- isClaimed: false,- filters: [["rating.value", ">=", 4]],- orderBy: ["rating.value,desc"],- limit: 20,- offset: 10,- });-- expect(requestOf(fetchMock).body).toEqual([- {- location_coordinate: "33.1,-84.9,5",- is_claimed: false,- filters: [["rating.value", ">=", 4]],- order_by: ["rating.value,desc"],- limit: 20,- offset: 10,- },- ]);- });});diff --git a/src/server/lib/dataforseo/client.test.ts b/src/server/lib/dataforseo/client.test.tsindex cfcf50e8..eb317506 100644--- a/src/server/lib/dataforseo/client.test.ts+++ b/src/server/lib/dataforseo/client.test.ts@@ -1,5 +1,5 @@/* eslint-disable max-lines */-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import {AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,creditsForProviderUsd,@@ -176,10 +176,6 @@ function mockDataforseoResult(costUsd: number) {}describe("meterDataforseoCall", () => {- beforeEach(() => {- vi.clearAllMocks();- });-it("skips billing in non-hosted mode", async () => {isHostedServerAuthModeMock.mockResolvedValue(false);mockDataforseoResult(RAW_COST);@@ -292,181 +288,29 @@ describe("meterDataforseoCall", () => {});describe("mapDataforseoPathToCreditFeature", () => {- it("maps real keyword research paths", () => {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "dataforseo_labs",- "google",- "related_keywords",- "live",- ]),- ).toBe("keyword_research");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "dataforseo_labs",- "google",- "keyword_suggestions",- "live",- ]),- ).toBe("keyword_research");- });-- it("maps real serp paths", () => {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "serp",- "google",- "organic",- "live",- "regular",- ]),- ).toBe("keyword_research");- });-- it("maps real domain paths", () => {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "dataforseo_labs",- "google",- "domain_rank_overview",- "live",- ]),- ).toBe("domain_overview");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "dataforseo_labs",- "google",- "ranked_keywords",- "live",- ]),- ).toBe("domain_overview");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "dataforseo_labs",- "google",- "relevant_pages",- "live",- ]),- ).toBe("domain_overview");- });-- it("maps real backlinks paths", () => {- expect(- mapDataforseoPathToCreditFeature(["v3", "backlinks", "summary", "live"]),- ).toBe("backlinks");- expect(mapDataforseoPathToCreditFeature(["backlinks", "summary"])).toBe(- "backlinks",- );- expect(- mapDataforseoPathToCreditFeature([- "v3",- "backlinks",- "referring_domains",- "live",- ]),- ).toBe("backlinks");- });-- it("maps real lighthouse/on_page paths to site_audit", () => {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "on_page",- "lighthouse",- "live",- "json",- ]),- ).toBe("site_audit");- });-- it("maps ai_optimization llm_mentions paths to ai_citations", () => {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "ai_optimization",- "llm_mentions",- "search",- "live",- ]),- ).toBe("ai_citations");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "ai_optimization",- "llm_mentions",- "aggregated_metrics",- "live",- ]),- ).toBe("ai_citations");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "ai_optimization",- "llm_mentions",- "top_pages",- "live",- ]),- ).toBe("ai_citations");- });-- it("maps ai_optimization provider llm_responses paths to ai_prompt_responses", () => {- for (const provider of ["chat_gpt", "claude", "gemini", "perplexity"]) {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "ai_optimization",- provider,- "llm_responses",- "live",- ]),- ).toBe("ai_prompt_responses");- }- });-- it("maps local and supporting paths to the intended credit features", () => {- expect(- mapDataforseoPathToCreditFeature([- "v3",- "business_data",- "business_listings",- "search",- "live",- ]),- ).toBe("local_seo");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "serp",- "google",- "local_finder",- "live",- "advanced",- ]),- ).toBe("local_seo");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "serp",- "google",- "maps",- "live",- "advanced",- ]),- ).toBe("local_seo");- expect(- mapDataforseoPathToCreditFeature([- "v3",- "keywords_data",- "google_ads",- "search_volume",- "live",- ]),- ).toBe("keyword_research");+ it.each([+ ["v3/dataforseo_labs/google/related_keywords/live", "keyword_research"],+ ["v3/dataforseo_labs/google/keyword_suggestions/live", "keyword_research"],+ ["v3/serp/google/organic/live/regular", "keyword_research"],+ ["v3/keywords_data/google_ads/search_volume/live", "keyword_research"],+ ["v3/dataforseo_labs/google/domain_rank_overview/live", "domain_overview"],+ ["v3/dataforseo_labs/google/ranked_keywords/live", "domain_overview"],+ ["v3/dataforseo_labs/google/relevant_pages/live", "domain_overview"],+ ["v3/backlinks/summary/live", "backlinks"],+ ["backlinks/summary", "backlinks"],+ ["v3/backlinks/referring_domains/live", "backlinks"],+ ["v3/on_page/lighthouse/live/json", "site_audit"],+ ["v3/ai_optimization/llm_mentions/search/live", "ai_citations"],+ ["v3/ai_optimization/llm_mentions/aggregated_metrics/live", "ai_citations"],+ ["v3/ai_optimization/llm_mentions/top_pages/live", "ai_citations"],+ ["v3/ai_optimization/chat_gpt/llm_responses/live", "ai_prompt_responses"],+ ["v3/ai_optimization/claude/llm_responses/live", "ai_prompt_responses"],+ ["v3/ai_optimization/gemini/llm_responses/live", "ai_prompt_responses"],+ ["v3/ai_optimization/perplexity/llm_responses/live", "ai_prompt_responses"],+ ["v3/business_data/business_listings/search/live", "local_seo"],+ ["v3/serp/google/local_finder/live/advanced", "local_seo"],+ ["v3/serp/google/maps/live/advanced", "local_seo"],+ ])("maps %s to %s", (path, feature) => {+ expect(mapDataforseoPathToCreditFeature(path.split("/"))).toBe(feature);});});diff --git a/src/server/lib/dataforseo/endpoints.test.ts b/src/server/lib/dataforseo/endpoints.test.tsindex 3046ce91..67b972e9 100644--- a/src/server/lib/dataforseo/endpoints.test.ts+++ b/src/server/lib/dataforseo/endpoints.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";vi.mock("@/server/lib/runtime-env", () => ({getRequiredEnvValue: vi.fn(async () => "test-api-key"),@@ -6,11 +6,8 @@ vi.mock("@/server/lib/runtime-env", () => ({import { fetchQuestionsAnswers } from "@/server/lib/dataforseo/business";import {- fetchLlmAggregatedMetrics,fetchLlmCrossAggregatedMetrics,- fetchLlmMentionsSearch,fetchLlmResponse,- fetchLlmTopPages,} from "@/server/lib/dataforseo/ai";import { buildLlmTarget } from "@/server/lib/dataforseo/shared";@@ -23,10 +20,6 @@ function parseDataforseoRequestBody(init: RequestInit | undefined): unknown {}describe("DataForSEO SDK-backed endpoints", () => {- beforeEach(() => {- vi.restoreAllMocks();- });-it("uses the live endpoint for Google Business Q&A and returns items + billing", async () => {const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({@@ -84,102 +77,6 @@ describe("DataForSEO SDK-backed endpoints", () => {});});- it("serializes LLM mentions domain targets for search, top pages, and aggregated endpoints", async () => {- const fetchMock = vi.fn<typeof fetch>().mockImplementation((url) => {- const path =- typeof url === "string" || url instanceof URL- ? url.toString()- : url.url;- const result = path.includes("/aggregated_metrics/")- ? { total: { platform: [] } }- : { items: [] };-- return Promise.resolve(- Response.json({- status_code: 20000,- tasks: [- {- status_code: 20000,- path: new URL(path).pathname.split("/").filter(Boolean),- cost: 0.0001,- result_count: 1,- result: [result],- },- ],- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- const target = buildLlmTarget({- type: "domain",- value: "example.com",- });-- await fetchLlmMentionsSearch({- target,- platform: "google",- locationCode: 2840,- languageCode: "en",- });- await fetchLlmAggregatedMetrics({- target,- platform: "google",- locationCode: 2840,- languageCode: "en",- });- await fetchLlmTopPages({- target,- platform: "google",- locationCode: 2840,- languageCode: "en",- itemsListLimit: 10,- });- const expectedTarget = [- {- search_scope: ["any"],- search_filter: "include",- domain: "example.com",- include_subdomains: true,- },- ];- const payloads = fetchMock.mock.calls.map(([, init]) =>- parseDataforseoRequestBody(init),- );-- expect(payloads).toEqual([- [- {- target: expectedTarget,- location_code: 2840,- language_code: "en",- platform: "google",- limit: 100,- },- ],- [- {- target: expectedTarget,- location_code: 2840,- language_code: "en",- platform: "google",- internal_list_limit: 10,- },- ],- [- {- target: expectedTarget,- location_code: 2840,- language_code: "en",- platform: "google",- links_scope: "sources",- items_list_limit: 10,- internal_list_limit: 5,- },- ],- ]);- });-it("serializes cross-aggregated target groups", async () => {const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({@@ -253,51 +150,6 @@ describe("DataForSEO SDK-backed endpoints", () => {]);});- it("serializes LLM mentions keyword targets", async () => {- const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(- Response.json({- status_code: 20000,- tasks: [- {- status_code: 20000,- path: ["v3", "ai_optimization", "llm_mentions", "search", "live"],- cost: 0.0001,- result_count: 1,- result: [{ items: [] }],- },- ],- }),- );- vi.stubGlobal("fetch", fetchMock);-- await fetchLlmMentionsSearch({- target: buildLlmTarget({- type: "keyword",- value: "Acme Storage",- }),- platform: "chat_gpt",- locationCode: 2840,- languageCode: "en",- });-- expect(parseDataforseoRequestBody(fetchMock.mock.calls[0]?.[1])).toEqual([- {- target: [- {- search_scope: ["any", "brand_entities"],- search_filter: "include",- keyword: "Acme Storage",- match_type: "word_match",- },- ],- location_code: 2840,- language_code: "en",- platform: "chat_gpt",- limit: 100,- },- ]);- });-it("preserves web_search for Perplexity LLM responses", async () => {const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({@@ -358,10 +210,6 @@ describe("DataForSEO SDK-backed endpoints", () => {});describe("fetchLlmResponse model_name validation", () => {- beforeEach(() => {- vi.restoreAllMocks();- });-it("rejects an unknown model_name before dispatching a paid LLM task", async () => {const fetchMock = vi.fn<typeof fetch>();vi.stubGlobal("fetch", fetchMock);diff --git a/src/server/lib/dataforseo/envelope.test.ts b/src/server/lib/dataforseo/envelope.test.tsindex e4f8deb4..429b173a 100644--- a/src/server/lib/dataforseo/envelope.test.ts+++ b/src/server/lib/dataforseo/envelope.test.ts@@ -10,34 +10,15 @@ import { AppError } from "@/server/lib/errors";const itemSchema = z.object({ keyword: z.string().optional() }).passthrough();describe("parseTaskItems", () => {- it("returns [] when the result items are null", () => {- const task = { status_code: 20000, result: [{ items: null }] };+ it.each([+ { status_code: 20000, result: [{ items: null }] },+ { result: undefined },+ ])("returns [] for a task without items (%o)", (task) => {expect(parseTaskItems("x", task, itemSchema)).toEqual([]);});-- it("returns [] when there is no result", () => {- expect(parseTaskItems("x", { result: undefined }, itemSchema)).toEqual([]);- });-- it("parses present items", () => {- const task = { result: [{ items: [{ keyword: "seo" }] }] };- expect(parseTaskItems("x", task, itemSchema)).toEqual([{ keyword: "seo" }]);- });});describe("assertOk", () => {- const okTask = {- status_code: 20000,- path: ["v3", "backlinks", "summary", "live"],- cost: 0.1,- result_count: 1,- result: [],- };-- it("returns the first task on success", () => {- expect(assertOk({ status_code: 20000, tasks: [okTask] })).toBe(okTask);- });-it("throws DataforseoChargedTaskError when a charged task fails", () => {const task = {status_code: 40000,@@ -60,122 +41,65 @@ describe("assertOk", () => {}});- it("classifies DataForSEO's own server errors as UPSTREAM_UNAVAILABLE", () => {- vi.spyOn(console, "error").mockImplementation(() => {});- const task = {- status_code: 40101,- status_message: "Internal SE Server Error.",- path: ["v3", "serp", "google", "organic", "live", "advanced"],- cost: 0.002,- result_count: 0,- };- try {- assertOk({ status_code: 20000, tasks: [task] });- throw new Error("expected assertOk to throw");- } catch (error) {- // Still a charged-task error so the billed attempt stays metered.- expect(error).toBeInstanceOf(DataforseoChargedTaskError);- if (error instanceof DataforseoChargedTaskError) {- expect(error.code).toBe("UPSTREAM_UNAVAILABLE");+ it.each([+ // DataForSEO's own SE failure: retryable upstream trouble.+ [40101, "Internal SE Server Error.", "UPSTREAM_UNAVAILABLE"],+ // 'Not Implemented' means we posted a bad task; keep it reportable.+ [50100, "Not Implemented.", "INTERNAL_ERROR"],+ ] as const)(+ "classifies a charged %s '%s' task as %s",+ (status, message, code) => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ const task = {+ status_code: status,+ status_message: message,+ path: ["v3", "serp", "google", "organic", "live", "advanced"],+ cost: 0.002,+ result_count: 0,+ };+ try {+ assertOk({ status_code: 20000, tasks: [task] });+ throw new Error("expected assertOk to throw");+ } catch (error) {+ // Still a charged-task error so the billed attempt stays metered.+ expect(error).toBeInstanceOf(DataforseoChargedTaskError);+ if (error instanceof DataforseoChargedTaskError) {+ expect(error.code).toBe(code);+ }}- }- });+ },+ );- it("keeps 'Not Implemented' reportable — we posted a bad task", () => {+ it("uses the classifier for account failures before charging billed task metadata", () => {+ const classify = vi.fn(+ () =>+ new AppError(+ "BACKLINKS_BILLING_ISSUE",+ "Classified DataForSEO account failure",+ ),+ );const task = {- status_code: 50100,- status_message: "Not Implemented.",- path: ["v3", "serp", "google", "organic", "live", "advanced"],- cost: 0.002,+ status_code: 40200,+ status_message: "Account balance is too low",+ path: ["v3", "backlinks", "summary", "live"],+ cost: 0.05,result_count: 0,};- try {- assertOk({ status_code: 20000, tasks: [task] });- throw new Error("expected assertOk to throw");- } catch (error) {- expect(error).toBeInstanceOf(DataforseoChargedTaskError);- if (error instanceof DataforseoChargedTaskError) {- expect(error.code).toBe("INTERNAL_ERROR");- }- }- });- it("appends the echoed request value to opaque 'Invalid Field' failures", () => {- const task = {- status_code: 40501,- status_message: "Invalid Field: 'target'.",- path: ["v3", "dataforseo_labs", "google", "domain_rank_overview", "live"],- cost: 0.02,- result_count: 0,- data: { target: "not a valid domain", language_code: "en" },- };try {- assertOk({ status_code: 20000, tasks: [task] });+ assertOk({ status_code: 20000, tasks: [task] }, { classify });throw new Error("expected assertOk to throw");} catch (error) {- expect(error).toBeInstanceOf(DataforseoChargedTaskError);- if (error instanceof DataforseoChargedTaskError) {- expect(error.message).toBe(- `Invalid Field: 'target'. (sent target="not a valid domain")`,- );- }+ expect(error).not.toBeInstanceOf(DataforseoChargedTaskError);+ expect(error).toMatchObject({ code: "BACKLINKS_BILLING_ISSUE" });}- });-- it("uses the classifier for non-charged (no-cost) failures", () => {- const classify = vi.fn(- () => new AppError("BACKLINKS_BILLING_ISSUE", "nope"),- );- const task = {- status_code: 40200,- status_message: "balance is too low",- };- expect(() =>- assertOk(- { status_code: 20000, tasks: [task] },- { classify, classifyPath: "/v3/backlinks/summary/live" },- ),- ).toThrow("nope");expect(classify).toHaveBeenCalledWith(40200,- "balance is too low",+ "Account balance is too low","/v3/backlinks/summary/live",);});- it.each([- [40200, "BACKLINKS_BILLING_ISSUE"],- [40210, "BACKLINKS_BILLING_ISSUE"],- [402, "BACKLINKS_BILLING_ISSUE"],- ] as const)(- "uses the classifier for account failure %s before charging billed task metadata",- (status, code) => {- const classify = vi.fn(- () => new AppError(code, "Classified DataForSEO account failure"),- );- const task = {- status_code: status,- status_message: "Account balance is too low",- path: ["v3", "backlinks", "summary", "live"],- cost: 0.05,- result_count: 0,- };-- try {- assertOk({ status_code: 20000, tasks: [task] }, { classify });- throw new Error("expected assertOk to throw");- } catch (error) {- expect(error).not.toBeInstanceOf(DataforseoChargedTaskError);- expect(error).toMatchObject({ code });- }- expect(classify).toHaveBeenCalledWith(- status,- "Account balance is too low",- "/v3/backlinks/summary/live",- );- },- );-it("treats 40501 as an empty success when asked", () => {const task = {status_code: 40501,@@ -212,6 +136,7 @@ describe("assertOk", () => {expect(error).toBeInstanceOf(DataforseoChargedTaskError);if (error instanceof DataforseoChargedTaskError) {expect(error.billing).toEqual({ path: task.path, costUsd: 0.02 });+ expect(error.isInvalidField).toBe(true);}}});diff --git a/src/server/lib/dataforseo/labs.test.ts b/src/server/lib/dataforseo/labs.test.tsindex 5895acd1..78a4be33 100644--- a/src/server/lib/dataforseo/labs.test.ts+++ b/src/server/lib/dataforseo/labs.test.ts@@ -1,9 +1,5 @@import { afterEach, expect, it, vi } from "vitest";-import {- fetchRelatedKeywords,- fetchKeywordSuggestions,- fetchKeywordIdeas,-} from "./labs";+import { fetchRelatedKeywords } from "./labs";vi.mock("@/server/lib/runtime-env", () => ({getRequiredEnvValue: vi.fn(async () => "test-api-key"),@@ -11,16 +7,14 @@ vi.mock("@/server/lib/runtime-env", () => ({afterEach(() => vi.unstubAllGlobals());-it("sends synonym filtering for every Labs research source and preserves omitted defaults", async () => {- const fetchMock = vi.fn<typeof fetch>().mockImplementation(async (url) =>+it("sends ignoreSynonyms to DataForSEO as ignore_synonyms", async () => {+ const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({status_code: 20000,tasks: [{status_code: 20000,- path: new URL(url instanceof Request ? url.url : url).pathname- .split("/")- .filter(Boolean),+ path: ["v3", "dataforseo_labs", "google", "related_keywords", "live"],cost: 0,result: [{ items: [] }],},@@ -28,25 +22,18 @@ it("sends synonym filtering for every Labs research source and preserves omitted}),);vi.stubGlobal("fetch", fetchMock);- for (const fetchKeywords of [- fetchRelatedKeywords,- fetchKeywordSuggestions,- fetchKeywordIdeas,- ]) {- for (const ignoreSynonyms of [true, false, undefined]) {- await fetchKeywords({- keyword: "caregiving",- locationCode: 2840,- languageCode: "en",- limit: 150,- ignoreSynonyms,- });- const body = fetchMock.mock.lastCall?.[1]?.body;- if (typeof body !== "string")- throw new Error("Expected JSON request body");- expect(JSON.parse(body)).toEqual([- expect.objectContaining({ ignore_synonyms: ignoreSynonyms ?? false }),- ]);- }- }++ await fetchRelatedKeywords({+ keyword: "caregiving",+ locationCode: 2840,+ languageCode: "en",+ limit: 150,+ ignoreSynonyms: true,+ });++ const body = fetchMock.mock.lastCall?.[1]?.body;+ if (typeof body !== "string") throw new Error("Expected JSON request body");+ expect(JSON.parse(body)).toEqual([+ expect.objectContaining({ ignore_synonyms: true }),+ ]);});diff --git a/src/server/lib/dataforseo/researchScopeFilters.test.ts b/src/server/lib/dataforseo/researchScopeFilters.test.tsindex 62ee99d7..52a679b0 100644--- a/src/server/lib/dataforseo/researchScopeFilters.test.ts+++ b/src/server/lib/dataforseo/researchScopeFilters.test.ts@@ -21,12 +21,6 @@ function target(}describe("buildRankedKeywordsScopeFilter", () => {- it("adds nothing for subdomains scope", () => {- expect(- buildRankedKeywordsScopeFilter(target("example.com", "subdomains")),- ).toEqual({ clauses: [], conditionCount: 0 });- });-it("pins the exact hostname (plus www) for domain scope", () => {const filter = buildRankedKeywordsScopeFilter(target("example.com", "domain"),diff --git a/src/server/lib/dataforseo/serp.test.ts b/src/server/lib/dataforseo/serp.test.tsindex c0e3da4a..4c43e96b 100644--- a/src/server/lib/dataforseo/serp.test.ts+++ b/src/server/lib/dataforseo/serp.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";vi.mock("@/server/lib/runtime-env", () => ({getRequiredEnvValue: vi.fn(async () => "test-api-key"),@@ -56,10 +56,6 @@ describe("live SERP", () => {});describe("rank check task queue", () => {- beforeEach(() => {- vi.restoreAllMocks();- });-it("posts queued tasks, maps ids by tag, and sums cost over all entries", async () => {const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(Response.json({diff --git a/src/server/lib/dataforseoBillingClassification.test.ts b/src/server/lib/dataforseoBillingClassification.test.tsindex 77ca5720..1e985e86 100644--- a/src/server/lib/dataforseoBillingClassification.test.ts+++ b/src/server/lib/dataforseoBillingClassification.test.ts@@ -8,10 +8,21 @@ const classify = createDataforseoBillingClassifier({});describe("createDataforseoBillingClassifier", () => {- it("returns null when the path is outside the configured prefix", () => {- expect(classify(402, "payment required", "/v3/serp/google/live")).toBe(- null,- );+ it.each([+ [+ "the path is outside the configured prefix",+ 402,+ "payment required",+ "/v3/serp/google/live",+ ],+ [+ "neither status nor text matches",+ 500,+ "boom",+ "/v3/backlinks/summary/live",+ ],+ ])("returns null when %s", (_label, status, message, path) => {+ expect(classify(status, message, path)).toBe(null);});it.each([40200, 40210, 402])(@@ -22,34 +33,7 @@ describe("createDataforseoBillingClassifier", () => {},);- it.each([- "insufficient funds",- "payment required",- "balance is too low",- "problem billing",- "account was not recharged",- ])(- "translates billing signal %s into the configured billing code",- (message) => {- const err = classify(undefined, message, "/v3/backlinks/summary/live");- expect(err?.code).toBe("BACKLINKS_BILLING_ISSUE");- },- );-- it("no longer classifies feature-access signals now that the add-ons are bundled", () => {- expect(- classify(40204, "subscription required", "/v3/backlinks/summary/live"),- ).toBe(null);- expect(classify(403, "access denied", "/v3/backlinks/summary/live")).toBe(- null,- );- });-- it("returns null when neither status nor text matches", () => {- expect(classify(500, "boom", "/v3/backlinks/summary/live")).toBe(null);- });-- it("matches billing signals case-insensitively", () => {+ it("translates billing signals in the message case-insensitively", () => {const err = classify(undefined,"INSUFFICIENT funds",diff --git a/src/server/lib/dataforseoLighthousePayload.test.ts b/src/server/lib/dataforseoLighthousePayload.test.tsindex ba66f8bd..b249d5a2 100644--- a/src/server/lib/dataforseoLighthousePayload.test.ts+++ b/src/server/lib/dataforseoLighthousePayload.test.ts@@ -24,10 +24,7 @@ describe("parseDataforseoLighthousePayload", () => {score: 0.54,auditRefs: [{ id: "unused-javascript" }],},- accessibility: {- score: 0.93,- auditRefs: [{ id: "accesskeys" }],- },+ accessibility: { score: 0.93, auditRefs: [] },"best-practices": { score: 0.79, auditRefs: [] },seo: { score: 0.92, auditRefs: [] },},@@ -50,12 +47,6 @@ describe("parseDataforseoLighthousePayload", () => {],},},- accesskeys: {- title: "`[accesskey]` values are unique",- description: "Access keys should not conflict.",- score: null,- scoreDisplayMode: "error",- },interactive: {title: "Time to Interactive",description: "Time until the page becomes interactive.",@@ -164,38 +155,6 @@ describe("parseDataforseoLighthousePayload", () => {).toThrow("DataForSEO Lighthouse returned no category scores");});- it("throws when DataForSEO returns a non-success task status", () => {- expect(() =>- parseDataforseoLighthousePayload(- {- status_code: 20000,- status_message: "Ok.",- tasks: [- {- id: "task-1",- status_code: 40501,- status_message: "Insufficient credits",- result: [],- },- ],- },- {- url: "https://everyapp.dev/",- strategy: "mobile",- },- ),- ).toThrow("Insufficient credits");- });-- it("includes schema details when the payload shape is invalid", () => {- expect(() =>- parseDataforseoLighthousePayload(null, {- url: "https://everyapp.dev/",- strategy: "mobile",- }),- ).toThrow("<root>");- });-it("rejects a report whose audit fields are off-spec", () => {expect(() =>parseDataforseoLighthousePayload(diff --git a/src/server/lib/domainUtils.test.ts b/src/server/lib/domainUtils.test.tsindex a6009eea..9cb41c56 100644--- a/src/server/lib/domainUtils.test.ts+++ b/src/server/lib/domainUtils.test.ts@@ -3,16 +3,8 @@ import { normalizeDomainInput } from "@/server/lib/domainUtils";import { isValidDomainHost } from "@/shared/researchScope";describe("isValidDomainHost", () => {- it("accepts real registrable domains", () => {- expect(isValidDomainHost("example.com")).toBe(true);- expect(isValidDomainHost("sub.example.co.uk")).toBe(true);- expect(isValidDomainHost("openseo.so")).toBe(true);- });-- it("rejects fake TLDs, IPs, and bare hosts", () => {+ it("rejects fake TLDs", () => {expect(isValidDomainHost("example.por")).toBe(false);- expect(isValidDomainHost("localhost")).toBe(false);- expect(isValidDomainHost("127.0.0.1")).toBe(false);});});@@ -35,8 +27,4 @@ describe("normalizeDomainInput", () => {/valid domain/i,);});-- it("rejects empty input", () => {- expect(() => normalizeDomainInput(" ", false)).toThrowError(/required/i);- });});diff --git a/src/server/lib/errors.test.ts b/src/server/lib/errors.test.tsindex 22a374cd..d009d5cc 100644--- a/src/server/lib/errors.test.ts+++ b/src/server/lib/errors.test.ts@@ -2,39 +2,35 @@ import { describe, expect, it } from "vitest";import { AppError, toClientError } from "@/server/lib/errors";describe("toClientError", () => {- it("sanitizes detailed internal error messages", () => {- const error = toClientError(- new AppError(+ it.each([+ {+ label: "sanitizes internal detail down to the bare code",+ error: new AppError("INTERNAL_ERROR","DataForSEO task missing billing metadata (path: Invalid input). Response: {...}",),- );-- expect(error.message).toBe("INTERNAL_ERROR");- });-- it("keeps public error codes unchanged", () => {- const error = toClientError(new AppError("PAYMENT_REQUIRED"));-- expect(error.message).toBe("PAYMENT_REQUIRED");- });-- it("passes setup-error detail through as CODE: detail", () => {- const error = toClientError(- new AppError(+ message: "INTERNAL_ERROR",+ },+ {+ label: "keeps public error codes unchanged",+ error: new AppError("PAYMENT_REQUIRED"),+ message: "PAYMENT_REQUIRED",+ },+ {+ label: "passes setup-error detail through as CODE: detail",+ error: new AppError("AUTH_CONFIG_MISSING","TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",),- );-- expect(error.message).toBe(- "AUTH_CONFIG_MISSING: TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",- );- });-- it("keeps a detail-less setup error as its bare code", () => {- const error = toClientError(new AppError("AUTH_CONFIG_MISSING"));-- expect(error.message).toBe("AUTH_CONFIG_MISSING");+ message:+ "AUTH_CONFIG_MISSING: TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",+ },+ {+ label: "keeps a detail-less setup error as its bare code",+ error: new AppError("AUTH_CONFIG_MISSING"),+ message: "AUTH_CONFIG_MISSING",+ },+ ])("$label", ({ error, message }) => {+ expect(toClientError(error).message).toBe(message);});});diff --git a/src/server/lib/ga4Client.test.ts b/src/server/lib/ga4Client.test.tsindex ee1f4e2c..a864aa6e 100644--- a/src/server/lib/ga4Client.test.ts+++ b/src/server/lib/ga4Client.test.ts@@ -85,52 +85,39 @@ describe("ga4Client admin API", () => {userId: "u1",accountId: "google-sub-a",});- const secondUrl = mocks.fetch.mock.calls[1]?.[0];- const secondUrlText =- typeof secondUrl === "string"- ? secondUrl- : secondUrl instanceof URL- ? secondUrl.toString()- : secondUrl?.url;- expect(secondUrlText).toContain("pageToken=page-2");- expect(mocks.getAccessToken).toHaveBeenCalledTimes(1);- });-- it("loads and validates the selected property's reporting metadata", async () => {- mocks.fetch.mockResolvedValue(- jsonResponse({- name: "properties/11",- displayName: "Site A",- timeZone: "America/New_York",- currencyCode: "USD",- }),- );- const property = await createGa4AdminClient({- userId: "u1",- ga4AccountId: "google-sub-a",- }).getProperty("properties/11");-- expect(property.timeZone).toBe("America/New_York");- expect(mocks.fetch.mock.calls[0]?.[0]).toBe(- "https://analyticsadmin.googleapis.com/v1beta/properties/11",+ expect(requestUrl(mocks.fetch.mock.calls[1][0])).toContain(+ "pageToken=page-2",);+ expect(mocks.getAccessToken).toHaveBeenCalledTimes(1);});- it("classifies a rejected grant as a typed 401", async () => {- mocks.fetch.mockResolvedValue(jsonResponse({ error: "expired" }, 401));- await expect(- createGa4AdminClient({+ it.each([+ {+ label: "a rejected grant",+ respond: () =>+ mocks.fetch.mockResolvedValue(jsonResponse({ error: "expired" }, 401)),+ status: 401,+ },+ {+ label: "a transport failure",+ respond: () =>+ mocks.fetch.mockRejectedValue(new TypeError("connection reset")),+ status: 0,+ },+ ])(+ "classifies $label as a typed admin error with status $status",+ async ({ respond, status }) => {+ respond();+ const client = createGa4AdminClient({userId: "u1",ga4AccountId: "google-sub-a",- }).listProperties(),- ).rejects.toBeInstanceOf(Ga4AdminApiError);- await expect(- createGa4AdminClient({- userId: "u1",- ga4AccountId: "google-sub-a",- }).listProperties(),- ).rejects.toMatchObject({ status: 401 });- });+ });+ await expect(client.listProperties()).rejects.toBeInstanceOf(+ Ga4AdminApiError,+ );+ await expect(client.listProperties()).rejects.toMatchObject({ status });+ },+ );it("throws a token error when no access token can be minted", async () => {mocks.getAccessToken.mockRejectedValue(new Error("revoked"));@@ -141,105 +128,6 @@ describe("ga4Client admin API", () => {}).listProperties(),).rejects.toBeInstanceOf(Ga4TokenError);});-- it("reads streams, enhanced measurement, key events, and custom definitions", async () => {- mocks.fetch- .mockResolvedValueOnce(- jsonResponse({- dataStreams: [- {- name: "properties/11/dataStreams/22",- type: "WEB_DATA_STREAM",- displayName: "Website",- webStreamData: {- measurementId: "G-ABC123",- defaultUri: "https://example.com",- },- },- ],- }),- )- .mockResolvedValueOnce(- jsonResponse({- streamEnabled: true,- }),- )- .mockResolvedValueOnce(- jsonResponse({- keyEvents: [- {- eventName: "purchase",- countingMethod: "ONCE_PER_EVENT",- custom: false,- },- ],- }),- )- .mockResolvedValueOnce(- jsonResponse({- customDimensions: [- {- parameterName: "content_type",- displayName: "Content type",- scope: "EVENT",- },- ],- }),- )- .mockResolvedValueOnce(- jsonResponse({- customMetrics: [- {- parameterName: "quality_score",- displayName: "Quality score",- measurementUnit: "STANDARD",- scope: "EVENT",- },- ],- }),- );- const client = createGa4AdminClient({- userId: "u1",- ga4AccountId: "google-sub-a",- });-- const streams = await client.listDataStreams("properties/11");- const enhanced = await client.getEnhancedMeasurementSettings(- "properties/11/dataStreams/22",- );- const keyEvents = await client.listKeyEvents("properties/11");- const dimensions = await client.listCustomDimensions("properties/11");- const metrics = await client.listCustomMetrics("properties/11");-- expect(streams[0]?.webStreamData?.measurementId).toBe("G-ABC123");- expect(enhanced).toMatchObject({- streamEnabled: true,- siteSearchEnabled: false,- searchQueryParameter: "",- });- expect(keyEvents[0]?.eventName).toBe("purchase");- expect(dimensions[0]?.parameterName).toBe("content_type");- expect(metrics[0]?.parameterName).toBe("quality_score");- expect(mocks.fetch.mock.calls.map((call) => requestUrl(call[0]))).toEqual([- "https://analyticsadmin.googleapis.com/v1alpha/properties/11/dataStreams?pageSize=200",- "https://analyticsadmin.googleapis.com/v1alpha/properties/11/dataStreams/22/enhancedMeasurementSettings",- "https://analyticsadmin.googleapis.com/v1beta/properties/11/keyEvents?pageSize=200",- "https://analyticsadmin.googleapis.com/v1beta/properties/11/customDimensions?pageSize=200",- "https://analyticsadmin.googleapis.com/v1beta/properties/11/customMetrics?pageSize=200",- ]);- expect(mocks.getAccessToken).toHaveBeenCalledTimes(1);- });-- it("converts transport failures to a typed upstream error", async () => {- mocks.fetch.mockRejectedValue(new TypeError("connection reset"));-- await expect(- createGa4AdminClient({- userId: "u1",- ga4AccountId: "google-sub-a",- }).listProperties(),- ).rejects.toMatchObject({ status: 0 });- });});const reportRequest = {diff --git a/src/server/lib/gscClient.test.ts b/src/server/lib/gscClient.test.tsindex 20cefca0..19eb3c00 100644--- a/src/server/lib/gscClient.test.ts+++ b/src/server/lib/gscClient.test.ts@@ -1,4 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createGscClient, GscApiError, GscTokenError } from "./gscClient";const mocks = vi.hoisted(() => ({getAccessToken: vi.fn(),@@ -15,9 +16,7 @@ function jsonResponse(body: unknown, status = 200) {describe("gscClient", () => {beforeEach(() => {- mocks.getAccessToken.mockReset();mocks.getAccessToken.mockResolvedValue("tok_123");- mocks.fetch.mockReset();vi.stubGlobal("fetch", mocks.fetch);});afterEach(() => {@@ -30,7 +29,6 @@ describe("gscClient", () => {siteEntry: [{ siteUrl: "https://x/", permissionLevel: "siteOwner" }],}),);- const { createGscClient } = await import("./gscClient");const sites = await createGscClient({ userId: "u1" }).listSites();expect(sites).toHaveLength(1);@@ -41,7 +39,6 @@ describe("gscClient", () => {it("targets the selected Better Auth grant by Google sub", async () => {mocks.fetch.mockResolvedValue(jsonResponse({ siteEntry: [] }));- const { createGscClient } = await import("./gscClient");await createGscClient({userId: "u1",@@ -57,7 +54,6 @@ describe("gscClient", () => {it("omits accountId for the legacy null-account fallback", async () => {mocks.fetch.mockResolvedValue(jsonResponse({ siteEntry: [] }));- const { createGscClient } = await import("./gscClient");await createGscClient({ userId: "u1" }).listSites();@@ -72,7 +68,6 @@ describe("gscClient", () => {mocks.fetch.mockResolvedValue(jsonResponse({ email: "[email protected]" }),);- const { createGscClient } = await import("./gscClient");const email = await createGscClient({userId: "u1",@@ -87,7 +82,6 @@ describe("gscClient", () => {it("encodes the siteUrl in the searchAnalytics path (both property forms)", async () => {mocks.fetch.mockImplementation(async () => jsonResponse({ rows: [] }));- const { createGscClient } = await import("./gscClient");const client = createGscClient({ userId: "u1" });await client.querySearchAnalytics("sc-domain:example.com", {@@ -115,7 +109,6 @@ describe("gscClient", () => {},}),);- const { createGscClient } = await import("./gscClient");const result = await createGscClient({ userId: "u1" }).inspectUrl("sc-domain:example.com","https://example.com/post",@@ -143,7 +136,6 @@ describe("gscClient", () => {mocks.fetch.mockImplementation(async () =>jsonResponse({ error: "forbidden" }, 403),);- const { createGscClient, GscApiError } = await import("./gscClient");await expect(createGscClient({ userId: "u1" }).listSites(),).rejects.toMatchObject({ status: 403 });@@ -154,7 +146,6 @@ describe("gscClient", () => {it("maps 429 to a rate-limit GscApiError", async () => {mocks.fetch.mockResolvedValue(jsonResponse({ error: "slow down" }, 429));- const { createGscClient } = await import("./gscClient");await expect(createGscClient({ userId: "u1" }).listSites(),).rejects.toMatchObject({ status: 429 });@@ -162,7 +153,6 @@ describe("gscClient", () => {it("throws GscTokenError when no access token can be minted", async () => {mocks.getAccessToken.mockRejectedValue(new Error("revoked"));- const { createGscClient, GscTokenError } = await import("./gscClient");await expect(createGscClient({ userId: "u1" }).listSites(),).rejects.toBeInstanceOf(GscTokenError);diff --git a/src/server/lib/lighthousePayload.test.ts b/src/server/lib/lighthousePayload.test.tsnew file mode 100644index 00000000..82634e53--- /dev/null+++ b/src/server/lib/lighthousePayload.test.ts@@ -0,0 +1,95 @@+import { z } from "zod";+import { describe, expect, it } from "vitest";+import { buildLighthouseExportFile } from "@/server/lib/lighthousePayload";++const issue = (category: string, auditKey: string) => ({+ category,+ auditKey,+ title: auditKey,+ description: "",+ score: 0,+ scoreDisplayMode: "binary",+ displayValue: null,+ impactMs: null,+ impactBytes: null,+ severity: "critical",+ items: [],+});++const metric = { score: null, displayValue: null, numericValue: null };++const storedPayloadJson = JSON.stringify({+ version: 2,+ source: "dataforseo-lighthouse",+ hasIssueDetails: true,+ metadata: {+ requestedUrl: "https://example.com/",+ finalUrl: "https://example.com/",+ strategy: "mobile",+ fetchedAt: "2026-03-23T19:27:33.000Z",+ lighthouseVersion: null,+ taskId: null,+ cost: null,+ },+ scores: { performance: 89, accessibility: 93, "best-practices": 92, seo: 91 },+ metrics: {+ firstContentfulPaint: metric,+ largestContentfulPaint: metric,+ totalBlockingTime: metric,+ cumulativeLayoutShift: metric,+ speedIndex: metric,+ timeToInteractive: metric,+ interactionToNextPaint: metric,+ serverResponseTime: metric,+ },+ issues: [+ issue("performance", "unused-javascript"),+ issue("accessibility", "color-contrast"),+ ],+});++const issuesExportSchema = z.object({+ resultId: z.string(),+ category: z.string(),+ issues: z.array(z.object({ auditKey: z.string() })),+});++describe("buildLighthouseExportFile", () => {+ it.each([+ {+ mode: "issues" as const,+ category: undefined,+ filename: "-issues.json",+ exportedCategory: "all",+ auditKeys: ["unused-javascript", "color-contrast"],+ },+ {+ mode: "category" as const,+ category: "accessibility" as const,+ filename: "-accessibility-issues.json",+ exportedCategory: "accessibility",+ auditKeys: ["color-contrast"],+ },+ ])(+ "exports only the issues for $mode mode",+ ({ mode, category, filename, exportedCategory, auditKeys }) => {+ const exported = buildLighthouseExportFile({+ idField: "resultId",+ idValue: "result-1",+ finalUrl: "https://example.com/",+ strategy: "mobile",+ createdAt: "2026-03-23T19:27:33.000Z",+ payloadJson: storedPayloadJson,+ mode,+ category,+ });++ const content = issuesExportSchema.parse(JSON.parse(exported.content));+ expect(exported.filename).toContain(filename);+ expect(content.resultId).toBe("result-1");+ expect(content.category).toBe(exportedCategory);+ expect(content.issues.map((entry) => entry.auditKey)).toEqual(auditKeys);+ expect(exported.content).not.toContain("timeToInteractive");+ },+ );+});diff --git a/src/server/lib/scrape.test.ts b/src/server/lib/scrape.test.tsindex 6ab7291e..c5c38678 100644--- a/src/server/lib/scrape.test.ts+++ b/src/server/lib/scrape.test.ts@@ -10,21 +10,17 @@ describe("readSite SSRF guard", () => {vi.unstubAllGlobals();});- it("blocks a metadata/private host without fetching it", async () => {- const result = await readSite("169.254.169.254");-- expect(result.blocked).toBe(true);- expect(result.pages).toEqual([]);- // The blocked host must be rejected before any outbound page fetch.- expect(fetch).not.toHaveBeenCalled();- });-- it("blocks localhost-style targets", async () => {- const result = await readSite("localhost:3000");-- expect(result.blocked).toBe(true);- expect(fetch).not.toHaveBeenCalled();- });+ it.each(["169.254.169.254", "localhost:3000"])(+ "blocks %s without fetching it",+ async (host) => {+ const result = await readSite(host);++ expect(result.blocked).toBe(true);+ expect(result.pages).toEqual([]);+ // The blocked host must be rejected before any outbound page fetch.+ expect(fetch).not.toHaveBeenCalled();+ },+ );});describe("readPages SSRF guard", () => {@@ -47,12 +43,4 @@ describe("readPages SSRF guard", () => {// Every URL is validated before any outbound fetch.expect(fetch).not.toHaveBeenCalled();});-- it("returns blocked for an empty URL list without fetching", async () => {- const result = await readPages([]);-- expect(result.blocked).toBe(true);- expect(result.pages).toEqual([]);- expect(fetch).not.toHaveBeenCalled();- });});diff --git a/src/server/lib/self-host-telemetry.test.ts b/src/server/lib/self-host-telemetry.test.tsindex 54e27f2f..dfe9ca33 100644--- a/src/server/lib/self-host-telemetry.test.ts+++ b/src/server/lib/self-host-telemetry.test.ts@@ -1,9 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { SelfHostTelemetryDependencies } from "./self-host-telemetry";import {- getCheckIntervalMs,- getHeartbeatIntervalMs,incrementSelfHostMcpToolCallCount,+ maybeSendSelfHostHeartbeat,} from "./self-host-telemetry";const dbMocks = vi.hoisted(() => {@@ -26,7 +25,6 @@ type StoredState = {};const NOW = new Date("2026-07-18T12:00:00.000Z");-const DAY_MS = 24 * 60 * 60 * 1000;const emptyCounts = {userCount: 0,projectCount: 0,@@ -50,22 +48,11 @@ function createHarness(...initialState,};const sendHeartbeat = vi.fn<SelfHostTelemetryDependencies["sendHeartbeat"]>();- const claimHeartbeat = vi.fn(async (now: Date) => {- if (- state.lastHeartbeatAt &&- now.getTime() - state.lastHeartbeatAt.getTime() <= DAY_MS- ) {- return null;- }-- const previous = { ...state };- state.lastHeartbeatAt = now;- return previous;- });- const markHeartbeatSent = vi.fn(async (currentVersion: string) => {- state.lastVersion = currentVersion;- state.mcpToolCallCount = 0;- });+ // The real claim is a compare-and-set SQL update; the harness only hands+ // back the stored row so the payload-building path can be exercised.+ const claimHeartbeat = vi.fn(async () => ({ ...state }));+ const markHeartbeatSent =+ vi.fn<SelfHostTelemetryDependencies["markHeartbeatSent"]>();const dependencies: Partial<SelfHostTelemetryDependencies> = {now: () => NOW,isNonProductionBuild: () => false,@@ -91,46 +78,12 @@ async function runHeartbeat(harness: ReturnType<typeof createHarness>,pathname = "/",) {- const { maybeSendSelfHostHeartbeat } = await import("./self-host-telemetry");await maybeSendSelfHostHeartbeat(pathname, {dependencies: harness.dependencies,skipMemoryThrottle: true,});}-describe("getHeartbeatIntervalMs", () => {- const MINUTE = 60 * 1000;- const HOUR = 60 * MINUTE;-- it("uses the 5-minute onboarding cadence during the first two hours", () => {- expect(getHeartbeatIntervalMs(0)).toBe(5 * MINUTE);- expect(getHeartbeatIntervalMs(2 * HOUR - 1)).toBe(5 * MINUTE);- });-- it("uses the daily cadence from two hours onward", () => {- expect(getHeartbeatIntervalMs(2 * HOUR)).toBe(24 * HOUR);- expect(getHeartbeatIntervalMs(Number.POSITIVE_INFINITY)).toBe(24 * HOUR);- });-});--describe("getCheckIntervalMs", () => {- const MINUTE = 60 * 1000;- const HOUR = 60 * MINUTE;-- it("checks immediately when the install age is unknown", () => {- expect(getCheckIntervalMs(null)).toBe(0);- });-- it("polls every minute during onboarding so 5-minute beats don't alias", () => {- expect(getCheckIntervalMs(0)).toBe(MINUTE);- expect(getCheckIntervalMs(2 * HOUR - 1)).toBe(MINUTE);- });-- it("polls every 15 minutes once onboarding is over", () => {- expect(getCheckIntervalMs(2 * HOUR)).toBe(15 * MINUTE);- });-});-describe("maybeSendSelfHostHeartbeat", () => {beforeEach(() => {vi.unstubAllEnvs();@@ -168,9 +121,6 @@ describe("maybeSendSelfHostHeartbeat", () => {{ mode: "production", prod: true, sends: true },{ mode: "selfhost", prod: true, sends: true },{ mode: "preview", prod: true, sends: false },- { mode: "development", prod: false, sends: false },- { mode: "test", prod: false, sends: false },- { mode: "selfhost", prod: false, sends: false },{ mode: "production", prod: false, sends: false },])("gates heartbeats and MCP counters for mode=$mode, PROD=$prod",@@ -189,28 +139,12 @@ describe("maybeSendSelfHostHeartbeat", () => {},);- it("does not send in hosted mode", async () => {- vi.stubEnv("AUTH_MODE", "hosted");- const harness = createHarness();-- await runHeartbeat(harness);-- expect(harness.claimHeartbeat).not.toHaveBeenCalled();- expect(harness.sendHeartbeat).not.toHaveBeenCalled();- });-- it("does not send when OPENSEO_TELEMETRY_DISABLED is set", async () => {- vi.stubEnv("OPENSEO_TELEMETRY_DISABLED", "1");- const harness = createHarness();-- await runHeartbeat(harness);-- expect(harness.claimHeartbeat).not.toHaveBeenCalled();- expect(harness.sendHeartbeat).not.toHaveBeenCalled();- });-- it("does not send when DO_NOT_TRACK is set", async () => {- vi.stubEnv("DO_NOT_TRACK", "1");+ it.each([+ ["AUTH_MODE", "hosted"],+ ["OPENSEO_TELEMETRY_DISABLED", "1"],+ ["DO_NOT_TRACK", "1"],+ ])("does not send when %s=%s", async (name, value) => {+ vi.stubEnv(name, value);const harness = createHarness();await runHeartbeat(harness);@@ -219,16 +153,6 @@ describe("maybeSendSelfHostHeartbeat", () => {expect(harness.sendHeartbeat).not.toHaveBeenCalled();});- it('still sends when the disable flags are explicitly "0"/"false"', async () => {- vi.stubEnv("OPENSEO_TELEMETRY_DISABLED", "0");- vi.stubEnv("DO_NOT_TRACK", "false");- const harness = createHarness();-- await runHeartbeat(harness);-- expect(harness.sendHeartbeat).toHaveBeenCalledTimes(1);- });-it("includes the setup-issue summary in heartbeat properties", async () => {const harness = createHarness();harness.dependencies.collectSetupIssues = async () => ["dataforseo:error"];@@ -240,47 +164,6 @@ describe("maybeSendSelfHostHeartbeat", () => {});});- it("does not send from non-production builds (dev, test, preview)", async () => {- const harness = createHarness();- // Omit the isNonProductionBuild override: the production gate reads- // import.meta.env.MODE, which is "test" under vitest and must block.- delete harness.dependencies.isNonProductionBuild;-- await runHeartbeat(harness);-- expect(harness.claimHeartbeat).not.toHaveBeenCalled();- expect(harness.sendHeartbeat).not.toHaveBeenCalled();- });-- it("allows only one concurrent caller to claim a heartbeat", async () => {- const harness = createHarness();-- await Promise.all([runHeartbeat(harness), runHeartbeat(harness)]);-- expect(harness.claimHeartbeat).toHaveBeenCalledTimes(2);- expect(harness.sendHeartbeat).toHaveBeenCalledTimes(1);- });-- it("does not send within 24 hours", async () => {- const harness = createHarness({- lastHeartbeatAt: new Date(NOW.getTime() - DAY_MS + 1),- });-- await runHeartbeat(harness);-- expect(harness.sendHeartbeat).not.toHaveBeenCalled();- });-- it("sends after 24 hours", async () => {- const harness = createHarness({- lastHeartbeatAt: new Date(NOW.getTime() - DAY_MS - 1),- });-- await runHeartbeat(harness);-- expect(harness.sendHeartbeat).toHaveBeenCalledTimes(1);- });-it("marks the first heartbeat and resets the reported MCP counter", async () => {const harness = createHarness({ mcpToolCallCount: 7 });@@ -290,8 +173,7 @@ describe("maybeSendSelfHostHeartbeat", () => {firstRun: true,mcpToolCalls: 7,});- expect(harness.state.mcpToolCallCount).toBe(0);- expect(harness.markHeartbeatSent).toHaveBeenCalledTimes(1);+ expect(harness.markHeartbeatSent).toHaveBeenCalledWith("1.0.0", 7);});it("reports minutesSinceInstall from the stored install time", async () => {@@ -319,7 +201,7 @@ describe("maybeSendSelfHostHeartbeat", () => {it("includes prevVersion only when the version changes", async () => {const changed = createHarness({- lastHeartbeatAt: new Date(NOW.getTime() - DAY_MS - 1),+ lastHeartbeatAt: new Date("2026-07-17T12:00:00.000Z"),lastVersion: "0.9.0",},"1.0.0",@@ -333,7 +215,7 @@ describe("maybeSendSelfHostHeartbeat", () => {const unchanged = createHarness({- lastHeartbeatAt: new Date(NOW.getTime() - DAY_MS - 1),+ lastHeartbeatAt: new Date("2026-07-17T12:00:00.000Z"),lastVersion: "1.0.0",},"1.0.0",diff --git a/src/server/lib/self-host-telemetry.ts b/src/server/lib/self-host-telemetry.tsindex e01a4b2e..9c69f919 100644--- a/src/server/lib/self-host-telemetry.ts+++ b/src/server/lib/self-host-telemetry.ts@@ -38,13 +38,13 @@ const ONBOARDING_CHECK_INTERVAL_MS = 60 * 1000;const STEADY_CHECK_INTERVAL_MS = 15 * 60 * 1000;const TELEMETRY_STATE_ID = 1;-export function getHeartbeatIntervalMs(installAgeMs: number) {+function getHeartbeatIntervalMs(installAgeMs: number) {return installAgeMs < ONBOARDING_WINDOW_MS? ONBOARDING_HEARTBEAT_INTERVAL_MS: DAILY_HEARTBEAT_INTERVAL_MS;}-export function getCheckIntervalMs(installAgeMs: number | null) {+function getCheckIntervalMs(installAgeMs: number | null) {if (installAgeMs === null) return 0;return installAgeMs < ONBOARDING_WINDOW_MS? ONBOARDING_CHECK_INTERVAL_MSdiff --git a/src/server/lib/string-retention.test.ts b/src/server/lib/string-retention.test.tsindex 9abc6ac2..3ec2fe4c 100644--- a/src/server/lib/string-retention.test.ts+++ b/src/server/lib/string-retention.test.ts@@ -2,12 +2,7 @@ import { spawnSync } from "node:child_process";import { describe, expect, it } from "vitest";describe("retained string memory", () => {- it.each([- "scraped title",- "scraped text",- "tool output",- "tool output with smaller budget",- ])(+ it.each(["scraped text", "tool output"])("releases the large source behind %s",(scenario) => {// Isolate GC from Vitest's heap. Each result must outlive its independently@@ -27,11 +22,9 @@ describe("retained string memory", () => {const scenario = ${JSON.stringify(scenario)};const title = "Example memory regression 🌱";globalThis.fetch = async () => {- const content = scenario === "scraped text"- ? "sample words ".repeat(100_000)- : "<script>" + "x".repeat(1_500_000) + "</script>Visible text";const bytes = new TextEncoder().encode(- "<title>" + title + "</title><body>" + content + "</body>");+ "<title>" + title + "</title><body>" ++ "sample words ".repeat(100_000) + "</body>");let offset = 0;return new Response(new ReadableStream({pull(controller) {@@ -42,7 +35,7 @@ describe("retained string memory", () => {}), { headers: { "content-type": "text/html" } });};const makeResult = async () => {- if (scenario.startsWith("scraped")) {+ if (scenario === "scraped text") {// Documentation-only IP avoids DNS; fetch is fully stubbed.const result = await readPages(["https://192.0.2.1/example"]);assert.equal(result.blocked, false);@@ -52,7 +45,7 @@ describe("retained string memory", () => {}const input = { pages: [{ text: new TextDecoder().decode(new TextEncoder().encode("x".repeat(1_500_000))) }] };- const budget = scenario.endsWith("smaller budget") ? 2000 : 32000;+ const budget = 2000;const result = capToolOutput(input, budget);assert.ok(JSON.stringify(result).length <= budget);assert.equal(input.pages[0].text.length, 1_500_000);diff --git a/src/server/mcp/api-key-auth.test.ts b/src/server/mcp/api-key-auth.test.tsindex 15e9fb75..beb8ba7f 100644--- a/src/server/mcp/api-key-auth.test.ts+++ b/src/server/mcp/api-key-auth.test.ts@@ -57,11 +57,9 @@ function request(headers?: HeadersInit, method = "POST") {describe("handleMcpApiKeyRequest", () => {beforeEach(() => {- vi.clearAllMocks();mocks.getHostedUser.mockResolvedValue({id: "user-1",email: "[email protected]",- name: "Person",});mocks.resolveExistingActiveHostedOrganization.mockResolvedValue({organizationId: "org-1",@@ -73,60 +71,51 @@ describe("handleMcpApiKeyRequest", () => {);});- it("handles a valid key with the hosted user, organization, and MCP scopes", async () => {- mocks.verifyApiKey.mockResolvedValue({- valid: true,- error: null,- key: { referenceId: "user-1" },- });- const mcpRequest = request({ Authorization: "Bearer oseo_secret" });-- const response = await handleMcpApiKeyRequest(mcpRequest, env, ctx);-- expect(await response?.text()).toBe("mcp response");- expect(mocks.verifyApiKey).toHaveBeenCalledWith({- body: { key: "oseo_secret" },- });- expect(mocks.resolveExistingActiveHostedOrganization).toHaveBeenCalledWith(- "user-1",- );- expect(mocks.recordMcpAuthorized).toHaveBeenCalledWith("org-1");- expect(mocks.handleAuthenticatedOpenSeoMcpRequest).toHaveBeenCalledTimes(1);- const [passedRequest, props, passedEnv, passedCtx] =- mocks.handleAuthenticatedOpenSeoMcpRequest.mock.calls[0];- expect(passedRequest).toBe(mcpRequest);- expect(passedEnv).toBe(env);- expect(passedCtx).toBe(ctx);- expect(props).toMatchObject({- [MCP_AUTH_CONTEXT_PROP]: {- userId: "user-1",- userEmail: "[email protected]",- organizationId: "org-1",- role: "owner",- scopes: [...MCP_OAUTH_SCOPES],- clientId: "api_key",- baseUrl: "https://app.openseo.so",- },- });- });-- it("accepts the key via a case-insensitive bearer scheme", async () => {- mocks.verifyApiKey.mockResolvedValue({- valid: true,- error: null,- key: { referenceId: "user-1" },- });-- await handleMcpApiKeyRequest(- request({ Authorization: "bearer oseo_secret" }),- env,- ctx,- );-- expect(mocks.verifyApiKey).toHaveBeenCalledWith({- body: { key: "oseo_secret" },- });- });+ it.each([+ ["Bearer", { Authorization: "Bearer oseo_secret" }],+ ["case-insensitive bearer", { Authorization: "bearer oseo_secret" }],+ ["x-api-key", { "x-api-key": "oseo_secret" }],+ ])(+ "handles a valid key sent as %s with the hosted user, organization, and MCP scopes",+ async (_label, headers) => {+ mocks.verifyApiKey.mockResolvedValue({+ valid: true,+ error: null,+ key: { referenceId: "user-1" },+ });+ const mcpRequest = request(headers);++ const response = await handleMcpApiKeyRequest(mcpRequest, env, ctx);++ expect(await response?.text()).toBe("mcp response");+ expect(mocks.verifyApiKey).toHaveBeenCalledWith({+ body: { key: "oseo_secret" },+ });+ expect(+ mocks.resolveExistingActiveHostedOrganization,+ ).toHaveBeenCalledWith("user-1");+ expect(mocks.recordMcpAuthorized).toHaveBeenCalledWith("org-1");+ expect(mocks.handleAuthenticatedOpenSeoMcpRequest).toHaveBeenCalledTimes(+ 1,+ );+ const [passedRequest, props, passedEnv, passedCtx] =+ mocks.handleAuthenticatedOpenSeoMcpRequest.mock.calls[0];+ expect(passedRequest).toBe(mcpRequest);+ expect(passedEnv).toBe(env);+ expect(passedCtx).toBe(ctx);+ expect(props).toMatchObject({+ [MCP_AUTH_CONTEXT_PROP]: {+ userId: "user-1",+ userEmail: "[email protected]",+ organizationId: "org-1",+ role: "owner",+ scopes: [...MCP_OAUTH_SCOPES],+ clientId: "api_key",+ baseUrl: "https://app.openseo.so",+ },+ });+ },+ );it("returns 403 when the user has no organization membership", async () => {mocks.verifyApiKey.mockResolvedValue({@@ -193,62 +182,29 @@ describe("handleMcpApiKeyRequest", () => {expect(mocks.handleAuthenticatedOpenSeoMcpRequest).not.toHaveBeenCalled();});- it("returns a JSON 500 when auth resolution throws", async () => {- mocks.verifyApiKey.mockRejectedValue(new Error("db down"));-- const response = await handleMcpApiKeyRequest(- request({ Authorization: "Bearer oseo_secret" }),- env,- ctx,- );-- expect(response?.status).toBe(500);- await expect(response?.json()).resolves.toMatchObject({- error: "internal_error",- });- expect(mocks.handleAuthenticatedOpenSeoMcpRequest).not.toHaveBeenCalled();- });-- it("leaves non-OpenSEO bearer tokens for OAuth", async () => {- await expect(- handleMcpApiKeyRequest(- request({ Authorization: "Bearer oauth-access-token" }),- env,- ctx,- ),- ).resolves.toBeNull();- expect(mocks.verifyApiKey).not.toHaveBeenCalled();- });-- it("leaves non-OpenSEO x-api-key values for OAuth", async () => {- await expect(- handleMcpApiKeyRequest(- request({- "x-api-key": "some-foreign-key",- Authorization: "Bearer oauth-access-token",- }),- env,- ctx,- ),- ).resolves.toBeNull();- expect(mocks.verifyApiKey).not.toHaveBeenCalled();- });-- it("leaves requests without credentials for OAuth", async () => {- await expect(- handleMcpApiKeyRequest(request(), env, ctx),- ).resolves.toBeNull();- expect(mocks.verifyApiKey).not.toHaveBeenCalled();- });-- it("leaves OPTIONS requests with API keys for the CORS handler", async () => {- await expect(- handleMcpApiKeyRequest(- request({ "x-api-key": "oseo_secret" }, "OPTIONS"),- env,- ctx,- ),- ).resolves.toBeNull();- expect(mocks.verifyApiKey).not.toHaveBeenCalled();- });+ it.each([+ [+ "non-OpenSEO bearer tokens",+ request({ Authorization: "Bearer oauth-access-token" }),+ ],+ [+ "non-OpenSEO x-api-key values",+ request({+ "x-api-key": "some-foreign-key",+ Authorization: "Bearer oauth-access-token",+ }),+ ],+ [+ "OPTIONS requests with API keys",+ request({ "x-api-key": "oseo_secret" }, "OPTIONS"),+ ],+ ])(+ "leaves %s for the OAuth and CORS handlers",+ async (_label, mcpRequest) => {+ await expect(+ handleMcpApiKeyRequest(mcpRequest, env, ctx),+ ).resolves.toBeNull();+ expect(mocks.verifyApiKey).not.toHaveBeenCalled();+ },+ );});diff --git a/src/server/mcp/context.test.ts b/src/server/mcp/context.test.tsindex 2ee2d23a..75986f7e 100644--- a/src/server/mcp/context.test.ts+++ b/src/server/mcp/context.test.ts@@ -3,8 +3,6 @@ import { describe, expect, it } from "vitest";import {createMcpToolContext,createWorkersOAuthMcpProps,- MCP_AUTH_CONTEXT_PROP,- workersOAuthMcpPropsSchema,} from "@/server/mcp/context";const applicationContext = {@@ -15,18 +13,6 @@ const applicationContext = {};describe("OpenSEO tool auth context", () => {- it("stores only application-specific identity in Workers OAuth props", () => {- const props = createWorkersOAuthMcpProps(applicationContext);-- expect(workersOAuthMcpPropsSchema.parse(props)).toEqual({- [MCP_AUTH_CONTEXT_PROP]: applicationContext,- });- });-- it("rejects unrecognized provider props", () => {- expect(workersOAuthMcpPropsSchema.safeParse({}).success).toBe(false);- });-it("prefers standard OAuth client metadata over the props fallback", () => {const props = createWorkersOAuthMcpProps({...applicationContext,diff --git a/src/server/mcp/formatters.test.ts b/src/server/mcp/formatters.test.tsindex dc41d706..42bba536 100644--- a/src/server/mcp/formatters.test.ts+++ b/src/server/mcp/formatters.test.ts@@ -2,81 +2,41 @@ import { describe, expect, it } from "vitest";import { mcpResponse } from "./formatters";describe("mcpResponse", () => {- it("returns content as a text block", () => {- const result = mcpResponse({ text: "hi" });- expect(result.content).toEqual([{ type: "text", text: "hi" }]);- });-- it("includes _meta only when meta is provided", () => {- const bare = mcpResponse({ text: "hi" });- expect(bare._meta).toBeUndefined();-- const withMeta = mcpResponse({- text: "hi",- meta: { url: "https://app.openseo.so/p/1", projectId: "1" },- });- expect(withMeta._meta).toEqual({- url: "https://app.openseo.so/p/1",- projectId: "1",- });- });-- it("drops undefined meta keys", () => {+ it("drops undefined meta keys and omits _meta when nothing is left", () => {const result = mcpResponse({text: "hi",meta: {url: "https://app.openseo.so",creditsCharged: 0,+ projectId: undefined,},});expect(result._meta).toEqual({url: "https://app.openseo.so",creditsCharged: 0,});- });- it("attaches structuredContent when provided", () => {- const result = mcpResponse({+ expect(mcpResponse({ text: "hi" })._meta).toBeUndefined();+ const allUndefined = mcpResponse({text: "hi",- structuredContent: { foo: "bar" },+ meta: { projectId: undefined },});- expect(result.structuredContent).toEqual({ foo: "bar" });+ expect(allUndefined._meta).toBeUndefined();+ expect(allUndefined.structuredContent).toBeUndefined();});it("mirrors metadata into structuredContent for clients that hide _meta", () => {- const result = mcpResponse({- text: "hi",- meta: {- url: "https://app.openseo.so/p/1",- projectId: "1",- creditsRemaining: 100,- },- structuredContent: { foo: "bar" },- });+ const meta = { url: "https://app.openseo.so/p/1", creditsRemaining: 100 };- expect(result.structuredContent).toEqual({- foo: "bar",- meta: {- url: "https://app.openseo.so/p/1",- projectId: "1",- creditsRemaining: 100,- },- });- expect(result._meta).toEqual({- url: "https://app.openseo.so/p/1",- projectId: "1",- creditsRemaining: 100,- });- });-- it("uses metadata as structuredContent when no data payload is provided", () => {- const result = mcpResponse({+ const withPayload = mcpResponse({text: "hi",- meta: { url: "https://app.openseo.so" },+ meta,+ structuredContent: { foo: "bar" },});+ expect(withPayload.structuredContent).toEqual({ foo: "bar", meta });+ expect(withPayload._meta).toEqual(meta);- expect(result.structuredContent).toEqual({- meta: { url: "https://app.openseo.so" },- });+ const metaOnly = mcpResponse({ text: "hi", meta });+ expect(metaOnly.structuredContent).toEqual({ meta });});});diff --git a/src/server/mcp/instrumentation.test.ts b/src/server/mcp/instrumentation.test.tsindex 239e9bd2..bb40095d 100644--- a/src/server/mcp/instrumentation.test.ts+++ b/src/server/mcp/instrumentation.test.ts@@ -1,5 +1,5 @@import type { CallToolResult } from "@modelcontextprotocol/server";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi } from "vitest";import { z } from "zod";import { instrumentMcpToolHandler } from "./instrumentation";import { type ToolAuthContext, type ToolContext } from "@/server/mcp/context";@@ -54,27 +54,7 @@ const authContext: ToolAuthContext = {const toolContext: ToolContext = { auth: authContext };describe("instrumentMcpToolHandler", () => {- beforeEach(() => {- mocks.captureServerError.mockReset();- mocks.captureServerEvent.mockReset();- mocks.recordExternalMcpToolCall.mockReset();- mocks.incrementSelfHostMcpToolCallCount.mockReset();- });-- it("passes a valid result through without reporting", async () => {- const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>- okResult({ items: [{ domain: "example.com" }] }),- );-- const result = await wrapped({}, toolContext);-- expect(result.structuredContent).toEqual({- items: [{ domain: "example.com" }],- });- expect(mocks.captureServerError).not.toHaveBeenCalled();- });-- it("reports an output schema mismatch the SDK would silently reject", async () => {+ it("reports an output schema mismatch the SDK would silently reject and marks the usage failed", async () => {const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>okResult({ items: "not-an-array" }),);@@ -86,6 +66,10 @@ describe("instrumentMcpToolHandler", () => {errorCode: "MCP_OUTPUT_VALIDATION",tool: "demo",});+ expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({+ event: "mcp:tool_call",+ properties: { success: false, error_code: "MCP_OUTPUT_VALIDATION" },+ });});it("reports and rethrows a reportable handler error", async () => {@@ -100,22 +84,31 @@ describe("instrumentMcpToolHandler", () => {expect(mocks.captureServerError.mock.calls[0][2]).toBe("user-1");});- it("rethrows expected errors without reporting them", async () => {+ it("rethrows expected errors without reporting them, as failed usage with no activation", async () => {const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () => {throw new AppError("NOT_FOUND");});await expect(wrapped({}, toolContext)).rejects.toThrow("NOT_FOUND");expect(mocks.captureServerError).not.toHaveBeenCalled();+ expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({+ event: "mcp:tool_call",+ properties: { success: false, error_code: "NOT_FOUND" },+ });+ expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();});- it("captures a usage event for every call", async () => {+ it("captures a usage event and the activation milestone for a successful external call", async () => {const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>- okResult({ items: [] }),+ okResult({ items: [{ domain: "example.com" }] }),);- await wrapped({}, toolContext);+ const result = await wrapped({}, toolContext);+ expect(result.structuredContent).toEqual({+ items: [{ domain: "example.com" }],+ });+ expect(mocks.captureServerError).not.toHaveBeenCalled();expect(mocks.captureServerEvent).toHaveBeenCalledTimes(1);expect(mocks.incrementSelfHostMcpToolCallCount).toHaveBeenCalledTimes(1);expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({@@ -129,82 +122,44 @@ describe("instrumentMcpToolHandler", () => {source: "mcp_client",},});- });-- it("marks schema-rejected results as failed usage", async () => {- const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>- okResult({ items: "not-an-array" }),- );-- await wrapped({}, toolContext);-- expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({- event: "mcp:tool_call",- properties: { success: false, error_code: "MCP_OUTPUT_VALIDATION" },- });- });-- it("marks a structured tool error as failed usage without recording activation", async () => {- const schema = z.object({- status: z.enum(["ok", "error"]),- error: z.object({ code: z.string() }).optional(),- });- const wrapped = instrumentMcpToolHandler("demo", schema, async () =>- okResult({ status: "error", error: { code: "ga4_not_connected" } }),- );-- await wrapped({}, toolContext);-- expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({- event: "mcp:tool_call",- properties: { success: false, error_code: "ga4_not_connected" },- });- expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();- });-- it("marks an ok-false tool result as failed usage", async () => {- const schema = z.object({- ok: z.boolean(),- reason: z.string().optional(),- });- const wrapped = instrumentMcpToolHandler("demo", schema, async () =>- okResult({ ok: false, reason: "audit_not_ready" }),- );-- await wrapped({}, toolContext);-- expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({- event: "mcp:tool_call",- properties: { success: false, error_code: "audit_not_ready" },- });- expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();- });-- it("captures a failed usage event with the error code", async () => {- const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () => {- throw new AppError("NOT_FOUND");- });-- await expect(wrapped({}, toolContext)).rejects.toThrow("NOT_FOUND");-- expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({- event: "mcp:tool_call",- properties: { success: false, error_code: "NOT_FOUND" },- });- });-- it("records the activation milestone for a successful external call", async () => {- const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>- okResult({ items: [] }),- );-- await wrapped({}, toolContext);-expect(mocks.recordExternalMcpToolCall).toHaveBeenCalledExactlyOnceWith("org-1",);});+ it.each([+ [+ "structured error",+ z.object({+ status: z.enum(["ok", "error"]),+ error: z.object({ code: z.string() }).optional(),+ }),+ { status: "error", error: { code: "ga4_not_connected" } },+ "ga4_not_connected",+ ],+ [+ "ok-false",+ z.object({ ok: z.boolean(), reason: z.string().optional() }),+ { ok: false, reason: "audit_not_ready" },+ "audit_not_ready",+ ],+ ])(+ "marks a %s tool result as failed usage without recording activation",+ async (_label, schema, structuredContent, errorCode) => {+ const wrapped = instrumentMcpToolHandler("demo", schema, async () =>+ okResult(structuredContent),+ );++ await wrapped({}, toolContext);++ expect(mocks.captureServerEvent.mock.calls[0][0]).toMatchObject({+ event: "mcp:tool_call",+ properties: { success: false, error_code: errorCode },+ });+ expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();+ },+ );+it("skips the activation milestone for first-party (null clientId) calls", async () => {const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>okResult({ items: [] }),@@ -214,14 +169,4 @@ describe("instrumentMcpToolHandler", () => {expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();});-- it("skips the activation milestone when the call fails", async () => {- const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () => {- throw new AppError("NOT_FOUND");- });-- await expect(wrapped({}, toolContext)).rejects.toThrow("NOT_FOUND");-- expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();- });});diff --git a/src/server/mcp/oauth-provider.test.ts b/src/server/mcp/oauth-provider.test.tsindex 13653bd7..a387c424 100644--- a/src/server/mcp/oauth-provider.test.ts+++ b/src/server/mcp/oauth-provider.test.ts@@ -1,11 +1,13 @@import {+ AuthorizationError as ProviderAuthorizationError,GrantType,+ OAuthError as ProviderOAuthError,type OAuthProviderOptions,type TokenExchangeCallbackOptions,} from "@cloudflare/workers-oauth-provider";import { beforeEach, describe, expect, it, vi } from "vitest";import { z } from "zod";-import type { createOpenSeoOAuthProvider } from "./oauth-provider";+import { createOpenSeoOAuthProvider } from "./oauth-provider";const mocks = vi.hoisted(() => ({options: [] as OAuthProviderOptions<unknown>[],@@ -179,42 +181,17 @@ describe("OpenSEO OAuth provider configuration", () => {});it("binds tokens and protected-resource metadata to the canonical MCP URL", async () => {- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");const provider = createOpenSeoOAuthProvider(() => new Response("app"));await dispatch(provider, new Request("https://app.openseo.so/health"));expect(mocks.options).toHaveLength(1);- expect(mocks.options[0]?.resourceMetadata).toEqual({- resource: "https://app.openseo.so/mcp",- scopes_supported: ["mcp"],- resource_name: "OpenSEO MCP",- });- expect(mocks.options[0]?.scopesSupported).toEqual([- "offline_access",- "mcp",- ]);- expect(mocks.options[0]?.clientRegistrationTTL).toBe(60 * 60 * 24 * 365);- });-- it("purges OAuth KV data without needing a prior request", async () => {- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");- const provider = createOpenSeoOAuthProvider(() => new Response("app"));-- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- mocked provider does not read its KV-backed environment- const result = await provider.purgeExpiredData({} as never);-- expect(result.done).toBe(true);- expect(mocks.purges).toHaveLength(1);- // The lazily built provider still pins the hosted resource.expect(mocks.options[0]?.resourceMetadata).toMatchObject({resource: "https://app.openseo.so/mcp",});});it("rejects token exchanges that drop the required MCP scope", async () => {- const { OAuthError } = await import("@cloudflare/workers-oauth-provider");- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");const provider = createOpenSeoOAuthProvider(() => new Response("app"));await dispatch(provider, new Request("https://app.openseo.so/health"));@@ -223,7 +200,7 @@ describe("OpenSEO OAuth provider configuration", () => {if (!callback) throw new Error("Missing token exchange callback");expect(() =>callback(tokenExchangeOptions(["offline_access"])),- ).toThrowError(OAuthError);+ ).toThrowError(ProviderOAuthError);expect(callback(tokenExchangeOptions(["mcp"]))).toEqual({accessTokenProps: {openSeoAuth: {@@ -239,7 +216,6 @@ describe("OpenSEO OAuth provider configuration", () => {});it("lets the provider issue Perplexity a real client secret", async () => {- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");const provider = createOpenSeoOAuthProvider(() => new Response("app"));await dispatch(@@ -260,7 +236,6 @@ describe("OpenSEO OAuth provider configuration", () => {});it("includes the authorization-server issuer when consent is denied", async () => {- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");const provider = createOpenSeoOAuthProvider(() => new Response("app"));await dispatch(provider, new Request("https://app.openseo.so/health"));@@ -299,10 +274,7 @@ describe("OpenSEO OAuth provider configuration", () => {});});- it("redirects safe authorization errors with state and issuer", async () => {- const { AuthorizationError } =- await import("@cloudflare/workers-oauth-provider");- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");+ it("redirects safe authorization errors with state and issuer, rethrowing anything else", async () => {const provider = createOpenSeoOAuthProvider(() => new Response("app"));await dispatch(provider, new Request("https://app.openseo.so/health"));@@ -312,7 +284,7 @@ describe("OpenSEO OAuth provider configuration", () => {OAUTH_PROVIDER: {parseAuthRequest: () =>Promise.reject(- new AuthorizationError("invalid_scope", {+ new ProviderAuthorizationError("invalid_scope", {description: "Unsupported scope",redirectUri: "https://client.example/callback",state: "state-1",@@ -332,13 +304,8 @@ describe("OpenSEO OAuth provider configuration", () => {state: "state-1",iss: "https://app.openseo.so",});- });-- it("does not expose unexpected authorization failures as client errors", async () => {- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");- const provider = createOpenSeoOAuthProvider(() => new Response("app"));- await dispatch(provider, new Request("https://app.openseo.so/health"));+ // Anything other than a provider AuthorizationError is not a client error.await expect(invokeDefaultHandler(new Request("https://app.openseo.so/api/auth/oauth2/authorize"),diff --git a/src/server/mcp/oauth-refresh.e2e.test.ts b/src/server/mcp/oauth-refresh.e2e.test.tsindex 577d5e7c..99b088bf 100644--- a/src/server/mcp/oauth-refresh.e2e.test.ts+++ b/src/server/mcp/oauth-refresh.e2e.test.ts@@ -1,7 +1,7 @@import { createHash, randomBytes } from "node:crypto";import { beforeEach, describe, expect, it, vi } from "vitest";import { z } from "zod";-import type { createOpenSeoOAuthProvider } from "./oauth-provider";+import { createOpenSeoOAuthProvider } from "./oauth-provider";// End-to-end OAuth lifecycle against the REAL @cloudflare/workers-oauth-provider// (only the Workers runtime shims and app session resolution are mocked),@@ -9,7 +9,7 @@ import type { createOpenSeoOAuthProvider } from "./oauth-provider";// PKCE S256, form-encoded token requests, and refresh with client_id only —// no client secret, no scope parameter. Refresh breakage has bitten real// clients before (PR #420); these tests pin the full register → authorize →-// consent → token → use → refresh → rotate chain.+// consent → token → use → refresh chain.const BASE = "https://app.openseo.so";const MCP_RESOURCE = `${BASE}/mcp`;@@ -133,9 +133,8 @@ type Env = Parameters<Provider["fetch"]>[1];let provider: Provider;let env: Env;-beforeEach(async () => {+beforeEach(() => {vi.useRealTimers();- const { createOpenSeoOAuthProvider } = await import("./oauth-provider");provider = createOpenSeoOAuthProvider(() => new Response("app"));// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the provider touches only OAUTH_KVenv = { OAUTH_KV: createKvFake() } as unknown as Env;@@ -144,7 +143,6 @@ beforeEach(async () => {const registrationSchema = z.looseObject({client_id: z.string(),token_endpoint_auth_method: z.string(),- client_secret: z.string().optional(),});const tokenResponseSchema = z.looseObject({@@ -173,9 +171,7 @@ function dispatch(request: Request) {}// Codex's DCR registration omits token_endpoint_auth_method entirely.-async function registerCodexStyleClient(- overrides: Record<string, unknown> = {},-) {+async function registerCodexStyleClient() {const response = await dispatch(new Request(`${BASE}/api/auth/oauth2/register`, {method: "POST",@@ -185,7 +181,6 @@ async function registerCodexStyleClient(redirect_uris: ["http://localhost:1455/auth/callback"],grant_types: ["authorization_code", "refresh_token"],response_types: ["code"],- ...overrides,}),}),);@@ -321,30 +316,6 @@ describe("Codex-style OAuth token refresh (real workers-oauth-provider)", () =>expect(second.status).toBe(200);});- it("honors the previous refresh token until the rotated one is used", async () => {- // Codex can lose a token response (crash, retry): the provider keeps the- // pre-rotation token valid until the new one is first used.- const { client, tokens } = await setupSession();-- const first = tokenResponseSchema.parse(- await (await refresh(client.client_id, tokens.refresh_token)).json(),- );- // Retry with the ORIGINAL token before ever using the rotated one.- const retry = await refresh(client.client_id, tokens.refresh_token);- expect(retry.status).toBe(200);-- const retried = tokenResponseSchema.parse(await retry.json());- // Once a newer refresh token is used, the stale original is rejected.- const afterUse = await refresh(client.client_id, retried.refresh_token);- expect(afterUse.status).toBe(200);- const stale = await refresh(client.client_id, tokens.refresh_token);- expect(stale.status).toBe(400);- expect(tokenErrorSchema.parse(await stale.json()).error).toBe(- "invalid_grant",- );- void first;- });-it("accepts a refresh carrying the canonical RFC 8707 resource and rejects a mismatched one", async () => {const { client, tokens } = await setupSession();@@ -424,45 +395,4 @@ describe("Codex-style OAuth token refresh (real workers-oauth-provider)", () =>vi.useRealTimers();}});-- it("still rejects a secretless refresh from a client registered as confidential", async () => {- // The pre-PR-#420 failure mode: a client stored with client_secret_basic- // that never sends its secret fails refresh until it re-registers.- const client = await registerCodexStyleClient({- token_endpoint_auth_method: "client_secret_basic",- });- expect(client.client_secret).toBeTruthy();- const codeVerifier = randomBytes(32).toString("base64url");- const code = await authorizeAndGetCode(client.client_id, codeVerifier);-- // Confidential clients must authenticate even at the code exchange — and- // since 0.9.0 the registered method is enforced: client_secret_basic means- // the Authorization header, not a client_secret form field.- const basicAuth = Buffer.from(- `${client.client_id}:${client.client_secret ?? ""}`,- ).toString("base64");- const exchange = await dispatch(- new Request(`${BASE}/api/auth/oauth2/token`, {- method: "POST",- headers: {- "Content-Type": "application/x-www-form-urlencoded",- Authorization: `Basic ${basicAuth}`,- },- body: new URLSearchParams({- grant_type: "authorization_code",- code,- redirect_uri: "http://localhost:1455/auth/callback",- code_verifier: codeVerifier,- }).toString(),- }),- );- expect(exchange.status).toBe(200);- const tokens = tokenResponseSchema.parse(await exchange.json());-- const secretless = await refresh(client.client_id, tokens.refresh_token);- expect(secretless.status).toBe(401);- expect(tokenErrorSchema.parse(await secretless.json()).error).toBe(- "invalid_client",- );- });});diff --git a/src/server/mcp/oauth-registration.test.ts b/src/server/mcp/oauth-registration.test.tsindex c2d5ccce..b9e9ed0f 100644--- a/src/server/mcp/oauth-registration.test.ts+++ b/src/server/mcp/oauth-registration.test.ts@@ -2,67 +2,6 @@ import { describe, expect, it } from "vitest";import { normalizeClientRegistrationRequest } from "@/server/mcp/oauth-registration";describe("normalizeClientRegistrationRequest", () => {- it("keeps explicit public registrations public", async () => {- const request = new Request(- "https://app.openseo.so/api/auth/oauth2/register",- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- redirect_uris: ["http://localhost:1455/auth/callback"],- client_name: "Codex",- token_endpoint_auth_method: "none",- }),- },- );-- const normalized = await normalizeClientRegistrationRequest(request);-- await expect(normalized.json()).resolves.toMatchObject({- token_endpoint_auth_method: "none",- });- });-- it("registers Perplexity as a real confidential client", async () => {- const request = new Request(- "https://app.openseo.so/api/auth/oauth2/register",- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- redirect_uris: ["https://www.perplexity.ai/api/mcp/oauth/callback"],- client_name: "Perplexity",- }),- },- );-- const normalized = await normalizeClientRegistrationRequest(request);-- await expect(normalized.json()).resolves.toMatchObject({- token_endpoint_auth_method: "client_secret_post",- });- });-- it("defaults other omitted token auth methods to public clients", async () => {- const request = new Request(- "https://app.openseo.so/api/auth/oauth2/register",- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- redirect_uris: ["http://localhost:1455/auth/callback"],- client_name: "Codex",- }),- },- );-- const normalized = await normalizeClientRegistrationRequest(request);-- await expect(normalized.json()).resolves.toMatchObject({- token_endpoint_auth_method: "none",- });- });-it("keeps explicit confidential registration methods", async () => {const request = new Request("https://app.openseo.so/api/auth/oauth2/register",@@ -82,27 +21,4 @@ describe("normalizeClientRegistrationRequest", () => {token_endpoint_auth_method: "client_secret_post",});});-- it("leaves oversized registration payloads for the provider to reject", async () => {- const body = JSON.stringify({- redirect_uris: ["https://www.perplexity.ai/api/mcp/oauth/callback"],- client_name: "a".repeat(1024 * 1024),- token_endpoint_auth_method: "none",- });- const request = new Request(- "https://app.openseo.so/api/auth/oauth2/register",- {- method: "POST",- headers: {- "Content-Type": "application/json",- "Content-Length": String(body.length),- },- body,- },- );-- await expect(normalizeClientRegistrationRequest(request)).resolves.toBe(- request,- );- });});diff --git a/src/server/mcp/output-schema-contract.test.ts b/src/server/mcp/output-schema-contract.test.tsindex 55b986b2..1ba6e435 100644--- a/src/server/mcp/output-schema-contract.test.ts+++ b/src/server/mcp/output-schema-contract.test.ts@@ -137,19 +137,4 @@ describe("published MCP output schemas", () => {),).toEqual(["tool.properties.rows.items[0].anyOf[0].additionalProperties"]);});-- it("ignores example data and property names that resemble schema keywords", () => {- expect(- closedOutputPaths(- {- properties: {- additionalProperties: { type: "boolean", const: false },- },- examples: [{ additionalProperties: false }],- default: { unevaluatedProperties: false },- },- "tool",- ),- ).toEqual([]);- });});diff --git a/src/server/mcp/project-auth.test.ts b/src/server/mcp/project-auth.test.tsindex 6ba42308..bf0b376a 100644--- a/src/server/mcp/project-auth.test.ts+++ b/src/server/mcp/project-auth.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { withMcpProjectAuth } from "@/server/mcp/project-auth";import { makeToolContext } from "@/server/mcp/tools/tool-test-support";const mocks = vi.hoisted(() => ({@@ -24,8 +25,6 @@ const toolContext = makeToolContext();describe("withMcpProjectAuth", () => {beforeEach(() => {- vi.resetModules();- mocks.getProjectForOrganization.mockReset();// Default: the project belongs to the org. Individual tests override.mocks.getProjectForOrganization.mockResolvedValue({id: "project_123",@@ -35,28 +34,16 @@ describe("withMcpProjectAuth", () => {});});- it("checks project access for the authenticated organization", async () => {- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");- const handler = vi.fn().mockResolvedValue("ok");+ it("checks project access for the authenticated organization and passes auth, billing, and project context to the handler", async () => {+ const handler = vi.fn().mockReturnValue("ok");const wrapped = withMcpProjectAuth(handler);- await expect(- wrapped({ projectId: "project_123" }, toolContext),- ).resolves.toBe("ok");+ await wrapped({ projectId: "project_123" }, toolContext);expect(mocks.getProjectForOrganization).toHaveBeenCalledWith("org_123","project_123",);- });-- it("passes auth, baseUrl, billing, and project context to the wrapped handler", async () => {- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");- const handler = vi.fn().mockReturnValue("ok");-- const wrapped = withMcpProjectAuth(handler);- await wrapped({ projectId: "project_123" }, toolContext);-expect(handler).toHaveBeenCalledWith({ projectId: "project_123" },{@@ -86,26 +73,11 @@ describe("withMcpProjectAuth", () => {);});- it("propagates project access failures without calling the wrapped handler", async () => {- const error = new Error("project not found");- mocks.getProjectForOrganization.mockRejectedValue(error);- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");- const handler = vi.fn();-- const wrapped = withMcpProjectAuth(handler);- await expect(- wrapped({ projectId: "project_123" }, toolContext),- ).rejects.toBe(error);-- expect(handler).not.toHaveBeenCalled();- });-// Defense-in-depth: even if the project lookup ever resolves falsy instead of// throwing (e.g. a future refactor returns null), the wrapper must still deny// access rather than run the handler with an unauthorized projectId.it("rejects when the project lookup resolves no project, without calling the handler", async () => {mocks.getProjectForOrganization.mockResolvedValue(null);- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");const handler = vi.fn();const wrapped = withMcpProjectAuth(handler);@@ -124,7 +96,6 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {const userScopedContext = makeToolContext({ orgScope: "user" });beforeEach(() => {- vi.resetModules();mocks.getProjectWithOrganization.mockResolvedValue({organizationId: "org_other",project: {@@ -138,7 +109,6 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {});it("rebinds auth and billing to the project's org and the member's role there", async () => {- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");const userContext = makeToolContext({ orgScope: "user" });const handler = vi.fn<(@@ -168,7 +138,6 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {it("rejects when the caller has no membership in the project's org", async () => {mocks.getMembership.mockResolvedValue(null);- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");const handler = vi.fn();await expect(@@ -183,7 +152,6 @@ describe("withMcpProjectAuth with a user-scoped credential", () => {it("rejects an unknown project without leaking whether it exists", async () => {mocks.getProjectWithOrganization.mockResolvedValue(null);- const { withMcpProjectAuth } = await import("@/server/mcp/project-auth");const handler = vi.fn();await expect(diff --git a/src/server/mcp/public-origin.test.ts b/src/server/mcp/public-origin.test.tsindex 4af32021..369a6ca7 100644--- a/src/server/mcp/public-origin.test.ts+++ b/src/server/mcp/public-origin.test.ts@@ -15,12 +15,6 @@ describe("getPublicOrigin", () => {);});- it("falls back to the request origin without proxy headers", () => {- const request = new Request("http://localhost:3102/api/oauth/consent");-- expect(getPublicOrigin(request)).toBe("http://localhost:3102");- });-it("ignores forwarded hosts when the request is already public https", () => {const request = new Request("https://app.openseo.so/api/oauth/consent", {headers: {diff --git a/src/server/mcp/table.test.ts b/src/server/mcp/table.test.tsindex 18b14897..cbf8e5cf 100644--- a/src/server/mcp/table.test.ts+++ b/src/server/mcp/table.test.ts@@ -2,94 +2,49 @@ import { describe, expect, it } from "vitest";import { formatMcpCell, formatMcpTable, readPath } from "./table";describe("formatMcpCell", () => {- it("renders nullish and empty values as an em dash", () => {- expect(formatMcpCell(null)).toBe("—");- expect(formatMcpCell(undefined)).toBe("—");- expect(formatMcpCell("")).toBe("—");- });-- it("keeps integers exact and gives other numbers two decimals", () => {- expect(formatMcpCell(0)).toBe("0");- expect(formatMcpCell(2400)).toBe("2400");- expect(formatMcpCell(1.5)).toBe("1.50");- expect(formatMcpCell(0.333333)).toBe("0.33");- });-- it("renders non-finite numbers as an em dash", () => {- expect(formatMcpCell(Number.NaN)).toBe("—");- expect(formatMcpCell(Number.POSITIVE_INFINITY)).toBe("—");- });-- it("renders booleans and bigints", () => {- expect(formatMcpCell(true)).toBe("yes");- expect(formatMcpCell(false)).toBe("no");- expect(formatMcpCell(10n)).toBe("10");- });-- it("collapses whitespace so a stray newline can't break the table", () => {- expect(formatMcpCell("multi\nline value")).toBe("multi line value");- });-- it("emits compact JSON for objects instead of [object Object]", () => {- expect(formatMcpCell({ a: 1 })).toBe('{"a":1}');- expect(formatMcpCell([1, 2])).toBe("[1,2]");+ it.each([+ [null, "—"],+ [undefined, "—"],+ ["", "—"],+ [Number.NaN, "—"],+ [Number.POSITIVE_INFINITY, "—"],+ [0, "0"],+ [2400, "2400"],+ [1.5, "1.50"],+ [0.333333, "0.33"],+ ["multi\nline value", "multi line value"],+ [{ a: 1 }, '{"a":1}'],+ [[1, 2], "[1,2]"],+ ])("renders %j as %j", (input, expected) => {+ expect(formatMcpCell(input)).toBe(expected);});});describe("formatMcpTable", () => {- type Row = { keyword: string; volume: number | null };- const columns = [- { header: "keyword", value: (row: Row) => row.keyword },- { header: "volume", value: (row: Row) => row.volume },- ];-it("renders a header line plus one line per row", () => {+ type Row = { keyword: string; volume: number | null };const table = formatMcpTable([{ keyword: "seo tools", volume: 2400 },{ keyword: "seo audit", volume: null },],- columns,- );- expect(table).toBe(- ["keyword | volume", "seo tools | 2400", "seo audit | —"].join("\n"),- );- });-- it("renders only the header when there are no rows", () => {- expect(formatMcpTable([], columns)).toBe("keyword | volume");- });-- it("uses a per-column format override when provided", () => {- const table = formatMcpTable(- [{ keyword: "x", volume: 0.04 }],[{ header: "keyword", value: (row: Row) => row.keyword },- {- header: "CTR",- value: (row: Row) => row.volume,- format: (value) =>- typeof value === "number" ? `${(value * 100).toFixed(1)}%` : "—",- },+ { header: "volume", value: (row: Row) => row.volume },],);- expect(table).toBe(["keyword | CTR", "x | 4.0%"].join("\n"));+ expect(table).toBe(+ ["keyword | volume", "seo tools | 2400", "seo audit | —"].join("\n"),+ );});});describe("readPath", () => {- it("walks nested records", () => {+ it("walks nested records and returns undefined when a hop is missing or not an object", () => {expect(readPath({ a: { b: { c: 3 } } }, "a", "b", "c")).toBe(3);- });-- it("returns undefined when a hop is missing or not an object", () => {expect(readPath({ a: null }, "a", "b")).toBeUndefined();expect(readPath({ a: 1 }, "a", "b")).toBeUndefined();expect(readPath(null, "a")).toBeUndefined();expect(readPath(undefined, "a")).toBeUndefined();});-- it("reads a top-level key", () => {- expect(readPath({ keyword: "seo" }, "keyword")).toBe("seo");- });});diff --git a/src/server/mcp/tools/cleanup-tools.test.ts b/src/server/mcp/tools/cleanup-tools.test.tsindex 39abc04f..340c387b 100644--- a/src/server/mcp/tools/cleanup-tools.test.ts+++ b/src/server/mcp/tools/cleanup-tools.test.ts@@ -1,12 +1,8 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { z } from "zod";import { removeSavedKeywordsTool } from "./remove-saved-keywords";import { deleteReportTool } from "./report-tools";import { deleteReportTemplateTool } from "./report-template-tools";-import {- deleteSiteAuditTool,- listSiteAuditsTool,-} from "./site-audit-cleanup-tools";+import { deleteSiteAuditTool } from "./site-audit-cleanup-tools";import { makeToolContext } from "./tool-test-support";const mocks = vi.hoisted(() => ({@@ -15,7 +11,6 @@ const mocks = vi.hoisted(() => ({removeSavedKeywords: vi.fn(),deleteTemplate: vi.fn(),getAuditForProject: vi.fn(),- getAuditsByProject: vi.fn(),deleteAuditForProject: vi.fn(),terminate: vi.fn(),status: vi.fn(),@@ -58,17 +53,17 @@ beforeEach(() => {mocks.getProjectForOrganization.mockResolvedValue({ id: "project_1" });mocks.deleteReport.mockResolvedValue(true);mocks.deleteTemplate.mockResolvedValue(true);+ mocks.removeSavedKeywords.mockResolvedValue(1);mocks.getAuditForProject.mockResolvedValue({id: "audit_1",status: "completed",});- mocks.getAuditsByProject.mockResolvedValue([]);});const context = makeToolContext();const deletes = [{- tool: deleteReportTool,+ name: deleteReportTool.name,call: () =>deleteReportTool.handler({ projectId: "project_1", reportId: "report_1" },@@ -78,7 +73,7 @@ const deletes = [scopedArgs: ["project_1", "report_1"],},{- tool: deleteReportTemplateTool,+ name: deleteReportTemplateTool.name,call: () =>deleteReportTemplateTool.handler({ projectId: "project_1", templateId: "template_1" },@@ -88,7 +83,7 @@ const deletes = [scopedArgs: ["project_1", "template_1"],},{- tool: deleteSiteAuditTool,+ name: deleteSiteAuditTool.name,call: () =>deleteSiteAuditTool.handler({ projectId: "project_1", auditId: "audit_1" },@@ -97,11 +92,21 @@ const deletes = [storage: mocks.deleteAuditForProject,scopedArgs: ["audit_1", "project_1"],},+ {+ name: removeSavedKeywordsTool.name,+ call: () =>+ removeSavedKeywordsTool.handler(+ { projectId: "project_1", savedKeywordIds: ["saved_1", "saved_2"] },+ context,+ ),+ storage: mocks.removeSavedKeywords,+ scopedArgs: [["saved_1", "saved_2"], "project_1"],+ },];-describe.each(deletes)("$tool.name", ({ tool, call, storage, scopedArgs }) => {+describe.each(deletes)("$name", ({ call, storage, scopedArgs }) => {it("deletes only within the authorized project", async () => {- expect((await call()).structuredContent.deleted).toBe(true);+ await call();expect(storage).toHaveBeenCalledWith(...scopedArgs);});@@ -110,31 +115,17 @@ describe.each(deletes)("$tool.name", ({ tool, call, storage, scopedArgs }) => {await expect(call()).rejects.toMatchObject({ code: "FORBIDDEN" });expect(storage).not.toHaveBeenCalled();});-- it("refuses missing IDs or IDs belonging to another project", async () => {- mocks.deleteReport.mockResolvedValue(false);- mocks.deleteTemplate.mockResolvedValue(false);- mocks.getAuditForProject.mockResolvedValue(null);- await expect(call()).rejects.toMatchObject({ code: "NOT_FOUND" });- });-- it("requires an explicit target and advertises destructive behavior", () => {- expect(- z.object(tool.config.inputSchema).safeParse({ projectId: "project_1" })- .success,- ).toBe(false);- expect(tool.config.annotations.destructiveHint).toBe(true);- });});describe("site audit cleanup", () => {- it("lists empty history without starting or deleting an audit", async () => {- const result = await listSiteAuditsTool.handler(- { projectId: "project_1" },- context,- );- expect(result.structuredContent.audits).toEqual([]);- expect(mocks.getAuditsByProject).toHaveBeenCalledWith("project_1");+ it("refuses an audit that is missing or belongs to another project", async () => {+ mocks.getAuditForProject.mockResolvedValue(null);+ await expect(+ deleteSiteAuditTool.handler(+ { projectId: "project_1", auditId: "audit_1" },+ context,+ ),+ ).rejects.toMatchObject({ code: "NOT_FOUND" });expect(mocks.deleteAuditForProject).not.toHaveBeenCalled();});@@ -184,56 +175,3 @@ describe("site audit cleanup", () => {expect(mocks.deleteAuditForProject).not.toHaveBeenCalled();});});--describe("remove_saved_keywords", () => {- it("passes exact row IDs to the scoped service and reports actual deletions", async () => {- mocks.removeSavedKeywords.mockResolvedValue(1);- const ids = ["saved_1", "saved_1", "missing_or_foreign"];- const result = await removeSavedKeywordsTool.handler(- { projectId: "project_1", savedKeywordIds: ids },- context,- );- expect(mocks.removeSavedKeywords).toHaveBeenCalledWith(ids, "project_1");- expect(result.structuredContent).toMatchObject({- projectId: "project_1",- requested: 3,- deletedCount: 1,- });- expect(- removeSavedKeywordsTool.config.outputSchema.safeParse(- result.structuredContent,- ).success,- ).toBe(true);- });-- it("refuses inaccessible projects before deletion", async () => {- mocks.getProjectForOrganization.mockResolvedValue(null);- await expect(- removeSavedKeywordsTool.handler(- { projectId: "project_1", savedKeywordIds: ["saved_1"] },- context,- ),- ).rejects.toMatchObject({ code: "FORBIDDEN" });- expect(mocks.removeSavedKeywords).not.toHaveBeenCalled();- });-- it("reports zero when no requested row belongs to the project", async () => {- mocks.removeSavedKeywords.mockResolvedValue(0);- const result = await removeSavedKeywordsTool.handler(- { projectId: "project_1", savedKeywordIds: ["missing_or_foreign"] },- context,- );- expect(result.structuredContent.deletedCount).toBe(0);- });-- it.each([undefined, [], [""], Array.from({ length: 2001 }, () => "saved_1")])(- "rejects a missing, empty, invalid, or oversized target list (%#)",- (savedKeywordIds) => {- expect(- z- .object(removeSavedKeywordsTool.config.inputSchema)- .safeParse({ projectId: "project_1", savedKeywordIds }).success,- ).toBe(false);- },- );-});diff --git a/src/server/mcp/tools/create-project.test.ts b/src/server/mcp/tools/create-project.test.tsindex e74d5009..dd717646 100644--- a/src/server/mcp/tools/create-project.test.ts+++ b/src/server/mcp/tools/create-project.test.ts@@ -22,8 +22,6 @@ vi.mock("@/server/auth/repositories/AuthRepository", () => ({const toolContext = makeToolContext();describe("create_project MCP tool", () => {- beforeEach(() => {});-it("creates a project scoped to the caller's organization and returns it", async () => {mocks.createProject.mockResolvedValue({id: "project_new",@@ -60,32 +58,6 @@ describe("create_project MCP tool", () => {}});- it("creates a minimal project with only a name (org default market)", async () => {- mocks.createProject.mockResolvedValue({- id: "project_min",- name: "Just a name",- domain: null,- locationCode: 2840,- languageCode: "en",- });-- await createProjectTool.handler({ name: "Just a name" }, toolContext);-- expect(mocks.createProject).toHaveBeenCalledWith("org_123", {- name: "Just a name",- });- });-- it("rejects a languageCode without a locationCode (market pair rule)", async () => {- await expect(- createProjectTool.handler(- { name: "Bad market", languageCode: "en" },- toolContext,- ),- ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });- expect(mocks.createProject).not.toHaveBeenCalled();- });-it("rejects an unsupported location as a readable validation error", async () => {const call = () =>createProjectTool.handler(diff --git a/src/server/mcp/tools/dataforseo-research-tools.google-ads.test.ts b/src/server/mcp/tools/dataforseo-research-tools.google-ads.test.tsdeleted file mode 100644index dcdb98f1..00000000--- a/src/server/mcp/tools/dataforseo-research-tools.google-ads.test.ts+++ /dev/null@@ -1,139 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import { z } from "zod";-import type { fetchKeywordMetricsForList as FetchKeywordMetricsForList } from "@/server/lib/dataforseo/keyword-metrics";-import { getKeywordMetricsTool } from "./dataforseo-research-tools";-import { makeToolContext } from "./tool-test-support";--const mocks = vi.hoisted(() => ({- createDataforseoClient: vi.fn(),- getProjectForOrganization: vi.fn(),-}));--vi.mock("cloudflare:workers", () => ({- env: {},-}));--// Keep the real fetchKeywordMetricsForList (it only routes provider calls onto-// the supplied client) so the handler's normalization is exercised end-to-end.-vi.mock("@/server/lib/dataforseo", async () => {- const keywordMetrics = await vi.importActual<{- fetchKeywordMetricsForList: typeof FetchKeywordMetricsForList;- }>("@/server/lib/dataforseo/keyword-metrics");- return {- createDataforseoClient: mocks.createDataforseoClient,- fetchKeywordMetricsForList: keywordMetrics.fetchKeywordMetricsForList,- };-});--vi.mock("@/server/features/projects/services/ProjectService", () => ({- ProjectService: {- getProjectForOrganization: mocks.getProjectForOrganization,- },-}));--const toolContext = makeToolContext();--describe("get_keyword_metrics for Google-Ads-only locations", () => {- beforeEach(() => {- mocks.getProjectForOrganization.mockResolvedValue({- id: "project_1",- locationCode: 2840,- languageCode: "en",- });- });-- it("serves Iceland from adsSearchVolume without KD/intent", async () => {- const keywordOverview = vi.fn();- const adsSearchVolume = vi.fn().mockResolvedValue([- {- keyword: "hotel reykjavik",- search_volume: 1300,- cpc: 2.54,- competition: "HIGH",- competition_index: 42,- monthly_searches: [{ year: 2026, month: 5, search_volume: 1300 }],- },- ]);-- mocks.createDataforseoClient.mockReturnValue({- labs: { keywordOverview },- keywords: { adsSearchVolume },- });-- const result = await getKeywordMetricsTool.handler(- {- projectId: "project_1",- keywords: ["hotel reykjavik"],- // Iceland is not supported by DataForSEO Labs.- locationCode: 2352,- languageCode: "is",- },- toolContext,- );-- expect(keywordOverview).not.toHaveBeenCalled();- expect(adsSearchVolume).toHaveBeenCalledWith(- expect.objectContaining({- keywords: ["hotel reykjavik"],- locationCode: 2352,- languageCode: "is",- creditFeature: "keyword_research",- }),- );- const rows = z- .object({ keywords: z.array(z.record(z.string(), z.unknown())) })- .passthrough()- .parse(result.structuredContent).keywords;- expect(rows[0]).toMatchObject({- keyword: "hotel reykjavik",- search_volume: 1300,- keyword_difficulty: null,- main_intent: null,- cpc: 2.54,- competition: 0.42,- competition_level: "HIGH",- });- });-- it("passes the clickstream opt-in to Labs and prefers refined volumes", async () => {- const keywordOverview = vi.fn().mockResolvedValue([- {- keyword: "seo tools",- keyword_info: {- search_volume: 10000,- monthly_searches: [{ year: 2026, month: 5, search_volume: 10000 }],- },- keyword_info_normalized_with_clickstream: {- search_volume: 6400,- monthly_searches: [{ year: 2026, month: 5, search_volume: 6400 }],- },- },- ]);-- mocks.createDataforseoClient.mockReturnValue({- labs: { keywordOverview },- });-- const result = await getKeywordMetricsTool.handler(- {- projectId: "project_1",- keywords: ["seo tools"],- includeClickstreamData: true,- },- toolContext,- );-- expect(keywordOverview).toHaveBeenCalledWith(- expect.objectContaining({ includeClickstreamData: true }),- );- const rows = z- .object({ keywords: z.array(z.record(z.string(), z.unknown())) })- .passthrough()- .parse(result.structuredContent).keywords;- expect(rows[0]).toMatchObject({- keyword: "seo tools",- search_volume: 6400,- monthly_searches: [{ year: 2026, month: 5, search_volume: 6400 }],- });- });-});diff --git a/src/server/mcp/tools/dataforseo-research-tools.market.test.ts b/src/server/mcp/tools/dataforseo-research-tools.market.test.tsindex 51e335ee..37194e92 100644--- a/src/server/mcp/tools/dataforseo-research-tools.market.test.ts+++ b/src/server/mcp/tools/dataforseo-research-tools.market.test.ts@@ -32,9 +32,6 @@ const toolContext = makeToolContext();function setProject(market: { locationCode: number; languageCode: string }) {mocks.getProjectForOrganization.mockResolvedValue({id: "project_1",- name: "Test",- domain: null,- createdAt: "2026-01-01T00:00:00.000Z",...market,});}@@ -87,45 +84,6 @@ describe("market resolution for Labs tools", () => {);});- it("exposes explicit location and language selectors on both tool schemas", async () => {- expect(getRankedKeywordsTool.config.inputSchema.locationCode).toBeDefined();- expect(getRankedKeywordsTool.config.inputSchema.languageCode).toBeDefined();- expect(- findSerpCompetitorsTool.config.inputSchema.locationCode,- ).toBeDefined();- expect(- findSerpCompetitorsTool.config.inputSchema.languageCode,- ).toBeDefined();- });-- it("passes an explicit non-US market to both Labs tools", async () => {- setProject({ locationCode: 2704, languageCode: "vi" });-- const rankedKeywords = await runRankedKeywords({- locationCode: 2756,- languageCode: "de",- });- expect(rankedKeywords).toHaveBeenCalledWith(- expect.objectContaining({ locationCode: 2756, languageCode: "de" }),- );-- const serpCompetitors = await runSerpCompetitors({- locationCode: 2756,- languageCode: "de",- });- expect(serpCompetitors).toHaveBeenCalledWith(- expect.objectContaining({ locationCode: 2756, languageCode: "de" }),- );- });-- it("uses the selected location's default language when only locationCode is explicit", async () => {- setProject({ locationCode: 2704, languageCode: "vi" });- const rankedKeywords = await runRankedKeywords({ locationCode: 2276 });- expect(rankedKeywords).toHaveBeenCalledWith(- expect.objectContaining({ locationCode: 2276, languageCode: "de" }),- );- });-it("prefers an explicit locationCode over the legacy market object", async () => {setProject({ locationCode: 2704, languageCode: "vi" });const rankedKeywords = await runRankedKeywords({@@ -163,14 +121,6 @@ describe("market resolution for Labs tools", () => {).rejects.toThrow("Domain analytics is not available for this country");});- it("follows the project's default market when the market object is omitted", async () => {- setProject({ locationCode: 2704, languageCode: "vi" });- const rankedKeywords = await runRankedKeywords({});- expect(rankedKeywords).toHaveBeenCalledWith(- expect.objectContaining({ locationCode: 2704, languageCode: "vi" }),- );- });-it("falls back to the US when the project market is not Labs-served", async () => {// Iceland (2352) is served from Google Ads data; the Labs-only market// tools must not inherit it.diff --git a/src/server/mcp/tools/dataforseo-research-tools.test.ts b/src/server/mcp/tools/dataforseo-research-tools.test.tsindex 9ba749c1..d6e4c8e4 100644--- a/src/server/mcp/tools/dataforseo-research-tools.test.ts+++ b/src/server/mcp/tools/dataforseo-research-tools.test.ts@@ -54,12 +54,8 @@ describe("DataForSEO research MCP tools", () => {attributes: { available_attributes: {} },},]);- const local = vi.fn();- const questionsAnswers = vi.fn();-mocks.createDataforseoClient.mockReturnValue({- business: { businessListings, questionsAnswers },- serp: { local },+ business: { businessListings },});const result = await researchTools.searchLocalBusinessesTool.handler(@@ -83,14 +79,9 @@ describe("DataForSEO research MCP tools", () => {categories: ["cafe"],}),);- expect(local).not.toHaveBeenCalled();- expect(questionsAnswers).not.toHaveBeenCalled();-expect(result.structuredContent.businesses).toEqual([{ title: "Acme Cafe", url: "https://acme-cafe.example" },]);- expect(textContent(result)).toContain("title | category");- expect(textContent(result)).toContain("Acme Cafe");});it("maps local business rating/review/claim filters onto the provider call", async () => {@@ -213,8 +204,6 @@ describe("DataForSEO research MCP tools", () => {expect(content.questions).toEqual([{ question_text: "Do you serve breakfast?" },]);- expect(textContent(result)).toContain("question | asked by");- expect(textContent(result)).toContain("Do you serve breakfast?");});it("filters SERP competitors only by explicit excluded domains", async () => {@@ -248,28 +237,7 @@ describe("DataForSEO research MCP tools", () => {expect(textContent(result)).toContain("competitor.example");});- it("keeps AI overview result types out of SERP competitors", async () => {- const { findSerpCompetitorsTool, getRankedKeywordsTool } = researchTools;-- expect(- getRankedKeywordsTool.config.inputSchema.resultTypes.safeParse([- "ai_overview_reference",- ]).success,- ).toBe(true);- expect(- findSerpCompetitorsTool.config.inputSchema.resultTypes.safeParse([- "ai_overview_reference",- ]).success,- ).toBe(false);- expect(- findSerpCompetitorsTool.config.inputSchema.resultTypes.safeParse([- "organic",- "local_pack",- ]).success,- ).toBe(true);- });-- it("normalizes keyword_overview rows with difficulty and intent", async () => {+ it("normalizes keyword_overview rows with difficulty and intent, sorted by the requested field", async () => {const keywordOverview = vi.fn().mockResolvedValue([{keyword: "seo automation",@@ -282,23 +250,30 @@ describe("DataForSEO research MCP tools", () => {keyword_properties: { keyword_difficulty: 18 },search_intent_info: { main_intent: "commercial" },},+ { keyword: "high", keyword_info: { search_volume: 9000 } },+ { keyword: "low", keyword_info: { search_volume: 10 } },]);mocks.createDataforseoClient.mockReturnValue({labs: { keywordOverview },});- const { getKeywordMetricsTool } = researchTools;-- const result = await getKeywordMetricsTool.handler(- { projectId: "project_1", keywords: ["seo automation"] },+ const result = await researchTools.getKeywordMetricsTool.handler(+ {+ projectId: "project_1",+ keywords: ["seo automation", "high", "low"],+ sortBy: "search_volume",+ // Doubles the credit cost, so it must reach the paid call.+ includeClickstreamData: true,+ },toolContext,);expect(keywordOverview).toHaveBeenCalledWith(expect.objectContaining({- keywords: ["seo automation"],+ keywords: ["seo automation", "high", "low"],locationCode: 2840,languageCode: "en",+ includeClickstreamData: true,creditFeature: "keyword_research",}),);@@ -317,7 +292,12 @@ describe("DataForSEO research MCP tools", () => {}).passthrough().parse(result.structuredContent).keywords;- expect(rows[0]).toMatchObject({+ expect(rows.map((row) => row.keyword)).toEqual([+ "high",+ "seo automation",+ "low",+ ]);+ expect(rows[1]).toMatchObject({keyword: "seo automation",search_volume: 2400,keyword_difficulty: 18,@@ -328,64 +308,54 @@ describe("DataForSEO research MCP tools", () => {expect(out).toContain("seo automation");});- it("sorts keyword metric rows by the requested numeric field", async () => {- const keywordOverview = vi.fn().mockResolvedValue([- { keyword: "low", keyword_info: { search_volume: 10 } },- { keyword: "high", keyword_info: { search_volume: 90 } },- { keyword: "medium", keyword_info: { search_volume: 50 } },- ]);-- mocks.createDataforseoClient.mockReturnValue({- labs: { keywordOverview },- });- const { getKeywordMetricsTool } = researchTools;-- const result = await getKeywordMetricsTool.handler(- {- projectId: "project_1",- keywords: ["low", "high", "medium"],- sortBy: "search_volume",- },- toolContext,- );-- const rows = z- .object({ keywords: z.array(z.object({ keyword: z.string() })) })- .passthrough()- .parse(result.structuredContent).keywords;- expect(rows.map((row) => row.keyword)).toEqual(["high", "medium", "low"]);- });-- it("drops monthly trends when includeMonthlyTrends is false", async () => {- const keywordOverview = vi.fn().mockResolvedValue([+ it("serves a Google-Ads-only location (Iceland) from adsSearchVolume without KD/intent", async () => {+ const keywordOverview = vi.fn();+ const adsSearchVolume = vi.fn().mockResolvedValue([{- keyword: "seo",- keyword_info: {- search_volume: 100,- monthly_searches: [{ year: 2026, month: 1, search_volume: 100 }],- },+ keyword: "hotel reykjavik",+ search_volume: 1300,+ cpc: 2.54,+ competition: "HIGH",+ competition_index: 42,},]);mocks.createDataforseoClient.mockReturnValue({labs: { keywordOverview },+ keywords: { adsSearchVolume },});- const { getKeywordMetricsTool } = researchTools;- const result = await getKeywordMetricsTool.handler(+ const result = await researchTools.getKeywordMetricsTool.handler({projectId: "project_1",- keywords: ["seo"],- includeMonthlyTrends: false,+ keywords: ["hotel reykjavik"],+ // Iceland is not supported by DataForSEO Labs; the tool must resolve+ // the market with the Ads-aware resolver rather than the Labs-only one.+ locationCode: 2352,+ languageCode: "is",},toolContext,);+ expect(keywordOverview).not.toHaveBeenCalled();+ expect(adsSearchVolume).toHaveBeenCalledWith(+ expect.objectContaining({+ keywords: ["hotel reykjavik"],+ locationCode: 2352,+ languageCode: "is",+ creditFeature: "keyword_research",+ }),+ );const rows = z.object({ keywords: z.array(z.record(z.string(), z.unknown())) }).passthrough().parse(result.structuredContent).keywords;- expect(rows[0]).not.toHaveProperty("monthly_searches");+ expect(rows[0]).toMatchObject({+ keyword: "hotel reykjavik",+ search_volume: 1300,+ keyword_difficulty: null,+ main_intent: null,+ });});});diff --git a/src/server/mcp/tools/google-analytics-tools.test.ts b/src/server/mcp/tools/google-analytics-tools.test.tsindex b94c225f..e51dbaff 100644--- a/src/server/mcp/tools/google-analytics-tools.test.ts+++ b/src/server/mcp/tools/google-analytics-tools.test.ts@@ -6,9 +6,6 @@ import { makeToolContext } from "./tool-test-support";const mocks = vi.hoisted(() => ({runReport: vi.fn(),- getOrganicOverview: vi.fn(),- getMeasurementHealth: vi.fn(),- getOpportunities: vi.fn(),getProjectForOrganization: vi.fn(),}));@@ -19,17 +16,13 @@ vi.mock("@/server/features/ga4/services/Ga4ReportingService", () => ({},}));vi.mock("@/server/features/ga4/services/Ga4OrganicOverviewService", () => ({- Ga4OrganicOverviewService: {- getOrganicOverview: mocks.getOrganicOverview,- },+ Ga4OrganicOverviewService: { getOrganicOverview: vi.fn() },}));vi.mock("@/server/features/ga4/services/Ga4MeasurementHealthService", () => ({- Ga4MeasurementHealthService: {- getMeasurementHealth: mocks.getMeasurementHealth,- },+ Ga4MeasurementHealthService: { getMeasurementHealth: vi.fn() },}));vi.mock("@/server/features/ga4/services/SearchOpportunityService", () => ({- SearchOpportunityService: { getOpportunities: mocks.getOpportunities },+ SearchOpportunityService: { getOpportunities: vi.fn() },}));vi.mock("@/server/features/projects/services/ProjectService", () => ({ProjectService: {@@ -38,276 +31,159 @@ vi.mock("@/server/features/projects/services/ProjectService", () => ({}));const toolContext = makeToolContext();-const reportResult = makeGa4ReportResult({- rowCount: 1,- totalRowCount: 1,- rows: [{ hostName: "example.com", sessions: 5 }],-});+const page = { projectId: "project_1", limit: 100, offset: 0 };describe("Google Analytics MCP tools", () => {beforeEach(() => {- mocks.runReport.mockResolvedValue(reportResult);- mocks.getProjectForOrganization.mockResolvedValue({ id: "project_1" });- });-- it("registers strict public input schemas", async () => {- const { getGoogleAnalyticsOrganicLandingPagesTool } = tools;- expect(- getGoogleAnalyticsOrganicLandingPagesTool.config.inputSchema.safeParse({- projectId: "project_1",- unknown: true,- }).success,- ).toBe(false);- expect(- getGoogleAnalyticsOrganicLandingPagesTool.config.inputSchema.safeParse({- projectId: "project_1",- startDate: "2026-01-01",- }).success,- ).toBe(true);- });-- it("returns normalized landing-page report content", async () => {- const { getGoogleAnalyticsOrganicLandingPagesTool } = tools;- const result = await getGoogleAnalyticsOrganicLandingPagesTool.handler(- { projectId: "project_1", limit: 10, offset: 0 },- toolContext,+ mocks.runReport.mockResolvedValue(+ makeGa4ReportResult({+ rowCount: 1,+ totalRowCount: 1,+ rows: [{ hostName: "example.com", sessions: 5 }],+ }),);- expect(mocks.runReport).toHaveBeenCalledWith({- projectId: "project_1",- limit: 10,- offset: 0,- kind: "landing_pages",- channel: "organic_search",- });- expect(result.structuredContent).toMatchObject({- status: "ok",- rowCount: 1,- meta: { projectId: "project_1" },- });+ mocks.getProjectForOrganization.mockResolvedValue({ id: "project_1" });});- it("maps page-performance and key-event options to fixed reports", async () => {- const {- getGoogleAnalyticsKeyEventsTool,- getGoogleAnalyticsPagePerformanceTool,- } = tools;- await getGoogleAnalyticsPagePerformanceTool.handler(- {- projectId: "project_1",- includeDate: true,- channel: "all",- limit: 100,- offset: 0,- },- toolContext,- );- await getGoogleAnalyticsKeyEventsTool.handler(+ // Each tool maps its public input onto the shared report input: fixed+ // `kind`, forced channels, and the per-report breakdown key.+ it.each([+ [+ "landing_pages",+ () =>+ tools.getGoogleAnalyticsOrganicLandingPagesTool.handler(+ page,+ toolContext,+ ),+ { kind: "landing_pages", channel: "organic_search" },+ ],+ [+ "page_performance",+ () =>+ tools.getGoogleAnalyticsPagePerformanceTool.handler(+ { ...page, includeDate: true, channel: "all" },+ toolContext,+ ),+ { kind: "page_performance", includeDate: true, channel: "all" },+ ],+ [+ "key_events",+ () =>+ tools.getGoogleAnalyticsKeyEventsTool.handler(+ {+ ...page,+ breakdown: "event_and_landing_page",+ channel: "organic_search",+ comparePreviousPeriod: false,+ },+ toolContext,+ ),{- projectId: "project_1",- breakdown: "event_and_landing_page",- channel: "organic_search",- comparePreviousPeriod: false,- limit: 100,- offset: 0,- },- toolContext,- );- expect(mocks.runReport).toHaveBeenNthCalledWith(- 1,- expect.objectContaining({- kind: "page_performance",- includeDate: true,- channel: "all",- }),- );- expect(mocks.runReport).toHaveBeenNthCalledWith(- 2,- expect.objectContaining({kind: "key_events",breakdown: "event_and_landing_page",- }),- );- });-- it("returns stable connection errors without leaking upstream details", async () => {- mocks.runReport.mockRejectedValue(- new Ga4ReportError(- "ga4_reconnect_required",- "The Google Analytics connection has expired or was revoked.",- ),- );- const { getGoogleAnalyticsKeyEventsTool } = tools;- const result = await getGoogleAnalyticsKeyEventsTool.handler(- {- projectId: "project_1",- breakdown: "event",channel: "organic_search",comparePreviousPeriod: false,- limit: 100,- offset: 0,},- toolContext,- );- expect(result.structuredContent).toMatchObject({- status: "error",- error: {- code: "ga4_reconnect_required",- actionUrl: "https://open-seo.test/p/project_1/settings/integrations",- },- });- });-- it("returns the cross-source opportunity envelope", async () => {- mocks.getOpportunities.mockResolvedValue({- status: "ok",- rowCount: 1,- totalCandidateRows: 2,- rows: [{ page: "https://example.com/a", score: 90 }],- coverage: { matchedRows: 1 },- });- const { getSearchOpportunitiesTool } = tools;- const result = await getSearchOpportunitiesTool.handler(- { projectId: "project_1", limit: 25 },- toolContext,- );- expect(mocks.getOpportunities).toHaveBeenCalledWith({- projectId: "project_1",- limit: 25,- });- expect(result.structuredContent).toMatchObject({- status: "ok",- rowCount: 1,- totalCandidateRows: 2,- });- });-- it.each([+ ],["traffic_acquisition",() =>tools.getGoogleAnalyticsTrafficAcquisitionTool.handler(- {- projectId: "project_1",- breakdown: "campaign",- comparePreviousPeriod: false,- limit: 100,- offset: 0,- },+ { ...page, breakdown: "campaign", comparePreviousPeriod: false },toolContext,),+ {+ kind: "traffic_acquisition",+ channel: "all",+ acquisitionBreakdown: "campaign",+ comparePreviousPeriod: false,+ },],["ecommerce_performance",() =>tools.getGoogleAnalyticsEcommercePerformanceTool.handler({- projectId: "project_1",+ ...page,breakdown: "landing_page",channel: "organic_search",- onlyWithTransactions: false,- limit: 100,- offset: 0,+ onlyWithTransactions: true,},toolContext,),+ {+ kind: "ecommerce_performance",+ channel: "organic_search",+ ecommerceBreakdown: "landing_page",+ ecommerceOnlyWithTransactions: true,+ onlyWithTransactions: true,+ },],["site_search",- () =>- tools.getGoogleAnalyticsSiteSearchTool.handler(- { projectId: "project_1", limit: 100, offset: 0 },- toolContext,- ),+ () => tools.getGoogleAnalyticsSiteSearchTool.handler(page, toolContext),+ { kind: "site_search", channel: "all" },],["audience_breakdown",() =>tools.getGoogleAnalyticsAudienceBreakdownTool.handler({- projectId: "project_1",+ ...page,breakdown: "country",channel: "all",comparePreviousPeriod: false,- limit: 100,- offset: 0,},toolContext,),+ {+ kind: "audience_breakdown",+ channel: "all",+ audienceBreakdown: "country",+ comparePreviousPeriod: false,+ },],] as const)(- "maps a controlled breakdown to %s",- async (expectedKind, run) => {- await run();- expect(mocks.runReport).toHaveBeenCalledWith(- expect.objectContaining({ kind: expectedKind }),- );+ "maps the %s tool onto its fixed report input",+ async (_kind, run, input) => {+ const result = await run();++ expect(mocks.runReport).toHaveBeenCalledExactlyOnceWith({+ ...page,+ ...input,+ });+ expect(result.structuredContent).toMatchObject({+ status: "ok",+ rowCount: 1,+ meta: { projectId: "project_1" },+ });},);- it("returns organic overview and measurement-health envelopes", async () => {- mocks.getOrganicOverview.mockResolvedValue({- status: "ok",- request: {- resolvedDateRange: { startDate: "2026-07-09", endDate: "2026-08-05" },- previousDateRange: { startDate: "2026-06-11", endDate: "2026-07-08" },- },- comparison: {},- trend: [],- warnings: [],- });- mocks.getMeasurementHealth.mockResolvedValue({- status: "ok",- summary: { webStreamCount: 1, keyEventCount: 2, issueCount: 0 },- issues: [],- });- const {- getGoogleAnalyticsMeasurementHealthTool,- getGoogleAnalyticsOrganicOverviewTool,- } = tools;- const overview = await getGoogleAnalyticsOrganicOverviewTool.handler(- { projectId: "project_1", trend: "weekly" },- toolContext,+ it("returns stable connection errors without leaking upstream details", async () => {+ mocks.runReport.mockRejectedValue(+ new Ga4ReportError(+ "ga4_reconnect_required",+ "The Google Analytics connection has expired or was revoked.",+ ),);- const health = await getGoogleAnalyticsMeasurementHealthTool.handler(- { projectId: "project_1" },++ const result = await tools.getGoogleAnalyticsKeyEventsTool.handler(+ {+ ...page,+ breakdown: "event",+ channel: "organic_search",+ comparePreviousPeriod: false,+ },toolContext,);- expect(mocks.getOrganicOverview).toHaveBeenCalledWith({- projectId: "project_1",- trend: "weekly",- });- expect(mocks.getMeasurementHealth).toHaveBeenCalledWith("project_1");- expect(overview.structuredContent).toMatchObject({ status: "ok" });- expect(health.structuredContent).toMatchObject({ status: "ok" });- });-- it("rejects incomplete success and error envelopes", async () => {- const {- getGoogleAnalyticsMeasurementHealthTool,- getGoogleAnalyticsOrganicLandingPagesTool,- getGoogleAnalyticsOrganicOverviewTool,- getSearchOpportunitiesTool,- } = tools;- for (const tool of [- getGoogleAnalyticsOrganicLandingPagesTool,- getGoogleAnalyticsOrganicOverviewTool,- getGoogleAnalyticsMeasurementHealthTool,- getSearchOpportunitiesTool,- ]) {- expect(tool.config.outputSchema.safeParse({ status: "ok" }).success).toBe(- false,- );- expect(- tool.config.outputSchema.safeParse({ status: "error" }).success,- ).toBe(false);- expect(- tool.config.outputSchema.safeParse({- status: "error",- error: { code: "ga4_not_connected", message: "Connect GA4." },- additiveField: true,- }).success,- ).toBe(true);- }+ expect(result.structuredContent).toMatchObject({+ status: "error",+ error: {+ code: "ga4_reconnect_required",+ actionUrl: "https://open-seo.test/p/project_1/settings/integrations",+ },+ });});});diff --git a/src/server/mcp/tools/local-seo-tools.test.ts b/src/server/mcp/tools/local-seo-tools.test.tsindex 35fd6499..d66b4dda 100644--- a/src/server/mcp/tools/local-seo-tools.test.ts+++ b/src/server/mcp/tools/local-seo-tools.test.ts@@ -176,7 +176,7 @@ describe("get_business_reviews", () => {await expect(failing).rejects.toThrow('taskId "google:task-1"');});- it("resumes from a taskId without posting a new task", async () => {+ it("resumes from a taskId without posting a new task, rejecting taskIds from elsewhere", async () => {const reviewsTaskPost = vi.fn();mocks.createDataforseoClient.mockReturnValue({business: { reviewsTaskPost },@@ -217,9 +217,7 @@ describe("get_business_reviews", () => {expect(out).toContain("# | when | rating | author | source | review");expect(out).toContain("Rare bottles and great staff.");expect(out).toContain("| yes");- });- it("rejects a taskId that did not come from this tool", async () => {await expect(getBusinessReviewsTool.handler({ projectId: "project_1", taskId: "task-9" },@@ -444,17 +442,4 @@ describe("list_business_categories", () => {]);expect(textContent(result)).toContain("pizza_restaurant | 120");});-- it("serves a cache hit without calling the provider", async () => {- mocks.getCached.mockResolvedValue(categories);-- const result = await listBusinessCategoriesTool.handler(- { projectId: "project_1" },- toolContext,- );-- expect(mocks.fetchBusinessListingsCategories).not.toHaveBeenCalled();- expect(mocks.setCached).not.toHaveBeenCalled();- expect(result.structuredContent.categories).toEqual(categories);- });});diff --git a/src/server/mcp/tools/output-schema-validation.test.ts b/src/server/mcp/tools/output-schema-validation.test.tsindex bbd7fdf5..bf734d88 100644--- a/src/server/mcp/tools/output-schema-validation.test.ts+++ b/src/server/mcp/tools/output-schema-validation.test.ts@@ -1,18 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { Ajv } from "@modelcontextprotocol/client/validators/ajv";-import { z } from "zod";-import { AppError } from "@/server/lib/errors";import { objectSchema } from "@/server/mcp/output-schemas";import * as researchTools from "./dataforseo-research-tools";import * as localSeoTools from "./local-seo-tools";import { getBacklinksProfileTool } from "./get-backlinks-profile";-import { getRankTrackerTool } from "./get-rank-tracker";-import {- getProjectContextTool,- updateProjectContextTool,-} from "./project-context";import { getSearchConsolePerformanceTool } from "./search-console-tools";-import { runSiteAuditTool } from "./site-audit-tools";import { makeToolContext } from "./tool-test-support";const mocks = vi.hoisted(() => ({@@ -93,68 +84,43 @@ beforeEach(() => {});});+const providerRows = (field: string) => ({+ [field]: [new ProviderRow("example.com", 1)],+ totalCount: 1,+ // Required by the queued business-data tools; ignored by the rest.+ status: "completed",+ taskId: "google:task-1",+});+describe("DataForSEO research tool output schemas", () => {- // Every tool that streams provider rows straight to structuredContent.+ // Every tool that streams provider rows or objects straight to+ // structuredContent.it.each([- ["find_serp_competitors", "competitors"],- ["get_local_serp_results", "results"],- ["search_local_businesses", "businesses"],- ["get_google_business_questions", "questions"],- ["get_ranked_keywords", "keywords"],- ["get_business_reviews", "reviews"],- ["get_business_updates", "updates"],+ ["find_serp_competitors", providerRows("competitors")],+ ["get_local_serp_results", providerRows("results")],+ ["search_local_businesses", providerRows("businesses")],+ ["get_google_business_questions", providerRows("questions")],+ ["get_ranked_keywords", providerRows("keywords")],+ ["get_business_reviews", providerRows("reviews")],+ ["get_business_updates", providerRows("updates")],+ ["get_business_profile", { profile: new ProviderRow("example.com", 1) }],])("%s accepts typed (non-plain-object) provider rows",- async (toolName, field) => {+ async (toolName, payload) => {const tools = { ...researchTools, ...localSeoTools };const tool = Object.values(tools).find((t) => t.name === toolName);if (!tool) throw new Error(`tool ${toolName} not found`);- const schema = objectSchema(tool.config.outputSchema);-// Mirror the MCP server: validate structuredContent against the tool's// own output schema. Extra keys (e.g. get_ranked_keywords' totalCount)// are allowed by the passthrough schemas, so one payload covers all.- const result = await schema.safeParseAsync({- [field]: [new ProviderRow("example.com", 1)],- totalCount: 1,- // Required by the queued business-data tools; ignored by the rest.- status: "completed",- taskId: "google:task-1",- });+ const result = await objectSchema(+ tool.config.outputSchema,+ ).safeParseAsync(payload);expect(result.success).toBe(true);},);-- it("get_business_profile accepts a typed provider profile object", async () => {- const schema = objectSchema(- localSeoTools.getBusinessProfileTool.config.outputSchema,- );-- const result = await schema.safeParseAsync({- profile: new ProviderRow("example.com", 1),- });-- expect(result.success).toBe(true);- });-- it("get_backlinks_profile accepts a paginated backlinks profile payload", async () => {- const schema = objectSchema(getBacklinksProfileTool.config.outputSchema);-- const result = await schema.safeParseAsync({- target: "example.com",- scope: "domain",- backlinks: backlinkPage,- meta: {- organizationId: "org_123",- projectId: "project_123",- url: "https://app.example.com/p/project_123/backlinks",- },- });-- expect(result.success).toBe(true);- });});describe("MCP output schemas with expected missing fields", () => {@@ -171,80 +137,6 @@ describe("MCP output schemas with expected missing fields", () => {expect(result.success).toBe(true);});-- // Refusals (for example, audit capacity) never start an audit, so they- // have no id to report.- it("accepts a site-audit refusal without an audit id", async () => {- const schema = objectSchema(runSiteAuditTool.config.outputSchema);-- const result = await schema.safeParseAsync({- meta: {- organizationId: "org_123",- projectId: "project_123",- },- });-- expect(result.success).toBe(true);- });-});--describe("MCP output compatibility across deployments", () => {- // Clients cache the JSON Schema from tools/list. Zod's safeParse alone- // misses this regression: it strips unknown fields, while its exported- // output schema rejects them unless the object allows additional fields.- const validator = new Ajv({ strict: false });-- it.each([getProjectContextTool, updateProjectContextTool])(- "$name accepts new context fields while validating known fields",- (tool) => {- const validate = validator.compile(- z.toJSONSchema(objectSchema(tool.config.outputSchema), {- target: "draft-7",- }),- );- const context = {- sections: [],- missingSections: [],- customSections: [],- competitors: [],- keyPages: [],- researchLog: [],- reportTemplates: [],- futureContextField: [],- };-- expect(validate(context)).toBe(true);- expect(validate({ ...context, sections: "invalid" })).toBe(false);- const { sections: _sections, ...missingSections } = context;- expect(validate(missingSections)).toBe(false);- },- );-- it("get_rank_tracker accepts new run fields while validating known fields", () => {- const validate = validator.compile(- z.toJSONSchema(getRankTrackerTool.config.outputSchema, {- target: "draft-7",- }),- );- const run = {- id: "run_1",- lastCheckedAt: null,- completedAt: "2026-09-17T00:00:00.000Z",- status: "completed",- errorMessage: null,- futureRunField: 1,- };- const detail = { config: {}, results: { rows: [], run } };-- expect(validate(detail)).toBe(true);- expect(validate({ configs: [] })).toBe(true);- expect(validate({ results: { rows: [], run: null } })).toBe(true);- expect(- validate({ results: { rows: [], run: { ...run, status: "invalid" } } }),- ).toBe(false);- const { completedAt: _completedAt, ...incompleteRun } = run;- expect(validate({ results: { rows: [], run: incompleteRun } })).toBe(false);- });});describe("get_backlinks_profile MCP tool", () => {@@ -298,67 +190,4 @@ describe("get_backlinks_profile MCP tool", () => {const first = result.content[0];expect(first.type === "text" && first.text).toContain("- has more: yes");});-- it("passes through final-page pagination state", async () => {- const finalPage = {- ...backlinkPage,- totalCount: 51,- hasMore: false,- page: 2,- };- mocks.profileBacklinksPage.mockResolvedValue(finalPage);-- const result = await getBacklinksProfileTool.handler(- {- projectId: "project_123",- target: "example.com",- scope: "domain",- page: 2,- pageSize: 50,- sortField: "rank",- sortOrder: "desc",- filters: {},- mode: "one_per_domain",- hideSpam: true,- },- toolContext,- );-- expect(result.structuredContent?.backlinks).toMatchObject({- totalCount: 51,- hasMore: false,- page: 2,- pageSize: 50,- });- });-- it("preserves Backlinks API access and credit errors", async () => {- const error = new AppError(- "BACKLINKS_BILLING_ISSUE",- "The connected DataForSEO account has a billing or balance issue",- );- mocks.profileBacklinksPage.mockRejectedValue(error);-- await expect(- getBacklinksProfileTool.handler(- {- projectId: "project_123",- target: "example.com",- scope: "domain",- page: 1,- pageSize: 100,- sortField: "rank",- sortOrder: "desc",- filters: {},- mode: "one_per_domain",- hideSpam: true,- },- toolContext,- ),- ).rejects.toMatchObject({- code: "BACKLINKS_BILLING_ISSUE",- message:- "The connected DataForSEO account has a billing or balance issue",- });- });});diff --git a/src/server/mcp/tools/project-context.test.ts b/src/server/mcp/tools/project-context.test.tsindex 7bd93a82..e08de74c 100644--- a/src/server/mcp/tools/project-context.test.ts+++ b/src/server/mcp/tools/project-context.test.ts@@ -17,8 +17,6 @@ const mocks = vi.hoisted(() => ({listResearchLog: vi.fn(),listTemplates: vi.fn(),deleteSection: vi.fn(),- deleteCompetitors: vi.fn(),- deleteKeyPages: vi.fn(),deleteResearchLogEntries: vi.fn(),}));@@ -55,40 +53,24 @@ beforeEach(() => {});describe("update_project_context", () => {- it("removes each kind of context entry within the authorized project", async () => {+ // Custom sections share the sections table with typed ones under a prefixed+ // key; a delete that misses the prefix silently leaves the section behind.+ it("deletes custom sections by their prefixed key and research log entries by id", async () => {await updateProjectContextTool.handler({projectId: "project_1",updates: [- { section: "current_goal", content: "" },{ deleteCustomSection: "old-findings" },- { removeCompetitors: ["https://www.Example.com/"] },- { removeKeyPages: ["https://Example.com/pricing#old"] },{ removeResearchLog: ["research_1"] },],},makeToolContext(),);- expect(mocks.deleteSection).toHaveBeenCalledWith(- expect.anything(),- "project_1",- "current_goal",- );expect(mocks.deleteSection).toHaveBeenCalledWith(expect.anything(),"project_1","custom:old-findings",);- expect(mocks.deleteCompetitors).toHaveBeenCalledWith(- expect.anything(),- "project_1",- ["example.com"],- );- expect(mocks.deleteKeyPages).toHaveBeenCalledWith(- expect.anything(),- "project_1",- ["https://example.com/pricing"],- );expect(mocks.deleteResearchLogEntries).toHaveBeenCalledWith(expect.anything(),"project_1",@@ -140,15 +122,8 @@ describe("get_project_context", () => {it("lists the project's report templates", async () => {mocks.listTemplates.mockResolvedValue([{- id: "template_1",- projectId: "project_1",name: "Monthly client check-in",description: "The monthly update we send retainer clients.",- instructions: "Audience: the client's marketing lead.",- createdBy: "OpenSEO app",- createdByUserId: "user_1",- createdAt: "2026-09-01T10:00:00.000Z",- updatedAt: "2026-09-01T10:00:00.000Z",},]);diff --git a/src/server/mcp/tools/rank-tracking-management-tools.test.ts b/src/server/mcp/tools/rank-tracking-management-tools.test.tsindex bfbc1b5b..ca28c019 100644--- a/src/server/mcp/tools/rank-tracking-management-tools.test.ts+++ b/src/server/mcp/tools/rank-tracking-management-tools.test.ts@@ -2,8 +2,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { z } from "zod";import { addRankTrackingKeywordsTool } from "./add-rank-tracking-keywords";import { createRankTrackerTool } from "./create-rank-tracker";-import { estimateRankTrackerCostTool } from "./estimate-rank-tracker-cost";-import { removeRankTrackingKeywordsTool } from "./remove-rank-tracking-keywords";import { runRankTrackerTool } from "./run-rank-tracker";import { makeToolContext, textContent } from "./tool-test-support";@@ -12,11 +10,9 @@ const mocks = vi.hoisted(() => ({createConfig: vi.fn(),getTracker: vi.fn(),addKeywords: vi.fn(),- removeKeywords: vi.fn(),- estimateCost: vi.fn(),triggerCheck: vi.fn(),captureServerEvent: vi.fn(),- waitUntil: vi.fn((promise: Promise<unknown>) => void promise.catch(() => {})),+ waitUntil: vi.fn(),}));vi.mock("cloudflare:workers", () => ({@@ -33,8 +29,6 @@ vi.mock("@/server/features/rank-tracking/services/RankTrackingService", () => ({createConfig: mocks.createConfig,getTracker: mocks.getTracker,addKeywords: mocks.addKeywords,- removeKeywords: mocks.removeKeywords,- estimateCost: mocks.estimateCost,triggerCheck: mocks.triggerCheck,},}));@@ -50,15 +44,9 @@ const toolContext = makeToolContext();const createdConfig = {id: trackerId,- projectId,domain: "openseo.so",- locationCode: 2840,- languageCode: "en",- locationName: null,- devices: "mobile" as const,- serpDepth: 40,- scheduleInterval: "manual" as const,- isActive: true,+ devices: "mobile",+ scheduleInterval: "manual",};describe("rank tracking management MCP tools", () => {@@ -80,28 +68,19 @@ describe("rank tracking management MCP tools", () => {});const result = await createRankTrackerTool.handler(parsed, toolContext);- expect(mocks.createConfig).toHaveBeenCalledWith({- projectId,- projectMarket: {- id: projectId,+ expect(mocks.createConfig).toHaveBeenCalledWith(+ expect.objectContaining({domain: "openseo.so",- locationCode: 2840,- languageCode: "en",- },- domain: "openseo.so",- locationCode: undefined,- languageCode: undefined,- locationName: undefined,- devices: "mobile",- serpDepth: 40,- scheduleInterval: "manual",- });+ devices: "mobile",+ serpDepth: 40,+ scheduleInterval: "manual",+ }),+ );expect(textContent(result)).toContain("no check was started");expect(result.structuredContent).toMatchObject({trackerId,config: createdConfig,});- expect(mocks.getTracker).not.toHaveBeenCalled();expect(mocks.captureServerEvent).toHaveBeenCalledWith({distinctId: "user_123",event: "rank_tracking:config_create",@@ -114,25 +93,6 @@ describe("rank tracking management MCP tools", () => {source: "mcp",},});- expect(- createRankTrackerTool.config.outputSchema.safeParse(- result.structuredContent,- ).success,- ).toBe(true);- });-- it("rejects tracker creation when neither the call nor project has a domain", async () => {- mocks.getProjectForOrganization.mockResolvedValue({- id: projectId,- domain: null,- locationCode: 2840,- languageCode: "en",- });-- await expect(- createRankTrackerTool.handler({ projectId }, toolContext),- ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });- expect(mocks.createConfig).not.toHaveBeenCalled();});it("requires maxCostCredits to run a rank tracker", () => {@@ -144,12 +104,8 @@ describe("rank tracking management MCP tools", () => {).toBe(false);});- it("reports database-confirmed add and removal counts in text and structured output", async () => {+ it("adds keywords under the credit-ceiling approval and reports the confirmed count", async () => {mocks.addKeywords.mockResolvedValue({ added: 1, addedIds: [keywordId] });- mocks.removeKeywords.mockResolvedValue({- removed: 1,- removedIds: [keywordId],- });const added = await addRankTrackingKeywordsTool.handler({@@ -172,68 +128,16 @@ describe("rank tracking management MCP tools", () => {},true,);-- const removed = await removeRankTrackingKeywordsTool.handler(- { projectId, trackerId, keywordIds: [keywordId, keywordId] },- toolContext,- );- expect(textContent(removed)).toContain("Removed 1 of 2 requested");- expect(removed.structuredContent).toMatchObject({- requested: 2,- removed: 1,- removedIds: [keywordId],- });- });-- it("returns the shared live cost estimate without starting a check", async () => {- mocks.estimateCost.mockResolvedValue({- costUsd: 0.0128,- costCredits: 13,- keywordCount: 8,- devicesCount: 2,- totalChecks: 16,- method: "live",- existingKeywordCount: 5,- additionalKeywordCount: 3,- scheduledEstimate: {- scheduleInterval: "weekly",- costUsd: 0.0046,- costCredits: 5,- checksPerMonth: 4,- monthlyCostUsd: 0.0184,- monthlyCostCredits: 20,- },- });- const result = await estimateRankTrackerCostTool.handler(- { projectId, trackerId, additionalKeywordCount: 3 },- toolContext,- );-- expect(textContent(result)).toContain(- "8 keywords × 2 devices = 16 SERP checks",- );- expect(textContent(result)).toContain(- "additional separately billed live fallback",- );- expect(result.structuredContent).toMatchObject({- costCredits: 13,- method: "live",- });- expect(mocks.estimateCost).toHaveBeenCalledWith(trackerId, projectId, 3);- expect(mocks.triggerCheck).not.toHaveBeenCalled();});- it("returns the created run ID and emits the existing telemetry contract", async () => {- mocks.triggerCheck.mockResolvedValue({- ok: true,- runId: "run_1",- });- const result = await runRankTrackerTool.handler(+ it("returns the created run ID and emits the telemetry contract, but not for an already-running tracker", async () => {+ mocks.triggerCheck.mockResolvedValue({ ok: true, runId: "run_1" });+ const started = await runRankTrackerTool.handler({ projectId, trackerId, maxCostCredits: 13 },toolContext,);- expect(result.structuredContent).toMatchObject({+ expect(started.structuredContent).toMatchObject({started: true,runId: "run_1",});@@ -252,41 +156,22 @@ describe("rank tracking management MCP tools", () => {},});expect(mocks.waitUntil).toHaveBeenCalledTimes(1);- });- it("does not emit telemetry or imply another charge for an active run", async () => {mocks.triggerCheck.mockResolvedValue({ok: false,reason: "already_running",blockingRunId: "run_0",});- const result = await runRankTrackerTool.handler(+ const blocked = await runRankTrackerTool.handler({ projectId, trackerId, maxCostCredits: 13 },toolContext,);- expect(textContent(result)).toContain("no additional check was charged");- expect(result.structuredContent).toMatchObject({+ expect(textContent(blocked)).toContain("no additional check was charged");+ expect(blocked.structuredContent).toMatchObject({started: false,blockingRunId: "run_0",});- expect(mocks.captureServerEvent).not.toHaveBeenCalled();- });-- it("returns a started run even when deferred telemetry rejects", async () => {- mocks.triggerCheck.mockResolvedValue({- ok: true,- runId: "run_1",- });- mocks.captureServerEvent.mockRejectedValue(new Error("telemetry down"));-- await expect(- runRankTrackerTool.handler(- { projectId, trackerId, maxCostCredits: 13 },- toolContext,- ),- ).resolves.toMatchObject({- structuredContent: { started: true, runId: "run_1" },- });+ expect(mocks.captureServerEvent).toHaveBeenCalledTimes(1);});});diff --git a/src/server/mcp/tools/report-tools.test.ts b/src/server/mcp/tools/report-tools.test.tsindex 81aa8e78..6c4f3f46 100644--- a/src/server/mcp/tools/report-tools.test.ts+++ b/src/server/mcp/tools/report-tools.test.ts@@ -1,5 +1,4 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { z } from "zod";import { AppError } from "@/server/lib/errors";import {REPORT_MAX_PER_PROJECT,@@ -131,27 +130,6 @@ describe("save_report", () => {);});- it("replaces the existing report when a reportId is passed, keeping its attribution", async () => {- mocks.getReport.mockResolvedValue(storedReport());-- const result = await saveReportTool.handler(- {- projectId,- reportId,- title: "badseo.dev SEO audit, Sep 2026",- summary: "Verdict: titles are still the problem.",- html,- },- toolContext,- );-- expect(mocks.insertReport).not.toHaveBeenCalled();- expect(mocks.updateReportContent).toHaveBeenCalledWith(- expect.objectContaining({ reportId, projectId }),- );- expect(result.structuredContent.created).toBe(false);- });-it("refuses a templateId that does not resolve in this project", async () => {// The template lookup is project-scoped, so another project's template// reads exactly like a deleted one.@@ -169,26 +147,6 @@ describe("save_report", () => {).rejects.toThrow(/No report template template_other_project/);expect(mocks.insertReport).not.toHaveBeenCalled();});-- it("passes a service refusal through with its message", async () => {- mocks.findReportByTitle.mockResolvedValue({- id: reportId,- title: "badseo.dev SEO audit, Sep 2026",- });-- await expect(- saveReportTool.handler(- {- projectId,- title: "badseo.dev SEO audit, Sep 2026",- summary: "Verdict.",- html,- },- toolContext,- ),- ).rejects.toThrow(/Pass reportId to update it/);- expect(mocks.insertReport).not.toHaveBeenCalled();- });});describe("list_reports", () => {@@ -242,20 +200,7 @@ describe("get_report", () => {});describe("public report sharing", () => {- it("requires an explicit boolean and advertises sharing as a mutation", () => {- const schema = z.object(setReportSharingTool.config.inputSchema);- for (const value of [undefined, null, "true", 1]) {- expect(- schema.safeParse({ projectId, reportId, public: value }).success,- ).toBe(false);- }- expect(setReportSharingTool.config.annotations).toMatchObject({- readOnlyHint: false,- destructiveHint: true,- });- });-- it("publishes, retrieves, preserves on save, revokes, and re-enables with a new URL", async () => {+ it("publishes, retrieves, preserves on save, and revokes", async () => {let stored = storedReport();mocks.getReport.mockImplementation(async () => stored);mocks.getReportWithHtml.mockImplementation(async () => ({@@ -283,11 +228,6 @@ describe("public report sharing", () => {expect(shareUrl).toMatch(/^https:\/\/open-seo\.test\/s\/[A-Za-z0-9_-]{32}$/,);- expect(- setReportSharingTool.config.outputSchema.safeParse(- published.structuredContent,- ).success,- ).toBe(true);expect(textContent(published)).toContain(shareUrl!);expect(mocks.captureServerEvent).toHaveBeenCalledWith(expect.objectContaining({@@ -302,8 +242,6 @@ describe("public report sharing", () => {},}),);- expect((await setSharing(true)).structuredContent.shareUrl).toBe(shareUrl);- expect(mocks.setShareToken).toHaveBeenCalledTimes(1);for (const includeHtml of [false, true]) {const fetched = await getReportTool.handler(@@ -313,10 +251,6 @@ describe("public report sharing", () => {expect(fetched.structuredContent.report.shareUrl).toBe(shareUrl);expect(fetched.structuredContent.report).not.toHaveProperty("shareToken");expect(textContent(fetched)).toContain(shareUrl!);- expect(- getReportTool.config.outputSchema.safeParse(fetched.structuredContent)- .success,- ).toBe(true);}await saveReportTool.handler({@@ -358,11 +292,6 @@ describe("public report sharing", () => {(await getReportTool.handler({ projectId, reportId }, toolContext)).structuredContent.report.shareUrl,).toBeNull();- await setSharing(false);- expect(mocks.setShareToken).toHaveBeenCalledTimes(2);- expect((await setSharing(true)).structuredContent.shareUrl).not.toBe(- shareUrl,- );});it("does not expose public links in bulk lists or mint links on reads", async () => {@@ -375,18 +304,11 @@ describe("public report sharing", () => {expect(mocks.setShareToken).not.toHaveBeenCalled();});- it("refuses publication on self-hosted deployments and hides unusable URLs, but permits revocation", async () => {+ it("hides unusable share URLs on self-hosted deployments but permits revocation", async () => {mocks.isHostedServerAuthMode.mockResolvedValue(false);mocks.getReport.mockResolvedValue(storedReport({ shareToken: "a".repeat(32) }),);- await expect(- setReportSharingTool.handler(- { projectId, reportId, public: true },- toolContext,- ),- ).rejects.toThrow("Sharing is only available on hosted OpenSEO.");- expect(mocks.setShareToken).not.toHaveBeenCalled();const fetched = await getReportTool.handler({ projectId, reportId },toolContext,@@ -399,35 +321,31 @@ describe("public report sharing", () => {expect(mocks.setShareToken).toHaveBeenCalledWith(projectId, reportId, null);});- it.each([true, false])(- "authorizes the project before changing sharing to %s",- async (isPublic) => {- mocks.getProjectForOrganization.mockRejectedValueOnce(- new AppError("FORBIDDEN"),- );- await expect(- setReportSharingTool.handler(- { projectId, reportId, public: isPublic },- toolContext,- ),- ).rejects.toThrow();- expect(mocks.getReport).not.toHaveBeenCalled();- expect(mocks.setShareToken).not.toHaveBeenCalled();- },- );+ it("authorizes the project before changing sharing", async () => {+ mocks.getProjectForOrganization.mockRejectedValueOnce(+ new AppError("FORBIDDEN"),+ );+ await expect(+ setReportSharingTool.handler(+ { projectId, reportId, public: true },+ toolContext,+ ),+ ).rejects.toThrow();+ expect(mocks.getReport).not.toHaveBeenCalled();+ expect(mocks.setShareToken).not.toHaveBeenCalled();+ });- it.each([true, false])(- "refuses missing or foreign report ids when changing sharing to %s",- async (isPublic) => {- mocks.getReport.mockResolvedValue(null);- await expect(- setReportSharingTool.handler(- { projectId, reportId: "foreign_report", public: isPublic },- toolContext,- ),- ).rejects.toThrow("No report foreign_report in this project.");- expect(mocks.getReport).toHaveBeenCalledWith(projectId, "foreign_report");- expect(mocks.setShareToken).not.toHaveBeenCalled();- },- );+ // Restored: ReportService.test no longer owns the unknown-id refusal on the+ // read path that share/unshare go through.+ it("refuses missing or foreign report ids when changing sharing", async () => {+ mocks.getReport.mockResolvedValue(null);+ await expect(+ setReportSharingTool.handler(+ { projectId, reportId: "foreign_report", public: true },+ toolContext,+ ),+ ).rejects.toThrow("No report foreign_report in this project.");+ expect(mocks.getReport).toHaveBeenCalledWith(projectId, "foreign_report");+ expect(mocks.setShareToken).not.toHaveBeenCalled();+ });});diff --git a/src/server/mcp/tools/saved-keywords-tools.test.ts b/src/server/mcp/tools/saved-keywords-tools.test.tsindex 28459695..9e90af1a 100644--- a/src/server/mcp/tools/saved-keywords-tools.test.ts+++ b/src/server/mcp/tools/saved-keywords-tools.test.ts@@ -1,8 +1,7 @@-import { z } from "zod";import { beforeEach, describe, expect, it, vi } from "vitest";import { listSavedKeywordsTool } from "./list-saved-keywords";import { saveKeywordsTool } from "./save-keywords";-import { makeToolContext } from "./tool-test-support";+import { makeToolContext, textContent } from "./tool-test-support";const mocks = vi.hoisted(() => ({getProjectForOrganization: vi.fn(),@@ -40,37 +39,9 @@ describe("saved keyword MCP tools", () => {});});- it("passes tags through save_keywords", async () => {- mocks.saveKeywords.mockResolvedValue({- success: true,- savedKeywordIds: ["saved_1"],- });-- const result = await saveKeywordsTool.handler(- {- projectId: "project_1",- keywords: ["technical seo"],- tags: ["Content"],- },- toolContext,- );-- expect(mocks.saveKeywords).toHaveBeenCalledWith({- projectId: "project_1",- keywords: ["technical seo"],- tags: ["Content"],- tagMode: "append",- locationCode: 2840,- languageCode: "en",- });- expect(result.structuredContent).toMatchObject({- savedCount: 1,- tags: ["Content"],- tagMode: "append",- });- });-- it("accepts and passes keyword metrics through save_keywords", async () => {+ // Appending is the default: a replace default would silently wipe the+ // user's existing tags on every save.+ it("passes tags and metrics through save_keywords, appending tags by default", async () => {mocks.saveKeywords.mockResolvedValue({success: true,savedKeywordIds: ["saved_1"],@@ -83,58 +54,33 @@ describe("saved keyword MCP tools", () => {cpc: 2.5,competition: 0.42,intent: "commercial" as const,- monthlySearches: [- { year: 2026, month: 7, searchVolume: 110 },- { year: 2026, month: 8, searchVolume: 120 },- ],+ monthlySearches: [{ year: 2026, month: 8, searchVolume: 120 }],},];- const args = z.object(saveKeywordsTool.config.inputSchema).parse({- projectId: "project_1",- keywords: ["technical seo"],- metrics,- });-- await saveKeywordsTool.handler(args, toolContext);-- expect(mocks.saveKeywords).toHaveBeenCalledWith({- projectId: "project_1",- keywords: ["technical seo"],- metrics,- tagMode: "append",- locationCode: 2840,- languageCode: "en",- });- });-- it("replaces tags through save_keywords when requested", async () => {- mocks.saveKeywords.mockResolvedValue({- success: true,- savedKeywordIds: ["saved_1", "saved_2"],- });const result = await saveKeywordsTool.handler({projectId: "project_1",- keywords: ["semrush alternative", "semrush pricing"],- tags: ["cluster: affordable semrush alternatives"],- tagMode: "replace",+ keywords: ["technical seo"],+ tags: ["Content"],+ metrics,},toolContext,);expect(mocks.saveKeywords).toHaveBeenCalledWith({projectId: "project_1",- keywords: ["semrush alternative", "semrush pricing"],- tags: ["cluster: affordable semrush alternatives"],- tagMode: "replace",+ keywords: ["technical seo"],+ tags: ["Content"],+ metrics,+ tagMode: "append",locationCode: 2840,languageCode: "en",});expect(result.structuredContent).toMatchObject({- savedCount: 2,- tags: ["cluster: affordable semrush alternatives"],- tagMode: "replace",+ savedCount: 1,+ tags: ["Content"],+ tagMode: "append",});});@@ -199,14 +145,8 @@ describe("saved keyword MCP tools", () => {rows: [{ keyword: "technical seo", tags: ["Content"] }],tags: [{ name: "Content", keywordCount: 1 }],});+ // remove_saved_keywords takes these ids, so both channels must carry them.expect(result.structuredContent?.rows?.[0]).toHaveProperty("id", "saved_1");- const [content] = result.content;- expect(content).toMatchObject({ type: "text" });- expect(content?.type === "text" ? content.text : "").toContain(- "id:saved_1",- );- expect(content?.type === "text" ? content.text : "").toContain(- "tags:Content",- );+ expect(textContent(result)).toContain("id:saved_1");});});diff --git a/src/server/mcp/tools/search-console-tools.test.ts b/src/server/mcp/tools/search-console-tools.test.tsindex 8880261d..98dabb2e 100644--- a/src/server/mcp/tools/search-console-tools.test.ts+++ b/src/server/mcp/tools/search-console-tools.test.ts@@ -244,75 +244,6 @@ describe("search console MCP tools", () => {expect(mocks.GscService.getPerformance).not.toHaveBeenCalled();});- it("allows performance queries in self-hosted mode with a Google client", async () => {- mocks.hasGoogleOAuthConfig.mockResolvedValue(true);- mocks.GscService.getPerformance.mockResolvedValue({- siteUrl: "https://example.com/",- connectedBy: "[email protected]",- request: {- dimensions: ["query"],- startDate: "2026-04-27",- endDate: "2026-05-25",- rowLimit: 1000,- },- rows: [],- });- const { getSearchConsolePerformanceTool } = searchConsoleTools;-- const result = await getSearchConsolePerformanceTool.handler(- { projectId: "project_1" },- toolContext,- );-- expect(mocks.GscService.getPerformance).toHaveBeenCalledWith(- expect.objectContaining({ projectId: "project_1" }),- );- expect(result.structuredContent).toMatchObject({ ok: true });- });-- it("inspects multiple URLs and reports partial failures inline", async () => {- mocks.GscService.inspectUrls.mockResolvedValue({- siteUrl: "sc-domain:example.com",- connectedBy: "[email protected]",- results: [- {- url: "https://example.com/a",- result: {- indexStatusResult: { verdict: "PASS", coverageState: "Indexed" },- },- },- {- url: "https://example.com/bad",- result: null,- error: "Search Console API error (400)",- },- ],- });- const { inspectUrlsTool } = searchConsoleTools;-- const result = await inspectUrlsTool.handler(- {- projectId: "project_1",- urls: ["https://example.com/a", "https://example.com/bad"],- },- toolContext,- );-- expect(mocks.GscService.inspectUrls).toHaveBeenCalledWith(- expect.objectContaining({- projectId: "project_1",- urls: ["https://example.com/a", "https://example.com/bad"],- }),- );- expect(result.structuredContent).toMatchObject({- ok: true,- siteUrl: "sc-domain:example.com",- });- const first = result.content[0];- expect(first.type === "text" && first.text).toContain("PASS");- expect(first.type === "text" && first.text).toContain("error:");- });-it("surfaces a not-connected message from inspect_urls", async () => {mocks.GscService.inspectUrls.mockRejectedValue(new GscNotConnectedError("project_1"),diff --git a/src/server/mcp/tools/tool-text-output.test.ts b/src/server/mcp/tools/tool-text-output.test.tsindex 06890f56..60ffbcf0 100644--- a/src/server/mcp/tools/tool-text-output.test.ts+++ b/src/server/mcp/tools/tool-text-output.test.ts@@ -2,7 +2,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";import * as researchTools from "./dataforseo-research-tools";import { getBacklinksOverviewTool } from "./get-backlinks-overview";-import { getBacklinksProfileTool } from "./get-backlinks-profile";import { getDomainKeywordSuggestionsTool } from "./get-domain-keyword-suggestions";import {getGoogleAnalyticsOrganicLandingPagesTool,@@ -13,7 +12,6 @@ import {import { getRankTrackerTool } from "./get-rank-tracker";import { getBusinessUpdatesTool } from "./local-seo-tools";import { getSerpResultsTool } from "./get-serp-results";-import { researchKeywordsTool } from "./research-keywords";import { makeToolContext, textContent } from "./tool-test-support";import { makeGa4ReportResult } from "@/server/features/ga4/services/ga4-test-fixtures";import type * as backlinksTargetModule from "@/server/lib/dataforseoBacklinksTarget";@@ -27,14 +25,9 @@ const mocks = vi.hoisted(() => ({getProjectForOrganization: vi.fn(),createDataforseoClient: vi.fn(),fetchBusinessDataTaskResult: vi.fn(),- research: vi.fn(),profileOverview: vi.fn(),profileReferringDomainsPage: vi.fn(),- profileBacklinksPage: vi.fn(),getSuggestedKeywords: vi.fn(),- getConfigById: vi.fn(),- getConfigsForProject: vi.fn(),- getLatestResults: vi.fn(),getTracker: vi.fn(),getConfigs: vi.fn(),runGa4Report: vi.fn(),@@ -60,31 +53,15 @@ vi.mock("@/server/features/projects/services/ProjectService", () => ({getProjectForOrganization: mocks.getProjectForOrganization,},}));-vi.mock("@/server/features/keywords/services/KeywordResearchService", () => ({- KeywordResearchService: { research: mocks.research },-}));vi.mock("@/server/features/backlinks/services/BacklinksService", () => ({BacklinksService: {profileOverview: mocks.profileOverview,profileReferringDomainsPage: mocks.profileReferringDomainsPage,- profileBacklinksPage: mocks.profileBacklinksPage,},}));vi.mock("@/server/features/domain/services/DomainService", () => ({DomainService: { getSuggestedKeywords: mocks.getSuggestedKeywords },}));-vi.mock(- "@/server/features/rank-tracking/repositories/RankTrackingRepository",- () => ({- RankTrackingRepository: {- getConfigById: mocks.getConfigById,- getConfigsForProject: mocks.getConfigsForProject,- },- }),-);-vi.mock("@/server/features/rank-tracking/services/rankTrackingResults", () => ({- getLatestResults: mocks.getLatestResults,-}));vi.mock("@/server/features/rank-tracking/services/RankTrackingService", () => ({RankTrackingService: {getTracker: mocks.getTracker,@@ -111,44 +88,6 @@ describe("MCP tool text output (service-backed tools)", () => {});});- it("research_keywords renders every keyword row in the text table", async () => {- mocks.research.mockResolvedValue({- rows: [- {- keyword: "seo tools",- searchVolume: 2400,- keywordDifficulty: 18,- cpc: 3.25,- competition: 0.4,- intent: "commercial",- trend: [],- },- {- keyword: "free seo tools",- searchVolume: 880,- keywordDifficulty: null,- cpc: null,- competition: null,- intent: "informational",- trend: [],- },- ],- source: "related",- usedFallback: false,- });-- const result = await researchKeywordsTool.handler(- { projectId: "project_1", seeds: [{ seed: "seo tools" }] },- toolContext,- );-- const out = textContent(result);- expect(out).toContain("keyword | volume | KD | CPC | competition | intent");- expect(out).toContain("seo tools | 2400 | 18 | 3.25 | 0.40 | commercial");- // Second row proves it isn't truncated and nulls render as em dashes.- expect(out).toContain("free seo tools | 880 | — | — | — | informational");- });-it("get_domain_keyword_suggestions renders keyword rows", async () => {mocks.getSuggestedKeywords.mockResolvedValue([{@@ -199,51 +138,6 @@ describe("MCP tool text output (service-backed tools)", () => {expect(out).toContain("linker.example | 42 | 5 | 30");});- it("get_backlinks_profile renders all backlink rows", async () => {- mocks.profileBacklinksPage.mockResolvedValue({- rows: [- {- urlFrom: "https://a.example/post",- domainFrom: "a.example",- urlTo: "https://target.example",- anchor: "click here",- isDofollow: true,- rank: 12,- domainFromRank: 40,- spamScore: 3,- isLost: false,- isBroken: false,- },- ],- page: 1,- pageSize: 100,- totalCount: 1,- hasMore: false,- });-- const result = await getBacklinksProfileTool.handler(- {- projectId: "project_1",- target: "example.com",- page: 1,- pageSize: 100,- sortField: "rank",- sortOrder: "desc",- filters: {},- mode: "one_per_domain",- },- toolContext,- );-- const out = textContent(result);- expect(out).toContain(- "source | target | anchor | type | rank | domainRank | spam | status",- );- expect(out).toContain("https://a.example/post");- expect(out).toContain("click here");- expect(out).toContain("dofollow");- });-it("get_rank_tracker renders every tracked-keyword row (detail view)", async () => {mocks.getTracker.mockResolvedValue({config: {@@ -314,10 +208,6 @@ describe("MCP tool text output (service-backed tools)", () => {},},});- expect(- getRankTrackerTool.config.outputSchema.safeParse(result.structuredContent)- .success,- ).toBe(true);});it("get_ranked_keywords renders nested provider rows as a text table", async () => {@@ -383,31 +273,6 @@ describe("MCP tool text output (service-backed tools)", () => {);});- it("get_serp_results renders each query's items as a text table", async () => {- const live = vi.fn().mockResolvedValue([- {- type: "organic",- rank_absolute: 1,- title: "Best SEO Tools",- url: "https://example.com/best",- domain: "example.com",- description: "desc",- },- ]);- mocks.createDataforseoClient.mockReturnValue({ serp: { live } });-- const result = await getSerpResultsTool.handler(- { projectId: "project_1", queries: [{ keyword: "seo tools" }] },- toolContext,- );-- const out = textContent(result);- expect(out).toContain("rank | domain | title | url");- expect(out).toContain(- "1 | example.com | Best SEO Tools | https://example.com/best",- );- });-it("get_serp_results crawls and returns rows to the requested depth", async () => {const live = vi.fn().mockResolvedValue(Array.from({ length: 40 }, (_, index) => ({@@ -435,47 +300,6 @@ describe("MCP tool text output (service-backed tools)", () => {expect(textContent(result)).toContain('"seo tools" (30 results)');});- it("get_google_analytics_organic_landing_pages renders report rows in the text table", async () => {- mocks.runGa4Report.mockResolvedValue(- makeGa4ReportResult({- rowCount: 2,- totalRowCount: 2,- rows: [- {- hostName: "example.com",- landingPage: "/home",- sessions: 12,- activeUsers: 9,- },- {- hostName: "example.com",- landingPage: "/blog",- sessions: 4,- activeUsers: 3,- },- ],- request: {- dimensions: ["hostName", "landingPage"],- metrics: ["sessions", "activeUsers"],- },- }),- );-- const result = await getGoogleAnalyticsOrganicLandingPagesTool.handler(- { projectId: "project_1", limit: 100, offset: 0 },- toolContext,- );-- expect(textContent(result)).toEqual(- [- "Organic landing pages: 2 of 2 rows for 2026-07-09 through 2026-08-05.",- "hostName | landingPage | sessions | activeUsers",- "example.com | /home | 12 | 9",- "example.com | /blog | 4 | 3",- ].join("\n"),- );- });-it("get_google_analytics_organic_landing_pages renders every fetched row and points at offset paging", async () => {const rows = Array.from({ length: 16 }, (_, index) => ({hostName: "example.com",@@ -512,8 +336,23 @@ describe("MCP tool text output (service-backed tools)", () => {expect(result.structuredContent).toMatchObject({ rows });});- it("get_google_analytics_page_performance names the Organic Search filter when empty", async () => {- mocks.runGa4Report.mockResolvedValue(+ // Empty-result copy: an agent must learn that the report was filtered to+ // Organic Search (and that its endDate moved) rather than conclude the site+ // has no traffic.+ it.each([+ [+ "page_performance names the Organic Search filter when empty",+ () =>+ getGoogleAnalyticsPagePerformanceTool.handler(+ {+ projectId: "project_1",+ includeDate: false,+ channel: "organic_search",+ limit: 100,+ offset: 0,+ },+ toolContext,+ ),makeGa4ReportResult({request: {reportKind: "page_performance",@@ -522,54 +361,41 @@ describe("MCP tool text output (service-backed tools)", () => {metrics: ["screenPageViews"],},}),- );-- const result = await getGoogleAnalyticsPagePerformanceTool.handler(- {- projectId: "project_1",- includeDate: false,- channel: "organic_search",- limit: 100,- offset: 0,- },- toolContext,- );-- expect(textContent(result)).toEqual("Page performance: 0 of 0 rows for 2026-07-09 through 2026-08-05. This report is filtered to Organic Search. Pass channel=all to include every channel.",- );- });-- it("get_google_analytics_organic_landing_pages names Organic Search without a channel argument", async () => {- mocks.runGa4Report.mockResolvedValue(makeGa4ReportResult());-- const result = await getGoogleAnalyticsOrganicLandingPagesTool.handler(- { projectId: "project_1", limit: 100, offset: 0 },- toolContext,- );-- expect(textContent(result)).toEqual(+ ],+ [+ "organic_landing_pages names Organic Search without a channel argument",+ () =>+ getGoogleAnalyticsOrganicLandingPagesTool.handler(+ { projectId: "project_1", limit: 100, offset: 0 },+ toolContext,+ ),+ makeGa4ReportResult(),"Organic landing pages: 0 of 0 rows for 2026-07-09 through 2026-08-05. This report is limited to Organic Search.",- );- });-- it("get_google_analytics_organic_landing_pages states an end-date clamp", async () => {- mocks.runGa4Report.mockResolvedValue(+ ],+ [+ "organic_landing_pages states an end-date clamp",+ () =>+ getGoogleAnalyticsOrganicLandingPagesTool.handler(+ { projectId: "project_1", limit: 100, offset: 0 },+ toolContext,+ ),makeGa4ReportResult({ warnings: ["end_date_clamped"] }),- );-- const result = await getGoogleAnalyticsOrganicLandingPagesTool.handler(- { projectId: "project_1", limit: 100, offset: 0 },- toolContext,- );-- expect(textContent(result)).toEqual("Organic landing pages: 0 of 0 rows for 2026-07-09 through 2026-08-05. The requested endDate was moved back to 2026-08-05, the last complete Analytics day. This report is limited to Organic Search.",- );- });-- it("get_google_analytics_traffic_acquisition does not mention Organic Search when empty", async () => {- mocks.runGa4Report.mockResolvedValue(+ ],+ [+ "traffic_acquisition does not mention Organic Search when empty",+ () =>+ getGoogleAnalyticsTrafficAcquisitionTool.handler(+ {+ projectId: "project_1",+ breakdown: "channel_group",+ comparePreviousPeriod: false,+ limit: 100,+ offset: 0,+ },+ toolContext,+ ),makeGa4ReportResult({request: {reportKind: "traffic_acquisition",@@ -578,72 +404,12 @@ describe("MCP tool text output (service-backed tools)", () => {metrics: ["sessions"],},}),- );-- const result = await getGoogleAnalyticsTrafficAcquisitionTool.handler(- {- projectId: "project_1",- breakdown: "channel_group",- comparePreviousPeriod: false,- limit: 100,- offset: 0,- },- toolContext,- );-- expect(textContent(result)).toEqual("Traffic acquisition: 0 of 0 rows for 2026-07-09 through 2026-08-05.",- );- });+ ],+ ])("get_google_analytics_%s", async (_label, call, report, expected) => {+ mocks.runGa4Report.mockResolvedValue(report);- it("get_google_analytics_organic_overview renders current and previous totals", async () => {- mocks.getOrganicOverview.mockResolvedValue({- status: "ok",- request: {- resolvedDateRange: { startDate: "2026-07-09", endDate: "2026-08-05" },- previousDateRange: { startDate: "2026-06-11", endDate: "2026-07-08" },- },- warnings: [],- current: {- sessions: 120,- activeUsers: 80,- engagedSessions: 70,- engagementRate: 0.58,- keyEvents: 9,- transactions: 2,- purchaseRevenue: 40.5,- },- previous: {- sessions: 100,- activeUsers: 70,- engagedSessions: 60,- engagementRate: 0.5,- keyEvents: 8,- transactions: 1,- purchaseRevenue: 20,- },- comparison: {},- trend: [{ date: "20260709", sessions: 5 }],- });-- const result = await getGoogleAnalyticsOrganicOverviewTool.handler(- { projectId: "project_1", trend: "daily" },- toolContext,- );-- expect(textContent(result)).toEqual(- [- "Organic overview for 2026-07-09 through 2026-08-05, compared with 2026-06-11 through 2026-07-08.",- "metric | current | previous",- "sessions | 120 | 100",- "activeUsers | 80 | 70",- "engagedSessions | 70 | 60",- "engagementRate | 0.58 | 0.50",- "keyEvents | 9 | 8",- "transactions | 2 | 1",- "purchaseRevenue | 40.50 | 20",- ].join("\n"),- );+ expect(textContent(await call())).toEqual(expected);});it("get_google_analytics_organic_overview states a truncated trend and names Organic Search when there is no current row", async () => {diff --git a/src/server/mcp/transport-v2.test.ts b/src/server/mcp/transport-v2.test.tsindex a4bcbbfa..f1e370af 100644--- a/src/server/mcp/transport-v2.test.ts+++ b/src/server/mcp/transport-v2.test.ts@@ -67,26 +67,6 @@ function request(}describe("Agents SDK v2 MCP transport", () => {- it("rejects a standalone GET without constructing a server", async () => {- let serverCount = 0;- const handler = createMcpHandler(- () => {- serverCount += 1;- const server = new McpServer({ name: "test", version: "1.0.0" });- server.registerTool("ping", {}, () => ({- content: [{ type: "text", text: "pong" }],- }));- return server;- },- { route: "/mcp" },- );-- const response = await handler(request("GET"), {}, ctx);-- expect(response.status).toBe(405);- expect(serverCount).toBe(0);- });-it("passes verified provider identity and application props to tools", async () => {const props = { openSeoAuth: { organizationId: "org-1" } };const oauthContext = {@@ -143,40 +123,6 @@ describe("Agents SDK v2 MCP transport", () => {expect(responseText).toContain('\\"organizationId\\":\\"org-1\\"');});- it("accepts the SurfMind extension origin and rejects other browser origins", async () => {- const handler = createMcpHandler(- () => new McpServer({ name: "test", version: "1.0.0" }),- {- route: "/mcp",- allowedOriginHostnames: [- "open-seo.test",- "pghallcbnfabbgfijhbcldaapmgidnaa",- ],- },- );- const body = {- jsonrpc: "2.0",- id: 1,- method: "tools/list",- };-- const surfMindResponse = await handler(- request("POST", body, {- Origin: "chrome-extension://pghallcbnfabbgfijhbcldaapmgidnaa",- }),- {},- ctx,- );- const unrelatedOriginResponse = await handler(- request("POST", body, { Origin: "https://evil.com" }),- {},- ctx,- );-- expect(surfMindResponse.status).toBe(200);- expect(unrelatedOriginResponse.status).toBe(403);- });-it("enforces exact hosted origins around the real SDK handler", async () => {const props = createWorkersOAuthMcpProps({userId: "user-1",diff --git a/src/server/mcp/transport.test.ts b/src/server/mcp/transport.test.tsindex 2dcc6eac..8c6365ce 100644--- a/src/server/mcp/transport.test.ts+++ b/src/server/mcp/transport.test.ts@@ -148,57 +148,57 @@ describe("handleSelfHostedOpenSeoMcpRequest", () => {});});- it("accepts local no-auth MCP requests with the local admin context", async () => {- const response = await handleSelfHostedOpenSeoMcpRequest(- createMcpRequest(),- "local_noauth",- {},- ctx,- );-- expect(response.status).toBe(200);- expect(response.headers.get("content-type")).toContain("application/json");- expect(response.headers.get("connection")).not.toBe("keep-alive");- expect(selfHostedAuthMocks.resolveLocalNoAuthContext).toHaveBeenCalled();- expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({- [MCP_AUTH_CONTEXT_PROP]: {+ it.each([+ [+ "local_noauth" as const,+ selfHostedAuthMocks.resolveLocalNoAuthContext,+ {userId: "local-admin",userEmail: "admin@localhost",organizationId: "delegated-local-admin",- baseUrl: "https://open-seo.test",},- });- // Self-hosted must not pin Origins to the request's own Host — the- // handler's localhost-class default is the rebinding-safe choice.- expect(selfHostedAuthMocks.createMcpHandler).toHaveBeenCalledWith(- expect.objectContaining({- allowedOriginHostnames: undefined,- legacy: "reject",- }),- );- });-- it("accepts Cloudflare Access MCP requests through the existing Access resolver", async () => {- const response = await handleSelfHostedOpenSeoMcpRequest(- createMcpRequest(),- "cloudflare_access",- {},- ctx,- );-- expect(response.status).toBe(200);- expect(+ ],+ [+ "cloudflare_access" as const,selfHostedAuthMocks.resolveCloudflareAccessContext,- ).toHaveBeenCalledWith(expect.any(Headers));- expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({- [MCP_AUTH_CONTEXT_PROP]: {+ {userId: "cloudflare-user",userEmail: "[email protected]",organizationId: "delegated-cloudflare-user",- baseUrl: "https://open-seo.test",},- });- });+ ],+ ])(+ "accepts %s MCP requests with the resolved identity",+ async (authMode, resolver, identity) => {+ const response = await handleSelfHostedOpenSeoMcpRequest(+ createMcpRequest(),+ authMode,+ {},+ ctx,+ );++ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toContain(+ "application/json",+ );+ expect(response.headers.get("connection")).not.toBe("keep-alive");+ expect(resolver).toHaveBeenCalled();+ expect(selfHostedAuthMocks.createOpenSeoMcpServer).toHaveBeenCalledWith({+ [MCP_AUTH_CONTEXT_PROP]: {+ ...identity,+ baseUrl: "https://open-seo.test",+ },+ });+ // Self-hosted must not pin Origins to the request's own Host — the+ // handler's localhost-class default is the rebinding-safe choice.+ expect(selfHostedAuthMocks.createMcpHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ allowedOriginHostnames: undefined,+ legacy: "reject",+ }),+ );+ },+ );it("answers OPTIONS preflight without resolving an auth context", async () => {const response = await handleSelfHostedOpenSeoMcpRequest(@@ -272,36 +272,6 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {expect(selfHostedAuthMocks.createOpenSeoMcpServer).not.toHaveBeenCalled();});- it("accepts a modern request from the exact SurfMind extension origin", async () => {- const props = hostedProps();-- const response = await handleAuthenticatedOpenSeoMcpRequest(- createModernMcpRequest({- Origin: "chrome-extension://pghallcbnfabbgfijhbcldaapmgidnaa",- }),- props,- {},- { ...ctx, props },- );-- expect(response.status).toBe(202);- expect(await response.json()).toEqual({ handledBy: "modern" });- });-- it("rejects a legacy request from a disallowed Origin", async () => {- const props = hostedProps();-- const response = await handleAuthenticatedOpenSeoMcpRequest(- createMcpRequest({ Origin: "https://evil.com" }),- props,- {},- { ...ctx, props },- );-- expect(response.status).toBe(403);- expect(selfHostedAuthMocks.createOpenSeoMcpServer).not.toHaveBeenCalled();- });-it("accepts a legacy request from the SurfMind Chrome extension", async () => {const props = hostedProps();@@ -324,28 +294,6 @@ describe("handleAuthenticatedOpenSeoMcpRequest", () => {});});- it.each([- [- "the SurfMind hostname over HTTPS",- "https://pghallcbnfabbgfijhbcldaapmgidnaa",- ],- [- "another Chrome extension",- "chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",- ],- ])("rejects a request from %s", async (_label, origin) => {- const props = hostedProps();-- const response = await handleAuthenticatedOpenSeoMcpRequest(- createMcpRequest({ Origin: origin }),- props,- {},- { ...ctx, props },- );-- expect(response.status).toBe(403);- });-it("rejects provider props missing the OAuth client identity", async () => {// Hosted tokens always carry clientId/scopes; a token without them must// fail closed rather than skip scope enforcement.diff --git a/src/server/referrals/dub-sale.test.ts b/src/server/referrals/dub-sale.test.tsindex f1275664..b2e9c9eb 100644--- a/src/server/referrals/dub-sale.test.ts+++ b/src/server/referrals/dub-sale.test.ts@@ -41,26 +41,16 @@ describe("buildDubSaleRequest", () => {).toBe(1999);});- it("skips unpaid invoices", () => {- expect(- buildDubSaleRequest(invoice({ status: "open" }), "org_1"),- ).toBeNull();- });-- it("skips zero-total invoices", () => {- expect(buildDubSaleRequest(invoice({ total: 0 }), "org_1")).toBeNull();- });-- it("skips non-USD invoices", () => {+ it.each([+ ["unpaid", { status: "open" }],+ ["zero-total", { total: 0 }],+ ["non-USD", { currency: "eur" }],+ // A total this large signals cents were passed where dollars belong.+ ["implausibly large", { total: 1900 }],+ ])("skips %s invoices", (_label, overrides) => {vi.spyOn(console, "warn").mockImplementation(() => {});- expect(- buildDubSaleRequest(invoice({ currency: "eur" }), "org_1"),- ).toBeNull();- });-- it("skips implausibly large totals that would signal a unit mismatch", () => {vi.spyOn(console, "error").mockImplementation(() => {});- expect(buildDubSaleRequest(invoice({ total: 1900 }), "org_1")).toBeNull();+ expect(buildDubSaleRequest(invoice(overrides), "org_1")).toBeNull();});it("falls back to a stable synthetic key when stripeId is missing", () => {diff --git a/src/server/workflows/RankCheckWorkflow.test.ts b/src/server/workflows/RankCheckWorkflow.test.tsindex cfafc209..491ad420 100644--- a/src/server/workflows/RankCheckWorkflow.test.ts+++ b/src/server/workflows/RankCheckWorkflow.test.ts@@ -1,9 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";import type { WorkflowStep } from "cloudflare:workers";-import {- prepareRankCheckKeywords,- RankCheckWorkflow,-} from "./RankCheckWorkflow";+import { RankCheckWorkflow } from "./RankCheckWorkflow";const mocks = vi.hoisted(() => ({getConfigById: vi.fn(),@@ -71,96 +68,82 @@ const activeRun = {status: "running",};+const payload = {+ runId: "run_1",+ configId: "config_1",+ billingCustomer,+ projectId: "project_1",+ domain: "example.com",+ locationCode: 2840,+ languageCode: "en",+ devices: "desktop" as const,+ serpDepth: 10,+ trigger: "manual" as const,+};++function keywords(count: number) {+ return Array.from({ length: count }, (_, index) => ({+ id: `kw_${index}`,+ keyword: `keyword ${index}`,+ }));+}++function runWorkflow(+ overrides: Partial<typeof payload> & { maxCostCredits?: number },+) {+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the mocked base class does not inspect Worker constructor context+ const workflow = new RankCheckWorkflow({} as ExecutionContext, {} as Env);+ return workflow.run(+ {+ instanceId: "run_1",+ timestamp: new Date(),+ payload: { ...payload, ...overrides },+ },+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- workflow steps are executed directly by the pgStep mock+ {} as WorkflowStep,+ );+}+describe("rank check workflow credit ceiling", () => {beforeEach(() => {+ mocks.getConfigById.mockResolvedValue({ isActive: true });mocks.getRunById.mockResolvedValue(activeRun);+ mocks.getSnapshotsForRun.mockResolvedValue([]);mocks.updateRun.mockResolvedValue(undefined);mocks.isHostedServerAuthMode.mockResolvedValue(true);mocks.autumnCheck.mockResolvedValue({ balance: { remaining: 1_000 } });});it("rejects a keyword-list race before balance or DataForSEO calls", async () => {- mocks.getConfigById.mockResolvedValue({ isActive: true });- mocks.getKeywordsForConfig.mockResolvedValue(- Array.from({ length: 5 }, (_, index) => ({- id: `kw_${index}`,- keyword: `keyword ${index}`,- })),- );- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the mocked base class does not inspect Worker constructor context- const workflow = new RankCheckWorkflow({} as ExecutionContext, {} as Env);-- await expect(- workflow.run(- {- instanceId: "run_1",- timestamp: new Date(),- payload: {- runId: "run_1",- configId: "config_1",- billingCustomer,- projectId: "project_1",- domain: "example.com",- locationCode: 2840,- languageCode: "en",- devices: "desktop",- serpDepth: 10,- trigger: "manual",- maxCostCredits: 12,- },- },- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- workflow steps are executed directly by the pgStep mock- {} as WorkflowStep,- ),- ).rejects.toMatchObject({ code: "VALIDATION_ERROR" });+ mocks.getKeywordsForConfig.mockResolvedValue(keywords(5));++ await expect(runWorkflow({ maxCostCredits: 12 })).rejects.toMatchObject({+ code: "VALIDATION_ERROR",+ });expect(mocks.autumnCheck).not.toHaveBeenCalled();expect(mocks.createDataforseoClient).not.toHaveBeenCalled();expect(mocks.runLiveCheck).not.toHaveBeenCalled();});- it("accepts the same reloaded list at the approved ceiling", async () => {- mocks.getKeywordsForConfig.mockResolvedValue(- Array.from({ length: 4 }, (_, index) => ({- id: `kw_${index}`,- keyword: `keyword ${index}`,- })),- );+ // Exactly at the ceiling is approved (the guard is strictly greater), and+ // callers without a ceiling — every scheduled check — must not be treated+ // as approving zero credits.+ it.each([+ ["at the approved ceiling", 12, 4],+ ["without a ceiling", undefined, 5],+ ])("checks the reloaded list %s", async (_label, maxCostCredits, count) => {+ mocks.getKeywordsForConfig.mockResolvedValue(keywords(count));- const result = await prepareRankCheckKeywords({- runId: "run_1",- configId: "config_1",- billingCustomer,- devices: "desktop",- serpDepth: 10,- trigger: "manual",- maxCostCredits: 12,- });+ await runWorkflow({ maxCostCredits });- expect(result.keywords).toHaveLength(4);- expect(mocks.autumnCheck).toHaveBeenCalledTimes(2);- });-- it("preserves callers that do not provide a ceiling", async () => {- mocks.getKeywordsForConfig.mockResolvedValue(- Array.from({ length: 5 }, (_, index) => ({- id: `kw_${index}`,- keyword: `keyword ${index}`,- })),- );- mocks.isHostedServerAuthMode.mockResolvedValue(false);-- const result = await prepareRankCheckKeywords({- runId: "run_1",- configId: "config_1",- billingCustomer,- devices: "desktop",- serpDepth: 10,- trigger: "manual",+ expect(mocks.updateRun).toHaveBeenCalledWith("run_1", {+ keywordsTotal: count,});-- expect(result.keywords).toHaveLength(5);- expect(mocks.autumnCheck).not.toHaveBeenCalled();+ expect(mocks.runLiveCheck).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ keywords: keywords(count) }),+ );});});@@ -173,12 +156,7 @@ describe("rank check finalization", () => {// Recorded by the batch step on the first rejected keyword.errorMessage: "Invalid Field: 'location_name'.",});- mocks.getKeywordsForConfig.mockResolvedValue(- Array.from({ length: 3 }, (_, index) => ({- id: `kw_${index}`,- keyword: `keyword ${index}`,- })),- );+ mocks.getKeywordsForConfig.mockResolvedValue(keywords(3));mocks.getSnapshotsForRun.mockResolvedValue([]);mocks.updateRun.mockResolvedValue(undefined);mocks.isHostedServerAuthMode.mockResolvedValue(true);@@ -186,29 +164,7 @@ describe("rank check finalization", () => {});it("fails a run where no keyword produced a snapshot, keeping the recorded reason", async () => {- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the mocked base class does not inspect Worker constructor context- const workflow = new RankCheckWorkflow({} as ExecutionContext, {} as Env);-- await workflow.run(- {- instanceId: "run_1",- timestamp: new Date(),- payload: {- runId: "run_1",- configId: "config_1",- billingCustomer,- projectId: "project_1",- domain: "example.com",- locationCode: 2840,- languageCode: "en",- devices: "desktop",- serpDepth: 10,- trigger: "manual",- },- },- // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- workflow steps are executed directly by the pgStep mock- {} as WorkflowStep,- );+ await runWorkflow({});expect(mocks.updateRun).toHaveBeenCalledWith("run_1",diff --git a/src/server/workflows/RankCheckWorkflow.ts b/src/server/workflows/RankCheckWorkflow.tsindex 50becfb7..9abe7647 100644--- a/src/server/workflows/RankCheckWorkflow.ts+++ b/src/server/workflows/RankCheckWorkflow.ts@@ -49,7 +49,7 @@ interface RankCheckParams {maxCostCredits?: number;}-export async function prepareRankCheckKeywords(input: {+async function prepareRankCheckKeywords(input: {runId: string;configId: string;billingCustomer: BillingCustomerContext;diff --git a/src/server/workflows/site-audit-workflow-helpers.test.ts b/src/server/workflows/site-audit-workflow-helpers.test.tsindex a3c33ebb..e5f72367 100644--- a/src/server/workflows/site-audit-workflow-helpers.test.ts+++ b/src/server/workflows/site-audit-workflow-helpers.test.ts@@ -60,35 +60,6 @@ describe("crawlPage", () => {expect(page?.rateLimited).toBe(true);});- it("holds every other fetch in the chunk while one URL's 429 pause runs", async () => {- vi.useFakeTimers();- const fetched: string[] = [];- vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => {- fetched.push(new Request(input).url);- // Only the first request to the first URL is refused.- const refused = fetched.length === 1;- return new Response(PAGE_HTML, {- status: refused ? 429 : 200,- headers: {- "content-type": "text/html",- ...(refused ? { "retry-after": "5" } : {}),- },- });- });- const throttle = createCrawlThrottle(Date.now() + 90_000);-- const first = crawlPage(`${PAGE_URL}/first`, 0, false, throttle);- await vi.advanceTimersByTimeAsync(0);- const second = crawlPage(`${PAGE_URL}/second`, 0, false, throttle);- await vi.advanceTimersByTimeAsync(4_000);- expect(fetched).toEqual([`${PAGE_URL}/first`]);-- await vi.advanceTimersByTimeAsync(3_000);- const pages = await Promise.all([first, second]);- expect(fetched).toHaveLength(3);- expect(pages.map((page) => page?.fetchClass)).toEqual(["ok", "ok"]);- });-it("records a page the site keeps rate limiting, without calling it blocked", async () => {vi.useFakeTimers();const fetchMock = stubFetch({ status: 429, retryAfter: "1" });@@ -101,52 +72,25 @@ describe("crawlPage", () => {expect(page?.fetchClass).toBe("rate_limited");});- it("recovers concurrent pages without a burst after sixty seconds", async () => {- vi.useFakeTimers();- vi.setSystemTime(0);- const starts: number[] = [];- vi.spyOn(globalThis, "fetch").mockImplementation(async () => {- starts.push(Date.now());- return new Response(PAGE_HTML, {- status: Date.now() < 60_000 ? 429 : 200,- headers: { "content-type": "text/html", "retry-after": "60" },- });- });- const throttle = createCrawlThrottle(90_000);- const pages = Promise.all(- Array.from({ length: 5 }, (_, i) =>- crawlPage(`${PAGE_URL}/${i}`, 0, false, throttle),- ),- );- await vi.advanceTimersByTimeAsync(59_999);- expect(starts).toEqual([0]);- await vi.runAllTimersAsync();- expect((await pages).map((page) => page?.fetchClass)).toEqual(- Array(5).fill("ok"),- );- expect(starts).toEqual([0, 60_000, 62_000, 64_000, 66_000, 68_000]);- });-- it("defers the refused URL when its cooldown exceeds the chunk deadline", async () => {+ // A long Retry-After is deferred to a later chunk; one past the audit's+ // whole cooldown budget is recorded as the page's final answer.+ it.each([+ ["defers the URL when its cooldown outlasts the chunk", "600", null, false],+ [+ "records a final 429 when the wait exceeds the cooldown budget",+ "3600",+ "rate_limited",+ true,+ ],+ ])("%s", async (_label, retryAfter, fetchClass, stopped) => {vi.useFakeTimers();- const fetchMock = stubFetch({ status: 429, retryAfter: "600" });+ const fetchMock = stubFetch({ status: 429, retryAfter });const throttle = createCrawlThrottle(Date.now() + 90_000);- expect(await crawlPage(PAGE_URL, 0, false, throttle)).toBeNull();- expect(- await crawlPage(`${PAGE_URL}/unvisited`, 0, false, throttle),- ).toBeNull();- expect(throttle.stopped).toBe(false);- expect(fetchMock).toHaveBeenCalledTimes(1);- });- it("records a final 429 when the requested wait exceeds the audit's cooldown budget", async () => {- vi.useFakeTimers();- const fetchMock = stubFetch({ status: 429, retryAfter: "3600" });- const throttle = createCrawlThrottle(Date.now() + 90_000);- expect((await crawlPage(PAGE_URL, 0, false, throttle))?.fetchClass).toBe(- "rate_limited",- );- expect(throttle.stopped).toBe(true);+ const page = await crawlPage(PAGE_URL, 0, false, throttle);++ expect(page?.fetchClass ?? null).toBe(fetchClass);+ expect(throttle.stopped).toBe(stopped);expect(fetchMock).toHaveBeenCalledTimes(1);});diff --git a/src/server/workflows/siteAuditWorkflowCrawl.test.ts b/src/server/workflows/siteAuditWorkflowCrawl.test.tsindex 4bbc0c2e..93cd3a74 100644--- a/src/server/workflows/siteAuditWorkflowCrawl.test.ts+++ b/src/server/workflows/siteAuditWorkflowCrawl.test.ts@@ -92,7 +92,6 @@ beforeEach(async () => {});afterEach(() => {vi.useRealTimers();- vi.restoreAllMocks();});function crawl(maxPages = 100) {@@ -130,7 +129,7 @@ function serve(status: (now: number) => number, retryAfter?: string) {}describe("crawl pacing and cooldowns", () => {- it("spaces a fast site's requests across chunks without duplicates", async () => {+ it("spaces a fast site's requests across chunks", async () => {const starts: number[] = [];vi.spyOn(globalThis, "fetch").mockImplementation(async () => {starts.push(Date.now());@@ -139,7 +138,6 @@ describe("crawl pacing and cooldowns", () => {const result = crawl(210);await vi.runAllTimersAsync();expect(await result).toEqual({ pagesCrawled: 210, completed: true });- expect(new Set(saved.map((page) => page.url)).size).toBe(210);expect(starts).toHaveLength(210);expect(starts.slice(1).every((at, i) => at - starts[i] >= 1_000)).toBe(true,diff --git a/src/server/workflows/siteAuditWorkflowPhases.test.ts b/src/server/workflows/siteAuditWorkflowPhases.test.tsindex 48209b3a..e6cd67cb 100644--- a/src/server/workflows/siteAuditWorkflowPhases.test.ts+++ b/src/server/workflows/siteAuditWorkflowPhases.test.ts@@ -73,7 +73,6 @@ const PHASE_PARAMS = {describe("runLighthousePhase", () => {beforeEach(() => {- vi.clearAllMocks();getPagesForAuditMock.mockResolvedValue([{id: "page-1",diff --git a/src/serverFunctions/searchPerformance.test.ts b/src/serverFunctions/searchPerformance.test.tsindex 5b50dd52..26e8368f 100644--- a/src/serverFunctions/searchPerformance.test.ts+++ b/src/serverFunctions/searchPerformance.test.ts@@ -5,7 +5,6 @@ import {getSearchPerformanceReport,getSearchPerformanceTable,} from "./searchPerformance";-import { searchPerformanceInputSchema } from "@/types/schemas/search-performance";const { getPerformance } = vi.hoisted(() => ({ getPerformance: vi.fn() }));vi.mock("@/server/features/gsc/services/GscService", () => ({@@ -89,24 +88,6 @@ describe("Search Performance combined filters", () => {},);- it("rejects empty expressions and unsupported match operators", () => {- for (const pageFilter of [- { operator: "contains", expression: " " },- { operator: "startsWith", expression: "/collections/" },- { operator: "contains", expression: "a".repeat(4097) },- ]) {- expect(- searchPerformanceInputSchema.safeParse({ ...data, pageFilter }).success,- ).toBe(false);- expect(- searchPerformanceInputSchema.safeParse({- ...data,- queryFilter: pageFilter,- }).success,- ).toBe(false);- }- });-it("reports the last-page row count instead of a full page for narrow filters", async () => {getPerformance.mockResolvedValue({rows: [diff --git a/src/shared/crawler-access.test.ts b/src/shared/crawler-access.test.tsindex 6943ff79..848eab25 100644--- a/src/shared/crawler-access.test.ts+++ b/src/shared/crawler-access.test.ts@@ -15,10 +15,14 @@ describe("crawlerHeadersFor", () => {expect(crawlerHeadersFor("https://store.example.com/a", access)).toEqual(access.headers,);- expect(- crawlerHeadersFor("https://www.store.example.com/a", access),- ).toEqual({});- expect(crawlerHeadersFor("http://store.example.com/a", access)).toEqual({});+ for (const url of [+ "https://www.store.example.com/a",+ "http://store.example.com/a",+ "https://cdn.example.com/a",+ "https://evil.test/a",+ ]) {+ expect(crawlerHeadersFor(url, access)).toEqual({});+ }});it("stops sending the signature once it expires mid-crawl", () => {@@ -27,9 +31,4 @@ describe("crawlerHeadersFor", () => {{},);});-- it("never sends the signature to another host", () => {- expect(crawlerHeadersFor("https://cdn.example.com/a", access)).toEqual({});- expect(crawlerHeadersFor("https://evil.test/a", access)).toEqual({});- });});diff --git a/src/shared/error-codes.test.ts b/src/shared/error-codes.test.tsindex 82ef6486..ccf666f3 100644--- a/src/shared/error-codes.test.ts+++ b/src/shared/error-codes.test.ts@@ -2,19 +2,9 @@ import { describe, expect, it } from "vitest";import { shouldCaptureAppErrorCode } from "@/shared/error-codes";describe("shouldCaptureAppErrorCode", () => {- it.each([- "UNAUTHENTICATED",- "NOT_FOUND",- "PAYMENT_REQUIRED",- "VALIDATION_ERROR",- "UNKNOWN_LOCATION",- "AUDIT_CAPACITY_REACHED",- "AUDIT_PAGE_LIMIT_EXCEEDED",- "AUDIT_ALREADY_RUNNING",- "RATE_LIMITED",- "UPSTREAM_UNAVAILABLE",- ] as const)("skips expected %s errors", (code) => {- expect(shouldCaptureAppErrorCode(code)).toBe(false);+ it("skips expected user-facing errors", () => {+ expect(shouldCaptureAppErrorCode("NOT_FOUND")).toBe(false);+ expect(shouldCaptureAppErrorCode("UPSTREAM_UNAVAILABLE")).toBe(false);});it("captures unexpected errors and unknown failures", () => {diff --git a/src/shared/json.test.ts b/src/shared/json.test.tsindex 30808d85..c11ebe84 100644--- a/src/shared/json.test.ts+++ b/src/shared/json.test.ts@@ -3,28 +3,9 @@ import { z } from "zod";import { jsonCodec } from "@/shared/json";describe("jsonCodec", () => {- const schema = z.object({- name: z.string(),- count: z.number().int().nonnegative(),- });-- const codec = jsonCodec(schema);-- it("parses valid JSON that matches schema", () => {- const parsed = codec.parse('{"name":"open-seo","count":2}');- expect(parsed).toEqual({ name: "open-seo", count: 2 });- });-- it("throws on invalid JSON", () => {- expect(() => codec.parse('{"name":"open-seo"')).toThrowError();- });+ const codec = jsonCodec(z.object({ count: z.number() }));it("throws when JSON does not match schema", () => {- expect(() => codec.parse('{"name":"open-seo","count":"2"}')).toThrowError();- });-- it("encodes typed values to JSON", () => {- const encoded = codec.encode({ name: "open-seo", count: 5 });- expect(encoded).toBe('{"name":"open-seo","count":5}');+ expect(() => codec.parse('{"count":"2"}')).toThrowError();});});diff --git a/src/shared/keyword-locations.test.ts b/src/shared/keyword-locations.test.tsindex 2a8d9fd6..0d2113db 100644--- a/src/shared/keyword-locations.test.ts+++ b/src/shared/keyword-locations.test.ts@@ -1,7 +1,6 @@import { sort } from "remeda";import { describe, expect, it } from "vitest";import {- LABS_LOCATION_OPTIONS,LOCATION_OPTIONS,formatLocationLabel,getIsoCountryCode,@@ -16,37 +15,16 @@ import {} from "./keyword-locations";describe("keyword locations", () => {- it("routes Labs-supported countries to labs", () => {- expect(getKeywordDataProvider(2840)).toBe("labs"); // US- expect(getKeywordDataProvider(2826)).toBe("labs"); // UK- });-- it("routes Google-Ads-only countries to google_ads", () => {+ it("routes Google-Ads-only countries to google_ads and unknown codes to labs", () => {expect(getKeywordDataProvider(2352)).toBe("google_ads"); // Icelandexpect(isSupportedLocationCode(2352)).toBe(true);expect(isLabsLocationCode(2352)).toBe(false);expect(getLanguageCode(2352)).toBe("is");- });-- it("falls back to labs for unknown codes (Labs rejects them upstream)", () => {+ // Labs rejects unknown codes upstream.expect(getKeywordDataProvider(999999)).toBe("labs");expect(isSupportedLocationCode(999999)).toBe(false);});- it("excludes every Google-Ads-only country from the Labs picker", () => {- const adsOnly = LOCATION_OPTIONS.filter((option) => option.googleAdsOnly);- expect(adsOnly.length).toBeGreaterThan(0);- const labsCodes = new Set(- LABS_LOCATION_OPTIONS.map((option) => option.code),- );- for (const option of adsOnly) {- expect(labsCodes.has(option.code)).toBe(false);- }- expect(LABS_LOCATION_OPTIONS.length + adsOnly.length).toBe(- LOCATION_OPTIONS.length,- );- });-it("accepts every supported language code and rejects unknown ones", () => {// Every per-country default we send is, by construction, a supported code.for (const option of LOCATION_OPTIONS) {@@ -71,28 +49,16 @@ describe("keyword locations", () => {});describe("getIsoCountryCode", () => {- it("lowercases the shortLabel for standard countries", () => {- expect(getIsoCountryCode(2840)).toBe("us");- expect(getIsoCountryCode(2036)).toBe("au");- });-it("maps the UK display label to its ISO code gb", () => {expect(getIsoCountryCode(2826)).toBe("gb");});-- it("falls back to us for unknown location codes", () => {- expect(getIsoCountryCode(999999)).toBe("us");- });});describe("formatLocationLabel", () => {- it("trims uneven spacing around canonical name segments", () => {+ it("trims uneven spacing around canonical name segments and truncates to maxSegments", () => {expect(formatLocationLabel("Portland-Auburn, ME,United States")).toBe("Portland-Auburn, ME, United States",);- });-- it("truncates to maxSegments for compact display", () => {expect(formatLocationLabel("Springfield,Illinois,United States", 2)).toBe("Springfield, Illinois",);@@ -102,13 +68,6 @@ describe("formatLocationLabel", () => {describe("resolveMarket", () => {const vietnamProject = { locationCode: 2704, languageCode: "vi" };- it("falls back to the project's pair when nothing is supplied", () => {- expect(resolveMarket({}, vietnamProject)).toEqual({- locationCode: 2704,- languageCode: "vi",- });- });-it("snaps the language to a location override instead of borrowing the project's", () => {// A Vietnam project querying Germany must not send Vietnamese.expect(resolveMarket({ locationCode: 2276 }, vietnamProject)).toEqual({@@ -124,19 +83,6 @@ describe("resolveMarket", () => {languageCode: "es",});});-- it("applies an explicit language to the project's location", () => {- expect(resolveMarket({ languageCode: "en" }, vietnamProject)).toEqual({- locationCode: 2704,- languageCode: "en",- });- });-- it("uses both overrides verbatim", () => {- expect(- resolveMarket({ locationCode: 2276, languageCode: "en" }, vietnamProject),- ).toEqual({ locationCode: 2276, languageCode: "en" });- });});describe("resolveLabsMarket", () => {@@ -173,11 +119,8 @@ describe("resolveLabsMarket", () => {});describe("resolveKeywordDataLanguage", () => {- it("keeps a language the country's keyword data serves", () => {- expect(resolveKeywordDataLanguage(2840, "es")).toBe("es");- });-it("falls back to the country default for a SERP-only pair", () => {+ expect(resolveKeywordDataLanguage(2840, "es")).toBe("es");// Rank tracking can track English in Czechia; Labs would charge and fail.expect(resolveKeywordDataLanguage(2203, "en")).toBe("cs");// Google-Ads countries keep their single default too.diff --git a/src/shared/rank-tracking.test.ts b/src/shared/rank-tracking.test.tsindex 03e96bca..549a188e 100644--- a/src/shared/rank-tracking.test.ts+++ b/src/shared/rank-tracking.test.ts@@ -1,9 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import {- computeNextCheckAt,- estimateRankCheckCredits,- scheduleLabel,-} from "./rank-tracking";+import { computeNextCheckAt, estimateRankCheckCredits } from "./rank-tracking";describe("rank tracking cost estimates", () => {it.each([@@ -54,10 +50,6 @@ describe("rank tracking schedules", () => {vi.useRealTimers();});- it("labels monthly schedules", () => {- expect(scheduleLabel("monthly")).toBe("Monthly");- });-it("schedules new monthly configs for the end of the current month", () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-01-15T12:00:00.000Z"));@@ -74,44 +66,36 @@ describe("rank tracking schedules", () => {expect(computeNextCheckAt("monthly")).toBe("2026-02-28T04:00:00.000Z");});- it("advances monthly schedules on month end across shorter months", () => {+ it("advances monthly schedules on month end until the next check is in the future", () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-02-01T00:00:00.000Z"));-expect(computeNextCheckAt("monthly", "2026-01-31T05:30:00.000Z")).toBe("2026-02-28T05:30:00.000Z",);- });- it("keeps advancing monthly schedules until the next check is in the future", () => {- vi.useFakeTimers();vi.setSystemTime(new Date("2026-03-10T00:00:00.000Z"));-expect(computeNextCheckAt("monthly", "2026-01-31T05:30:00.000Z")).toBe("2026-03-31T05:30:00.000Z",);});- it("preserves the time-of-day anchor for heavily overdue daily schedules", () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));-- expect(computeNextCheckAt("daily", "2026-01-31T05:30:00.000Z")).toBe(- "2026-03-11T05:30:00.000Z",- );- });-- it("preserves the weekday and time anchor for heavily overdue weekly schedules", () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));-- // 2026-01-31 is a Saturday; every advance lands on a Saturday.- expect(computeNextCheckAt("weekly", "2026-01-31T05:30:00.000Z")).toBe(- "2026-03-14T05:30:00.000Z",- );- });+ // 2026-01-31 is a Saturday; every weekly advance lands on a Saturday.+ it.each([+ ["daily", "2026-03-11T05:30:00.000Z"],+ ["weekly", "2026-03-14T05:30:00.000Z"],+ ] as const)(+ "preserves the time anchor for heavily overdue %s schedules",+ (frequency, expected) => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));++ expect(computeNextCheckAt(frequency, "2026-01-31T05:30:00.000Z")).toBe(+ expected,+ );+ },+ );- it("starts a chosen weekly time on its next occurrence", () => {+ it("starts a chosen time on its next occurrence", () => {vi.useFakeTimers();// A Tuesday.vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));@@ -125,6 +109,10 @@ describe("rank tracking schedules", () => {expect(computeNextCheckAt("weekly", null, tuesday9am)).toBe("2026-03-17T09:00:00.000Z",);+ // A daily time still ahead runs later today.+ expect(computeNextCheckAt("daily", null, { hour: 21, minute: 15 })).toBe(+ "2026-03-10T21:15:00.000Z",+ );});it("converts a time chosen in a timezone, weekday included", () => {@@ -149,15 +137,6 @@ describe("rank tracking schedules", () => {).toBe("2026-03-15T15:30:00.000Z");});- it("runs a chosen daily time later today when it is still ahead", () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-03-10T12:00:00.000Z"));-- expect(computeNextCheckAt("daily", null, { hour: 21, minute: 15 })).toBe(- "2026-03-10T21:15:00.000Z",- );- });-it("keeps monthly on the user's last day when it is another UTC date", () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-02-10T12:00:00.000Z"));@@ -185,13 +164,4 @@ describe("rank tracking schedules", () => {"2026-03-30T19:30:00.000Z",);});-- it("keeps monthly on the last day when a time is chosen", () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-02-10T12:00:00.000Z"));-- expect(- computeNextCheckAt("monthly", null, { weekday: 0, hour: 21, minute: 0 }),- ).toBe("2026-02-28T21:00:00.000Z");- });});diff --git a/src/shared/researchScope.test.ts b/src/shared/researchScope.test.tsindex d77c0a16..f78cbe59 100644--- a/src/shared/researchScope.test.ts+++ b/src/shared/researchScope.test.ts@@ -1,10 +1,5 @@import { describe, expect, it } from "vitest";-import {- defaultScopeForPath,- isScopeAllowedForInput,- parseResearchTarget,- urlMatchesResearchTarget,-} from "./researchScope";+import { parseResearchTarget, urlMatchesResearchTarget } from "./researchScope";function parseOk(input: string,@@ -51,11 +46,6 @@ describe("parseResearchTarget", () => {expect(target.urlHostname).toBe("www.example.com");});- it("keeps subdomain hostnames intact", () => {- const target = parseOk("blog.example.com", "subdomains");- expect(target.hostname).toBe("blog.example.com");- });-it("rejects subfolder for a root input instead of silently rescoping", () => {const result = parseResearchTarget("example.com", "subfolder");expect(result).toEqual({@@ -64,10 +54,6 @@ describe("parseResearchTarget", () => {});});- it("allows exact_url for a root input", () => {- expect(parseOk("example.com", "exact_url").scope).toBe("exact_url");- });-it("rejects invalid hosts and credentials", () => {expect(parseResearchTarget("example.por").ok).toBe(false);expect(parseResearchTarget("").ok).toBe(false);@@ -76,20 +62,6 @@ describe("parseResearchTarget", () => {});});-describe("scope helpers", () => {- it("computes defaults from the path", () => {- expect(defaultScopeForPath("")).toBe("subdomains");- expect(defaultScopeForPath("/blog")).toBe("subfolder");- });-- it("only disallows subfolder without a path", () => {- expect(isScopeAllowedForInput("subfolder", "")).toBe(false);- expect(isScopeAllowedForInput("subfolder", "/blog")).toBe(true);- expect(isScopeAllowedForInput("exact_url", "")).toBe(true);- expect(isScopeAllowedForInput("domain", "/blog")).toBe(true);- });-});-describe("urlMatchesResearchTarget", () => {const subfolder = parseOk("example.com/blog", "subfolder");diff --git a/src/shared/saved-keyword-tags.test.ts b/src/shared/saved-keyword-tags.test.tsindex 9b9a9eb8..82c937f9 100644--- a/src/shared/saved-keyword-tags.test.ts+++ b/src/shared/saved-keyword-tags.test.ts@@ -1,24 +1,21 @@import { describe, expect, it } from "vitest";import {- normalizeSavedKeywordTag,normalizeSavedKeywordTags,parseSavedKeywordTagInput,} from "./saved-keyword-tags";describe("saved keyword tag helpers", () => {- it("normalizes display and lookup names", () => {- expect(normalizeSavedKeywordTag(" Technical SEO ")).toEqual({- name: "Technical SEO",- normalizedName: "technical seo",- });- });-it("dedupes tags by normalized name", () => {expect(- normalizeSavedKeywordTags(["Content", "content", " technical seo "]),+ normalizeSavedKeywordTags([+ "Content",+ "content",+ " Technical SEO ",+ "technical seo",+ ]),).toEqual([{ name: "Content", normalizedName: "content" },- { name: "technical seo", normalizedName: "technical seo" },+ { name: "Technical SEO", normalizedName: "technical seo" },]);});diff --git a/src/shared/selfhost-checks.test.ts b/src/shared/selfhost-checks.test.tsindex 49a6ec5d..aa8d5f24 100644--- a/src/shared/selfhost-checks.test.ts+++ b/src/shared/selfhost-checks.test.ts@@ -6,12 +6,6 @@ import {} from "./selfhost-checks";describe("validateTeamDomain", () => {- it("accepts a full https team domain", () => {- expect(- validateTeamDomain("https://your-team.cloudflareaccess.com"),- ).toEqual({ ok: true, origin: "https://your-team.cloudflareaccess.com" });- });-it("trims whitespace and trailing slashes", () => {expect(validateTeamDomain(" https://your-team.cloudflareaccess.com/ "),@@ -33,46 +27,29 @@ describe("validateTeamDomain", () => {const result = validateTeamDomain("http://your-team.cloudflareaccess.com");expect(result.ok).toBe(false);});-- it("rejects empty values", () => {- expect(validateTeamDomain("").ok).toBe(false);- });});describe("looksLikeDataForSeoKey", () => {- it("accepts base64 of login:password", () => {+ it("accepts base64 of login:password, tolerating surrounding whitespace", () => {expect(looksLikeDataForSeoKey(btoa("[email protected]:secret"))).toBe(true);+ expect(looksLikeDataForSeoKey(` ${btoa("a:b")} `)).toBe(true);});it("rejects a raw dashboard API key", () => {expect(looksLikeDataForSeoKey("0123456789abcdef0123")).toBe(false);});-- it("rejects base64 without a colon", () => {- expect(looksLikeDataForSeoKey(btoa("no-colon-here"))).toBe(false);- });-- it("tolerates surrounding whitespace", () => {- expect(looksLikeDataForSeoKey(` ${btoa("a:b")} `)).toBe(true);- });});describe("isTelemetryOptOutValue", () => {- it("treats unset and empty as opted in", () => {- expect(isTelemetryOptOutValue(undefined)).toBe(false);- expect(isTelemetryOptOutValue(null)).toBe(false);- expect(isTelemetryOptOutValue("")).toBe(false);- });-it('treats "1" and "true" as opted out', () => {expect(isTelemetryOptOutValue("1")).toBe(true);expect(isTelemetryOptOutValue("true")).toBe(true);});- it('treats explicit "0"/"false"/"no"/"off" as opted in', () => {- expect(isTelemetryOptOutValue("0")).toBe(false);- expect(isTelemetryOptOutValue("false")).toBe(false);- expect(isTelemetryOptOutValue("no")).toBe(false);- expect(isTelemetryOptOutValue("OFF")).toBe(false);- });+ it.each([undefined, null, "", "0", "false", "no", "OFF"])(+ "treats %j as opted in",+ (value) => {+ expect(isTelemetryOptOutValue(value)).toBe(false);+ },+ );});diff --git a/src/shared/targetDetection.test.ts b/src/shared/targetDetection.test.tsindex 752faff5..b4f768c4 100644--- a/src/shared/targetDetection.test.ts+++ b/src/shared/targetDetection.test.ts@@ -3,27 +3,19 @@ import { detectTarget } from "./targetDetection";describe("detectTarget", () => {it.each([- ["example.com", "example.com"],+ [" example.com ", "example.com"],["https://example.com", "example.com"],- ["https://www.example.com/features", "example.com"],- ["WWW.Example.COM", "example.com"],["sub.example.com", "sub.example.com"],])("treats %s as a domain", (input, expected) => {expect(detectTarget(input)).toEqual({ type: "domain", value: expected });});- it.each([- "Example Brand",- "best ai video clipper",- "OpenAI",- "GPT-5",- "ChatGPT pricing",- ])("treats '%s' as a keyword", (input) => {- expect(detectTarget(input)).toEqual({- type: "keyword",- value: input.trim(),- });- });+ it.each(["GPT-5", "best ai video clipper"])(+ "treats '%s' as a keyword",+ (input) => {+ expect(detectTarget(input)).toEqual({ type: "keyword", value: input });+ },+ );it("falls back to keyword when input has spaces but contains a dot", () => {expect(detectTarget("Visit example.com today")).toEqual({@@ -31,18 +23,4 @@ describe("detectTarget", () => {value: "Visit example.com today",});});-- it("falls back to keyword when domain normalization throws", () => {- expect(detectTarget("not a real domain.")).toEqual({- type: "keyword",- value: "not a real domain.",- });- });-- it("trims whitespace before classification", () => {- expect(detectTarget(" example.com ")).toEqual({- type: "domain",- value: "example.com",- });- });});diff --git a/src/types/schemas/crawlerAccess.test.ts b/src/types/schemas/crawlerAccess.test.tsindex 27df0755..acdbb2ca 100644--- a/src/types/schemas/crawlerAccess.test.ts+++ b/src/types/schemas/crawlerAccess.test.ts@@ -32,11 +32,4 @@ describe("saveCrawlerCredentialSchema", () => {}).success,).toBe(false);});-- it("requires both signature values, not just one", () => {- expect(- saveCrawlerCredentialSchema.safeParse({ ...valid, signature: "" })- .success,- ).toBe(false);- });});diff --git a/src/types/schemas/projects.test.ts b/src/types/schemas/projects.test.tsindex f7ff01b7..6dc59d74 100644--- a/src/types/schemas/projects.test.ts+++ b/src/types/schemas/projects.test.ts@@ -4,36 +4,21 @@ import { createProjectSchema, updateProjectSchema } from "./projects";// The service derives a missing language from the location, so a language// arriving on its own has nothing to validate against.describe("project market fields", () => {- it("rejects a language with no location", () => {+ it.each([+ [{}, true],+ [{ locationCode: 2704 }, true],+ [{ locationCode: 2704, languageCode: "vi" }, true],+ [{ languageCode: "vi" }, false],+ ])("market %j is accepted: %s", (market, success) => {expect(- updateProjectSchema.safeParse({- projectId: "project_1",- name: "Acme",- languageCode: "vi",- }).success,- ).toBe(false);- expect(- createProjectSchema.safeParse({ name: "Acme", languageCode: "vi" })- .success,- ).toBe(false);- });-- it("accepts a location on its own, and a full pair", () => {- expect(- createProjectSchema.safeParse({ name: "Acme", locationCode: 2704 })- .success,- ).toBe(true);+ createProjectSchema.safeParse({ name: "Acme", ...market }).success,+ ).toBe(success);expect(updateProjectSchema.safeParse({projectId: "project_1",name: "Acme",- locationCode: 2704,- languageCode: "vi",+ ...market,}).success,- ).toBe(true);- });-- it("accepts a project with no market at all", () => {- expect(createProjectSchema.safeParse({ name: "Acme" }).success).toBe(true);+ ).toBe(success);});});diff --git a/src/types/schemas/search-params.test.ts b/src/types/schemas/search-params.test.tsindex 33f35b92..b90e20cb 100644--- a/src/types/schemas/search-params.test.ts+++ b/src/types/schemas/search-params.test.ts@@ -1,20 +1,7 @@import { describe, expect, it } from "vitest";-import { backlinksSearchSchema } from "@/types/schemas/backlinks";import { domainSearchSchema } from "@/types/schemas/domain";describe("search param boolean parsing", () => {- it("parses backlinks search params with target and tab", () => {- const parsed = backlinksSearchSchema.parse({- target: "example.com",- tab: "domains",- });-- expect(parsed).toEqual({- target: "example.com",- tab: "domains",- });- });-it("parses explicit false values for domain search params", () => {const parsed = domainSearchSchema.parse({subdomains: "false",diff --git a/web/tests/free-tool-protection.test.ts b/web/tests/free-tool-protection.test.tsindex abfa1a60..cc317838 100644--- a/web/tests/free-tool-protection.test.ts+++ b/web/tests/free-tool-protection.test.ts@@ -41,10 +41,6 @@ beforeEach(() => {});describe("public tool verification", () => {- it("accepts a verified token for this hostname and purpose", async () => {- expect(await guard()).toBeNull();- expect(fetchMock).toHaveBeenCalledTimes(1);- });it.each(["TURNSTILE_SECRET_KEY", "BACKLINK_CHECK_RATE_LIMIT"])("fails closed without %s",async (key) => {@@ -77,13 +73,6 @@ describe("public tool verification", () => {).toBe(403);expect(fetchMock).not.toHaveBeenCalled();});- it("rejects missing tokens", async () => {- expect(- (await guardToolRequest({ tool: "backlink-checker", request: request() }))- ?.status,- ).toBe(403);- expect(fetchMock).not.toHaveBeenCalled();- });it.each([{ success: false },{ success: true, hostname: "other.example", action: "free_tool" },