Skip to content

Open source alternative to Semrush and Ahrefs

Keyword research: blend suggestions + ideas in auto mode and group shared-volume keywords (EVE-64) (#655)

Carter Smithe7e462359587
diff --git a/e2e/fixtures/keyword-research-fixtures.ts b/e2e/fixtures/keyword-research-fixtures.ts
index fa8bf840..b4d2995e 100644
--- a/e2e/fixtures/keyword-research-fixtures.ts
+++ b/e2e/fixtures/keyword-research-fixtures.ts
@@ -56,18 +56,7 @@ export function getKeywordResearchFixture(data: ResolvedResearchKeywordsInput) {
return {
rows,
- source: "related" as const,
+ source: "blended" as const,
usedFallback: false,
- diagnostics: {
- requestedMode: data.mode,
- threshold: 3,
- sourceAttempts: [
- {
- source: "related" as const,
- rowCount: rows.length,
- nonSeedCount: rows.length - 1,
- },
- ],
- },
};
}
diff --git a/plugins/openseo/.claude-plugin/plugin.json b/plugins/openseo/.claude-plugin/plugin.json
index dff1db85..8ffcc26a 100644
--- a/plugins/openseo/.claude-plugin/plugin.json
+++ b/plugins/openseo/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "openseo",
"displayName": "OpenSEO",
- "version": "1.0.1",
+ "version": "1.0.2",
"description": "Without good data, your agent gives generic advice. Keyword research, competitor research, backlinks, and site audits. All for $10/month.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.codex-plugin/plugin.json b/plugins/openseo/.codex-plugin/plugin.json
index bf2b0609..ff9e24de 100644
--- a/plugins/openseo/.codex-plugin/plugin.json
+++ b/plugins/openseo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.1",
+ "version": "1.0.2",
"description": "Without good data, your agent gives generic advice. Keyword research, competitor research, backlinks, and site audits. All for $10/month.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.cursor-plugin/plugin.json b/plugins/openseo/.cursor-plugin/plugin.json
index baf29409..2d1201d2 100644
--- a/plugins/openseo/.cursor-plugin/plugin.json
+++ b/plugins/openseo/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.1",
+ "version": "1.0.2",
"description": "SEO made simple. Research keywords and competitors, audit sites, track rankings, and use Search Console data from your agent.",
"author": {
"name": "Every App, Inc",
diff --git a/specs/0004-keyword-data-source-routing.md b/specs/0004-keyword-data-source-routing.md
index 16cde436..f92c8125 100644
--- a/specs/0004-keyword-data-source-routing.md
+++ b/specs/0004-keyword-data-source-routing.md
@@ -2,7 +2,13 @@
## Status
-Accepted (June 2026)
+Accepted (June 2026). Superseded in part (September 2026): auto mode blends
+`keyword_suggestions` + `keyword_ideas` at half the result limit each instead
+of cascading related → suggestions → ideas, and Labs live pricing has risen to
+$0.012/task + $0.00012/row (measured against the live API). The default
+150-row research call is now two tasks, $0.042 raw → 54 credits, not $0.025 →
+32 credits. The routing, clickstream, and Google-Ads-coverage decisions below
+still hold.
## Context
@@ -43,7 +49,7 @@ There is no user-facing provider choice.
| Feature | Labs country | Google-Ads-only country (e.g. Iceland) |
| --------------------------------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------- |
- | Keyword research (UI + `research_keywords`) | Labs related→suggestions→ideas | `keywords_for_keywords` (single source) |
+ | Keyword research (UI + `research_keywords`) | Labs suggestions + ideas blend | `keywords_for_keywords` (single source) |
| `get_keyword_metrics`, rank-tracking metric refresh | Labs keyword_overview | `search_volume` |
| SERP analysis, `get_serp_results`, rank tracking | SERP API | SERP API (supports all countries) |
| Domain overview, ranked keywords, SERP competitors | Labs | **Unavailable** — pickers filtered to Labs countries; MCP tools return a clear validation error |
diff --git a/src/client/features/keywords/groupSharedVolumeRows.test.ts b/src/client/features/keywords/groupSharedVolumeRows.test.ts
new file mode 100644
index 00000000..d42b0906
--- /dev/null
+++ b/src/client/features/keywords/groupSharedVolumeRows.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from "vitest";
+import type { KeywordResearchRow } from "@/types/keywords";
+import { groupSharedVolumeRows, ungroupRows } from "./groupSharedVolumeRows";
+
+const SERIES = [
+ { year: 2026, month: 7, searchVolume: 110000 },
+ { year: 2026, month: 8, searchVolume: 90500 },
+];
+
+function row(overrides: Partial<KeywordResearchRow>): KeywordResearchRow {
+ return {
+ keyword: "caregiving",
+ searchVolume: 110000,
+ trend: SERIES,
+ keywordDifficulty: 61,
+ cpc: 8.14,
+ competition: 0.27,
+ intent: "informational",
+ ...overrides,
+ };
+}
+
+describe("groupSharedVolumeRows", () => {
+ it("folds rows with the same volume, CPC, and monthly series under the first", () => {
+ const rows = [
+ row({ keyword: "caregiving" }),
+ row({ keyword: "respite care", searchVolume: 165000 }),
+ row({ keyword: "caregiver", keywordDifficulty: 45 }),
+ ];
+
+ const grouped = groupSharedVolumeRows(rows);
+
+ expect(grouped.map((r) => r.keyword)).toEqual([
+ "caregiving",
+ "respite care",
+ ]);
+ expect(grouped[0].variants).toEqual([rows[2]]);
+ expect(ungroupRows(grouped).map((r) => r.keyword)).toEqual([
+ "caregiving",
+ "caregiver",
+ "respite care",
+ ]);
+ });
+
+ it("leads a group with the searched keyword as typed", () => {
+ const rows = [
+ row({ keyword: "caregiver" }),
+ row({ keyword: "caregiving" }),
+ ];
+
+ const [group] = groupSharedVolumeRows(rows, " Caregiving");
+
+ expect(group.keyword).toBe("caregiving");
+ expect(group.variants.map((r) => r.keyword)).toEqual(["caregiver"]);
+ });
+
+ it("keeps rows apart when the shared number is a flat or low-volume bucket", () => {
+ const flat = [{ year: 2026, month: 8, searchVolume: 5400 }];
+ const rows = [
+ row({ keyword: "a", searchVolume: 5400, trend: flat }),
+ row({ keyword: "b", searchVolume: 5400, trend: flat }),
+ row({ keyword: "c", searchVolume: 90 }),
+ row({ keyword: "d", searchVolume: 90 }),
+ ];
+
+ expect(groupSharedVolumeRows(rows)).toHaveLength(4);
+ });
+});
diff --git a/src/client/features/keywords/groupSharedVolumeRows.ts b/src/client/features/keywords/groupSharedVolumeRows.ts
new file mode 100644
index 00000000..7d4ad123
--- /dev/null
+++ b/src/client/features/keywords/groupSharedVolumeRows.ts
@@ -0,0 +1,68 @@
+import type { KeywordResearchRow } from "@/types/keywords";
+
+/** A results row plus the other keywords that report the same search volume. */
+export type KeywordResearchDisplayRow = KeywordResearchRow & {
+ variants: KeywordResearchRow[];
+};
+
+// Only group above this volume: bucketed low volumes (10, 20, ...) collide by
+// coincidence, while real close-variant groups share big grouped numbers.
+const SHARED_VOLUME_MIN = 1000;
+
+function sharedVolumeKey(row: KeywordResearchRow): string | null {
+ if (row.searchVolume == null || row.searchVolume < SHARED_VOLUME_MIN) {
+ return null;
+ }
+ // A flat series is a bucketed placeholder, not a fingerprint, so two
+ // unrelated keywords could share it by coincidence.
+ if (new Set(row.trend.map((entry) => entry.searchVolume)).size <= 1) {
+ return null;
+ }
+ const series = row.trend
+ .map((entry) => `${entry.year}-${entry.month}:${entry.searchVolume}`)
+ .join(",");
+ return `${row.searchVolume}|${row.cpc}|${series}`;
+}
+
+/**
+ * Google Ads reports one volume for a whole close-variant group ("caregiving"
+ * / "caregiver" / "caregivers"), so those rows all claim the same searches.
+ * Fold rows with an identical volume, CPC, and monthly series under the
+ * searched keyword when it is in the group, otherwise under the first one in
+ * the given order. Display only: every keyword keeps its own metrics
+ * and stays in the data, so filters and exports still reach each variant.
+ */
+export function groupSharedVolumeRows(
+ rows: KeywordResearchRow[],
+ searchedKeyword?: string,
+): KeywordResearchDisplayRow[] {
+ // Row keywords are lowercase; the searched keyword arrives as typed.
+ const seed = searchedKeyword?.trim().toLowerCase();
+ const groups = new Map<string, KeywordResearchDisplayRow>();
+ const result: KeywordResearchDisplayRow[] = [];
+
+ for (const row of rows) {
+ const key = sharedVolumeKey(row);
+ const group = key ? groups.get(key) : undefined;
+ if (group && row.keyword === seed) {
+ const { variants, ...leader } = group;
+ Object.assign(group, row, { variants: [leader, ...variants] });
+ continue;
+ }
+ if (group) {
+ group.variants.push(row);
+ continue;
+ }
+ const displayRow = { ...row, variants: [] };
+ if (key) groups.set(key, displayRow);
+ result.push(displayRow);
+ }
+
+ return result;
+}
+
+export function ungroupRows(
+ rows: KeywordResearchDisplayRow[],
+): KeywordResearchRow[] {
+ return rows.flatMap(({ variants, ...row }) => [row, ...variants]);
+}
diff --git a/src/client/features/keywords/hooks/useKeywordFiltering.ts b/src/client/features/keywords/hooks/useKeywordFiltering.ts
index 8e69d274..5d2488bf 100644
--- a/src/client/features/keywords/hooks/useKeywordFiltering.ts
+++ b/src/client/features/keywords/hooks/useKeywordFiltering.ts
@@ -7,6 +7,7 @@ import {
type KeywordFilterValues,
} from "@/client/features/keywords/keywordResearchTypes";
import type { SortDir, SortField } from "@/client/features/keywords/components";
+import { groupSharedVolumeRows } from "@/client/features/keywords/groupSharedVolumeRows";
export function applyKeywordFiltersAndSort(params: {
rows: KeywordResearchRow[];
@@ -72,19 +73,31 @@ export function applyKeywordFiltersAndSort(params: {
export function useKeywordFiltering(params: {
rows: KeywordResearchRow[];
+ searchedKeyword: string;
filters: KeywordFilterValues;
sortField: SortField;
sortDir: SortDir;
}) {
+ // Group after filtering so a variant that passes the filters on its own
+ // (say, a lower difficulty) is never hidden behind one that does not.
const filteredRows = useMemo(
() =>
- applyKeywordFiltersAndSort({
- rows: params.rows,
- filters: params.filters,
- sortField: params.sortField,
- sortDir: params.sortDir,
- }),
- [params.filters, params.rows, params.sortDir, params.sortField],
+ groupSharedVolumeRows(
+ applyKeywordFiltersAndSort({
+ rows: params.rows,
+ filters: params.filters,
+ sortField: params.sortField,
+ sortDir: params.sortDir,
+ }),
+ params.searchedKeyword,
+ ),
+ [
+ params.filters,
+ params.rows,
+ params.searchedKeyword,
+ params.sortDir,
+ params.sortField,
+ ],
);
const activeFilterCount = useMemo(
diff --git a/src/client/features/keywords/hooks/useKeywordResearchData.ts b/src/client/features/keywords/hooks/useKeywordResearchData.ts
index f93083b1..ede39ca6 100644
--- a/src/client/features/keywords/hooks/useKeywordResearchData.ts
+++ b/src/client/features/keywords/hooks/useKeywordResearchData.ts
@@ -7,7 +7,6 @@ import { parseKeywordInput } from "@/client/features/keywords/state/keywordContr
import { researchKeywords } from "@/serverFunctions/keywords";
import type {
KeywordMode,
- ResearchSource,
ResultLimit,
} from "@/client/features/keywords/keywordResearchTypes";
@@ -175,9 +174,6 @@ export function useKeywordResearchData(
rows,
hasSearched,
lastSearchError: hasSearched && researchQuery.isError,
- lastResultSource:
- researchQuery.data?.source ?? ("related" as ResearchSource),
- lastUsedFallback: researchQuery.data?.usedFallback ?? false,
lastSearchKeyword: request?.seedKeyword ?? "",
lastSearchLocationCode: displayedLocationCode,
researchError,
diff --git a/src/client/features/keywords/keywordResearchTypes.ts b/src/client/features/keywords/keywordResearchTypes.ts
index 687c70b3..c92441e5 100644
--- a/src/client/features/keywords/keywordResearchTypes.ts
+++ b/src/client/features/keywords/keywordResearchTypes.ts
@@ -7,8 +7,6 @@ export const RESULT_LIMITS: ResultLimit[] = [150, 300, 500];
export type KeywordSource = "related" | "suggestions" | "ideas";
export type KeywordMode = "auto" | KeywordSource;
-/** Actual result source; google_ads serves countries Labs doesn't cover. */
-export type ResearchSource = KeywordSource | "google_ads";
export type KeywordFilterValues = {
include: string;
diff --git a/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx b/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx
index b273cb20..5789b843 100644
--- a/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx
+++ b/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx
@@ -86,12 +86,7 @@ export function KeywordResearchDesktopResults({ controller }: Props) {
}
function DesktopKeywordPanel({ controller }: Props) {
- const {
- lastResultSource,
- lastUsedFallback,
- searchedKeyword,
- showApproximateMatchNotice,
- } = controller;
+ const { searchedKeyword, showApproximateMatchNotice } = controller;
return (
<div className="order-2 xl:order-1 flex flex-col min-w-0 gap-2 xl:basis-3/5">
@@ -103,12 +98,6 @@ function DesktopKeywordPanel({ controller }: Props) {
No exact match for{" "}
<span className="font-medium">"{searchedKeyword}"</span>. Showing
closest related keywords instead.
- {lastUsedFallback ? (
- <span className="text-base-content/75">
- {" "}
- Source: {lastResultSource} fallback.
- </span>
- ) : null}
</div>
) : null}
{controller.overviewKeyword ? (
@@ -130,13 +119,17 @@ function DesktopTableCard({ controller }: Props) {
} = controller;
const { page, pageSize, pageRows, setPage, setPageSize } =
useKeywordResearchPagination(filteredRows);
+ const keywordCount = filteredRows.reduce(
+ (count, row) => count + 1 + row.variants.length,
+ 0,
+ );
const keywordCountLabel =
selectedRows.size > 0
? `${selectedRows.size} of ${filteredRows.length} selected`
: activeFilterCount > 0
- ? `Showing ${filteredRows.length} of ${rows.length} keywords`
- : `Showing ${filteredRows.length} keywords`;
+ ? `Showing ${keywordCount} of ${rows.length} keywords`
+ : `Showing ${keywordCount} keywords`;
const canExport = filteredRows.length > 0;
const selectedExportRows = filteredRows
diff --git a/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx b/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx
index fd14c3f1..d033869e 100644
--- a/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx
+++ b/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx
@@ -18,12 +18,13 @@ import {
} from "@/client/features/keywords/components";
import { DifficultyBadge } from "@/client/features/domain/components/DifficultyBadge";
import { formatNumber } from "@/client/features/keywords/utils";
+import type { KeywordResearchDisplayRow } from "@/client/features/keywords/groupSharedVolumeRows";
import type { KeywordResearchRow } from "@/types/keywords";
import { EmptyFilterResults } from "./keywordResearchFilters";
type Props = {
activeFilterCount: number;
- filteredRows: KeywordResearchRow[];
+ filteredRows: KeywordResearchDisplayRow[];
overviewKeyword: KeywordResearchRow | null;
selectedRows: Set<string>;
setSelectedRows: (rows: Set<string>) => void;
@@ -34,7 +35,26 @@ type Props = {
handleRowClick: (row: KeywordResearchRow) => void;
};
-const keywordColumnHelper = createColumnHelper<KeywordResearchRow>();
+/** The close variants that report the same search volume as the row above. */
+function SharedVolumeVariants({
+ variants,
+}: {
+ variants: KeywordResearchRow[];
+}) {
+ if (variants.length === 0) return null;
+ const keywords = variants.map((variant) => variant.keyword).join(", ");
+
+ return (
+ <span
+ className="block max-w-64 truncate text-xs font-normal text-base-content/50"
+ title={keywords}
+ >
+ {keywords}
+ </span>
+ );
+}
+
+const keywordColumnHelper = createColumnHelper<KeywordResearchDisplayRow>();
export function KeywordResearchDesktopTable({
activeFilterCount,
@@ -56,9 +76,9 @@ export function KeywordResearchDesktopTable({
) as RowSelectionState,
[selectedRows],
);
- const columns = useMemo<ColumnDef<KeywordResearchRow>[]>(
+ const columns = useMemo<ColumnDef<KeywordResearchDisplayRow>[]>(
() => [
- makeSelectionColumn<KeywordResearchRow>(selectAnchorRef),
+ makeSelectionColumn<KeywordResearchDisplayRow>(selectAnchorRef),
keywordColumnHelper.accessor("keyword", {
header: () => (
<SortHeader
@@ -71,12 +91,15 @@ export function KeywordResearchDesktopTable({
/>
),
cell: ({ row }) => (
- <span
- className="block min-w-48 whitespace-normal break-words font-medium capitalize md:min-w-0 md:truncate"
- title={row.original.keyword}
- >
- {row.original.keyword}
- </span>
+ <div className="min-w-48 md:min-w-0">
+ <span
+ className="block whitespace-normal break-words font-medium capitalize md:truncate"
+ title={row.original.keyword}
+ >
+ {row.original.keyword}
+ </span>
+ <SharedVolumeVariants variants={row.original.variants} />
+ </div>
),
meta: {
headerClassName: "min-w-48 md:min-w-0",
diff --git a/src/client/features/keywords/page/KeywordResearchMobileResults.tsx b/src/client/features/keywords/page/KeywordResearchMobileResults.tsx
index 489469f2..62d9f215 100644
--- a/src/client/features/keywords/page/KeywordResearchMobileResults.tsx
+++ b/src/client/features/keywords/page/KeywordResearchMobileResults.tsx
@@ -94,13 +94,17 @@ function MobileKeywordResults({ controller }: Props) {
} = controller;
const { page, pageSize, pageRows, setPage, setPageSize } =
useKeywordResearchPagination(filteredRows);
+ const keywordCount = filteredRows.reduce(
+ (count, row) => count + 1 + row.variants.length,
+ 0,
+ );
const keywordCountLabel =
selectedRows.size > 0
? `${selectedRows.size} selected`
: activeFilterCount > 0
- ? `Showing ${filteredRows.length} of ${rows.length}`
- : `Showing ${filteredRows.length} keywords`;
+ ? `Showing ${keywordCount} of ${rows.length}`
+ : `Showing ${keywordCount} keywords`;
const canExport = filteredRows.length > 0;
const selectedExportRows = filteredRows
diff --git a/src/client/features/keywords/page/KeywordResearchPagination.tsx b/src/client/features/keywords/page/KeywordResearchPagination.tsx
index cbeaf571..06b74e4c 100644
--- a/src/client/features/keywords/page/KeywordResearchPagination.tsx
+++ b/src/client/features/keywords/page/KeywordResearchPagination.tsx
@@ -89,7 +89,9 @@ function parseKeywordResearchPageSize(value: string): KeywordResearchPageSize {
);
}
-export function useKeywordResearchPagination(rows: KeywordResearchRow[]) {
+export function useKeywordResearchPagination<Row extends KeywordResearchRow>(
+ rows: Row[],
+) {
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState<KeywordResearchPageSize>(() =>
getStoredKeywordResearchPageSize(),
diff --git a/src/client/features/keywords/page/KeywordResearchSearchBar.tsx b/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
index 89d7768a..baf44ab3 100644
--- a/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
+++ b/src/client/features/keywords/page/KeywordResearchSearchBar.tsx
@@ -105,9 +105,9 @@ export function KeywordResearchSearchBar({ controller }: Props) {
}
>
<option value="auto">Auto</option>
- <option value="related">Related keywords</option>
- <option value="suggestions">Suggestions</option>
- <option value="ideas">Ideas</option>
+ <option value="suggestions">Phrase match</option>
+ <option value="ideas">Category ideas</option>
+ <option value="related">People also search for</option>
</select>
)}
</controlsForm.Field>
diff --git a/src/client/features/keywords/state/keywordControllerActions.ts b/src/client/features/keywords/state/keywordControllerActions.ts
index f11c668e..90319910 100644
--- a/src/client/features/keywords/state/keywordControllerActions.ts
+++ b/src/client/features/keywords/state/keywordControllerActions.ts
@@ -11,6 +11,10 @@ import type {
ResultLimit,
} from "@/client/features/keywords/keywordResearchTypes";
import type { KeywordResearchControllerInput } from "./useKeywordResearchController";
+import {
+ ungroupRows,
+ type KeywordResearchDisplayRow,
+} from "@/client/features/keywords/groupSharedVolumeRows";
export const KEYWORD_RESEARCH_HEADERS = [
"Keyword",
@@ -35,7 +39,7 @@ export function keywordResearchExportRow(row: KeywordResearchRow): CsvValue[] {
type SaveExportActionParams = {
selectedRows: Set<string>;
rows: KeywordResearchRow[];
- filteredRows: KeywordResearchRow[];
+ filteredRows: KeywordResearchDisplayRow[];
input: KeywordResearchControllerInput;
saveKeywordsMutate: (
variables: SaveKeywordsInput,
@@ -145,7 +149,7 @@ export function useSaveAndExportActions(params: SaveExportActionParams) {
};
const sheetsExportRows: CsvValue[][] = useMemo(
- () => filteredRows.map(keywordResearchExportRow),
+ () => ungroupRows(filteredRows).map(keywordResearchExportRow),
[filteredRows],
);
diff --git a/src/client/features/keywords/state/useKeywordResearchController.ts b/src/client/features/keywords/state/useKeywordResearchController.ts
index 392d8fa9..a272503e 100644
--- a/src/client/features/keywords/state/useKeywordResearchController.ts
+++ b/src/client/features/keywords/state/useKeywordResearchController.ts
@@ -94,8 +94,6 @@ export function useKeywordResearchController(
rows,
hasSearched,
lastSearchError,
- lastResultSource,
- lastUsedFallback,
lastSearchKeyword,
lastSearchLocationCode,
researchError,
@@ -180,6 +178,7 @@ export function useKeywordResearchController(
const { filteredRows, activeFilterCount } = useKeywordFiltering({
rows,
+ searchedKeyword,
filters: filterValues,
sortField: input.sortField,
sortDir: input.sortDir,
@@ -252,11 +251,9 @@ export function useKeywordResearchController(
history,
historyLoaded,
isLoading,
- lastResultSource,
lastSearchError,
lastSearchKeyword,
lastSearchLocationCode,
- lastUsedFallback,
mobileTab: uiState.mobileTab,
overviewKeyword,
removeHistoryItem,
diff --git a/src/server/features/keywords/services/research/helpers.test.ts b/src/server/features/keywords/services/research/helpers.test.ts
new file mode 100644
index 00000000..fbbd2423
--- /dev/null
+++ b/src/server/features/keywords/services/research/helpers.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { interleaveRows, type EnrichedKeyword } from "./helpers";
+
+const row = (
+ keyword: string,
+ overrides: Partial<EnrichedKeyword> = {},
+): EnrichedKeyword => ({
+ keyword,
+ searchVolume: 1000,
+ trend: [{ year: 2026, month: 7, searchVolume: 1000 }],
+ cpc: 1.5,
+ 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"]);
+ });
+});
diff --git a/src/server/features/keywords/services/research/helpers.ts b/src/server/features/keywords/services/research/helpers.ts
index 42f9efed..4ccf4ee7 100644
--- a/src/server/features/keywords/services/research/helpers.ts
+++ b/src/server/features/keywords/services/research/helpers.ts
@@ -1,19 +1,36 @@
-import type { KeywordIntent, MonthlySearch } from "@/types/keywords";
+import type { KeywordIntent, KeywordResearchRow } from "@/types/keywords";
-export type EnrichedKeyword = {
- keyword: string;
- searchVolume: number | null;
- trend: MonthlySearch[];
- cpc: number | null;
- competition: number | null;
- keywordDifficulty: number | null;
- intent: KeywordIntent;
-};
+export type EnrichedKeyword = KeywordResearchRow;
export function normalizeKeyword(input: string): string {
return input.trim().toLowerCase();
}
+/**
+ * Alternates rows from two sources into one list, deduping by keyword, so a
+ * volume-sorted source can't crowd out the other before the limit is reached.
+ */
+export function interleaveRows(
+ first: EnrichedKeyword[],
+ second: EnrichedKeyword[],
+ limit: number,
+): EnrichedKeyword[] {
+ const rows: EnrichedKeyword[] = [];
+ const seen = new Set<string>();
+ const longest = Math.max(first.length, second.length);
+
+ for (let i = 0; i < longest && rows.length < limit; i++) {
+ for (const source of [first, second]) {
+ const row = source[i];
+ if (!row || seen.has(row.keyword) || rows.length >= limit) continue;
+ seen.add(row.keyword);
+ rows.push(row);
+ }
+ }
+
+ return rows;
+}
+
export function normalizeIntent(raw: string | null | undefined): KeywordIntent {
if (!raw) return "unknown";
const value = raw.toLowerCase();
diff --git a/src/server/features/keywords/services/research/research.test.ts b/src/server/features/keywords/services/research/research.test.ts
new file mode 100644
index 00000000..3cf56349
--- /dev/null
+++ b/src/server/features/keywords/services/research/research.test.ts
@@ -0,0 +1,116 @@
+import { expect, it, vi } from "vitest";
+import type { KeywordResearchRow } from "@/types/keywords";
+import { EMPTY_FILTERS } from "@/client/features/keywords/keywordResearchTypes";
+import { applyKeywordFiltersAndSort } from "@/client/features/keywords/hooks/useKeywordFiltering";
+import { buildCacheKey } from "@/server/lib/r2-cache";
+import { research } from "./research";
+
+const mocks = vi.hoisted(() => ({
+ cache: new Map<string, string>(),
+ fetchRows: vi.fn(),
+ upsertKeywordMetric: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("cloudflare:workers", () => ({
+ env: {
+ R2: {
+ get: async (key: string) => {
+ const value = mocks.cache.get(key);
+ return value === undefined ? null : { text: async () => value };
+ },
+ put: async (key: string, value: string) => mocks.cache.set(key, value),
+ },
+ },
+}));
+vi.mock("./research-data", () => ({
+ fetchResearchRowsBySource: mocks.fetchRows,
+ fetchGoogleAdsResearchRows: vi.fn(),
+}));
+vi.mock(
+ "@/server/features/keywords/repositories/KeywordResearchRepository",
+ () => ({
+ KeywordResearchRepository: {
+ upsertKeywordMetric: mocks.upsertKeywordMetric,
+ },
+ }),
+);
+
+it("keeps shared-volume keywords independently filterable through research and cache", async () => {
+ const seed: KeywordResearchRow = {
+ keyword: "caregiving",
+ searchVolume: 110000,
+ trend: [
+ { year: 2026, month: 6, searchVolume: 90500 },
+ { year: 2026, month: 7, searchVolume: 110000 },
+ ],
+ cpc: 8.25,
+ competition: 0.4,
+ keywordDifficulty: 60,
+ intent: "informational",
+ };
+ const opportunity: KeywordResearchRow = {
+ ...seed,
+ keyword: "caregiver",
+ keywordDifficulty: 20,
+ intent: "commercial",
+ };
+ const siblings = [
+ "respite care",
+ "elder care",
+ "adult day care",
+ "care home",
+ ].map((keyword) => ({ ...seed, keyword, searchVolume: 500 }));
+ mocks.fetchRows.mockImplementation(async ({ source }) =>
+ source === "suggestions" ? [seed] : [opportunity, ...siblings],
+ );
+ const input = {
+ projectId: "project_1",
+ keywords: ["caregiving"],
+ locationCode: 2840,
+ languageCode: "en",
+ resultLimit: 150 as const,
+ mode: "auto" as const,
+ clickstream: false,
+ };
+ const customer = {
+ organizationId: "org_1",
+ userId: "user_1",
+ userEmail: "[email protected]",
+ };
+ // An older cached grouping must not hide the opportunity after this fix.
+ const oldKey = await buildCacheKey("kw:research", {
+ ...input,
+ cacheVersion: 4,
+ organizationId: customer.organizationId,
+ depth: 3,
+ });
+ mocks.cache.set(
+ `dataforseo-cache/${oldKey}`,
+ JSON.stringify({
+ rows: [{ ...seed, closeVariants: [opportunity.keyword] }],
+ source: "blended",
+ usedFallback: false,
+ }),
+ );
+
+ const fresh = await research(input, customer);
+ const cached = await research(input, customer);
+ expect(mocks.fetchRows).toHaveBeenCalledTimes(2);
+ expect(cached).toEqual(fresh);
+ expect(fresh.rows).toContainEqual(opportunity);
+ expect(fresh.source).toBe("blended");
+ expect(mocks.upsertKeywordMetric).toHaveBeenCalledWith(
+ expect.objectContaining({
+ keyword: "caregiver",
+ keywordDifficulty: 20,
+ intent: "commercial",
+ }),
+ );
+ const filtered = applyKeywordFiltersAndSort({
+ rows: cached.rows,
+ filters: { ...EMPTY_FILTERS, maxKd: "30", intents: "commercial" },
+ sortField: "keyword",
+ sortDir: "asc",
+ });
+ expect(filtered).toEqual([opportunity]);
+});
diff --git a/src/server/features/keywords/services/research/research.ts b/src/server/features/keywords/services/research/research.ts
index 248627f1..91a3ae40 100644
--- a/src/server/features/keywords/services/research/research.ts
+++ b/src/server/features/keywords/services/research/research.ts
@@ -12,38 +12,27 @@ import type { KeywordResearchRow } from "@/types/keywords";
import type { ResolvedResearchKeywordsInput } from "@/types/schemas/keywords";
import { z } from "zod";
import { getKeywordDataProvider } from "@/shared/keyword-locations";
-import { type EnrichedKeyword, normalizeKeyword } from "./helpers";
+import {
+ interleaveRows,
+ normalizeKeyword,
+ type EnrichedKeyword,
+} from "./helpers";
import {
fetchGoogleAdsResearchRows,
fetchResearchRowsBySource,
} from "./research-data";
import {
- AUTO_KEYWORD_SOURCES,
MIN_NON_SEED_FOR_AUTO,
countNonSeedKeywords,
- hasSufficientCoverage,
type KeywordMode,
type KeywordSource,
type ResearchSource,
} from "./selection";
-type SourceAttempt = {
- source: ResearchSource;
- rowCount: number;
- nonSeedCount: number;
-};
-
-type ResearchDiagnostics = {
- requestedMode: KeywordMode;
- threshold: number;
- sourceAttempts: SourceAttempt[];
-};
-
type ResearchResult = {
rows: KeywordResearchRow[];
source: ResearchSource;
usedFallback: boolean;
- diagnostics: ResearchDiagnostics;
};
type CachedResult = ResearchResult;
@@ -70,33 +59,22 @@ const cachedKeywordRowSchema = z.object({
]),
});
-const sourceAttemptSchema = z.object({
- source: z.enum(["related", "suggestions", "ideas", "google_ads"]),
- rowCount: z.number(),
- nonSeedCount: z.number(),
-});
-
const cachedResultSchema = z.object({
rows: z.array(cachedKeywordRowSchema),
- source: z.enum(["related", "suggestions", "ideas", "google_ads"]),
+ source: z.enum(["related", "suggestions", "ideas", "google_ads", "blended"]),
usedFallback: z.boolean(),
- diagnostics: z.object({
- requestedMode: z.enum(["auto", "related", "suggestions", "ideas"]),
- threshold: z.number(),
- sourceAttempts: z.array(sourceAttemptSchema),
- }),
});
-// v3: research volumes are no longer clickstream-refined, and Google-Ads-only
-// locations route to keywords_for_keywords.
-const CACHE_VERSION = 3;
+// v5: auto mode blends suggestions + ideas. v4 (collapsed close variants)
+// only ran in previews; skip it so those entries are never reused.
+const CACHE_VERSION = 5;
async function fetchRowsFromSource(
source: KeywordSource,
input: ResolvedResearchKeywordsInput,
seedKeyword: string,
billingCustomer: BillingCustomerContext,
- creditFeature?: CreditFeature,
+ opts: { creditFeature?: CreditFeature; resultLimit?: number } = {},
): Promise<EnrichedKeyword[]> {
return fetchResearchRowsBySource(
{
@@ -104,73 +82,83 @@ async function fetchRowsFromSource(
seedKeyword,
locationCode: input.locationCode,
languageCode: input.languageCode,
- resultLimit: input.resultLimit,
+ resultLimit: opts.resultLimit ?? input.resultLimit,
includeClickstreamData: input.clickstream,
- creditFeature,
+ creditFeature: opts.creditFeature,
},
billingCustomer,
);
}
+/**
+ * Auto blends phrase-match suggestions with category-level ideas, half the
+ * limit each. Neither works as a sole default: suggestions miss sibling head
+ * terms ("respite care" for "caregiving") and ideas drift toward generic
+ * category terms. The old related-first behavior is worse than both — its
+ * depth-3 "people also search for" graph is tiny for broad seeds and full of
+ * SERP-adjacency noise — so related is only a fallback for obscure seeds
+ * where the blend comes back thin.
+ */
async function fetchAutoRows(
input: ResolvedResearchKeywordsInput,
seedKeyword: string,
billingCustomer: BillingCustomerContext,
creditFeature?: CreditFeature,
): Promise<ResearchResult> {
- const attempts: SourceAttempt[] = [];
- let lastSource: KeywordSource = "related";
- const accumulatedRows: EnrichedKeyword[] = [];
- const seenKeywords = new Set<string>();
-
- for (const source of AUTO_KEYWORD_SOURCES) {
- const rows = await fetchRowsFromSource(
- source,
+ const blendOpts = {
+ creditFeature,
+ resultLimit: Math.ceil(input.resultLimit / 2),
+ };
+ // Settled, not Promise.all: each call meters its own DataForSEO spend, and
+ // workerd cancels in-flight I/O once a response is sent, so throwing while
+ // the sibling call is mid-flight can drop its billing write.
+ const [suggestions, ideas] = await Promise.allSettled([
+ fetchRowsFromSource(
+ "suggestions",
input,
seedKeyword,
billingCustomer,
- creditFeature,
- );
- for (const row of rows) {
- if (accumulatedRows.length >= input.resultLimit) break;
- if (seenKeywords.has(row.keyword)) continue;
- seenKeywords.add(row.keyword);
- accumulatedRows.push(row);
+ blendOpts,
+ ),
+ fetchRowsFromSource(
+ "ideas",
+ input,
+ seedKeyword,
+ billingCustomer,
+ blendOpts,
+ ),
+ ]);
+ if (suggestions.status === "rejected") {
+ if (ideas.status === "rejected") {
+ console.warn("keywords.research.ideas-leg failed:", ideas.reason);
}
+ throw suggestions.reason;
+ }
+ if (ideas.status === "rejected") throw ideas.reason;
+ const blended = interleaveRows(
+ suggestions.value,
+ ideas.value,
+ input.resultLimit,
+ );
- attempts.push({
- source,
- rowCount: rows.length,
- nonSeedCount: countNonSeedKeywords(rows, seedKeyword),
- });
-
- lastSource = source;
-
- if (
- hasSufficientCoverage(accumulatedRows, seedKeyword, MIN_NON_SEED_FOR_AUTO)
- ) {
- return {
- rows: accumulatedRows,
- source,
- usedFallback: source !== AUTO_KEYWORD_SOURCES[0],
- diagnostics: {
- requestedMode: "auto",
- threshold: MIN_NON_SEED_FOR_AUTO,
- sourceAttempts: attempts,
- },
- };
- }
+ if (countNonSeedKeywords(blended, seedKeyword) >= MIN_NON_SEED_FOR_AUTO) {
+ return { rows: blended, source: "blended", usedFallback: false };
}
+ const related = await fetchRowsFromSource(
+ "related",
+ input,
+ seedKeyword,
+ billingCustomer,
+ {
+ creditFeature,
+ },
+ );
+
return {
- rows: accumulatedRows,
- source: lastSource,
+ rows: interleaveRows(blended, related, input.resultLimit),
+ source: "blended",
usedFallback: true,
- diagnostics: {
- requestedMode: "auto",
- threshold: MIN_NON_SEED_FOR_AUTO,
- sourceAttempts: attempts,
- },
};
}
@@ -191,22 +179,7 @@ async function fetchGoogleAdsRows(
billingCustomer,
);
- return {
- rows,
- source: "google_ads",
- usedFallback: false,
- diagnostics: {
- requestedMode: "auto",
- threshold: MIN_NON_SEED_FOR_AUTO,
- sourceAttempts: [
- {
- source: "google_ads",
- rowCount: rows.length,
- nonSeedCount: countNonSeedKeywords(rows, seedKeyword),
- },
- ],
- },
- };
+ return { rows, source: "google_ads", usedFallback: false };
}
async function fetchManualRows(
@@ -221,24 +194,11 @@ async function fetchManualRows(
input,
seedKeyword,
billingCustomer,
- creditFeature,
- );
- const attempt: SourceAttempt = {
- source: mode,
- rowCount: rows.length,
- nonSeedCount: countNonSeedKeywords(rows, seedKeyword),
- };
-
- return {
- rows,
- source: mode,
- usedFallback: false,
- diagnostics: {
- requestedMode: mode,
- threshold: MIN_NON_SEED_FOR_AUTO,
- sourceAttempts: [attempt],
+ {
+ creditFeature,
},
- };
+ );
+ return { rows, source: mode, usedFallback: false };
}
async function buildResearchCacheKey(
diff --git a/src/server/features/keywords/services/research/selection.ts b/src/server/features/keywords/services/research/selection.ts
index e5d00f6f..1a251d0b 100644
--- a/src/server/features/keywords/services/research/selection.ts
+++ b/src/server/features/keywords/services/research/selection.ts
@@ -4,15 +4,10 @@ export type KeywordSource = "related" | "suggestions" | "ideas";
export type KeywordMode = "auto" | KeywordSource;
/**
* Where research rows actually came from. "google_ads" is not requestable as
- * a mode; it's the automatic source for countries Labs doesn't support.
+ * a mode (it's the automatic source for countries Labs doesn't support), and
+ * "blended" is auto mode's suggestions + ideas mix.
*/
-export type ResearchSource = KeywordSource | "google_ads";
-
-export const AUTO_KEYWORD_SOURCES: KeywordSource[] = [
- "related",
- "suggestions",
- "ideas",
-];
+export type ResearchSource = KeywordSource | "google_ads" | "blended";
export const MIN_NON_SEED_FOR_AUTO = 5;
@@ -23,11 +18,3 @@ export function countNonSeedKeywords(
const normalizedSeed = seedKeyword.trim().toLowerCase();
return rows.filter((row) => row.keyword !== normalizedSeed).length;
}
-
-export function hasSufficientCoverage(
- rows: EnrichedKeyword[],
- seedKeyword: string,
- threshold: number = MIN_NON_SEED_FOR_AUTO,
-): boolean {
- return countNonSeedKeywords(rows, seedKeyword) >= threshold;
-}
diff --git a/src/server/mcp/tools/research-keywords.ts b/src/server/mcp/tools/research-keywords.ts
index cb757a20..757e4940 100644
--- a/src/server/mcp/tools/research-keywords.ts
+++ b/src/server/mcp/tools/research-keywords.ts
@@ -35,7 +35,9 @@ const inputSchema = {
resultLimit: z
.union([z.literal(150), z.literal(300), z.literal(500)])
.optional()
- .describe("Max keywords returned per seed. Defaults to 150."),
+ .describe(
+ "Max keywords returned per seed. Defaults to 150. Auto mode blends two sources; duplicate keywords across sources appear once.",
+ ),
includeClickstreamData: z
.boolean()
.optional()
@@ -86,7 +88,7 @@ export const researchKeywordsTool = {
config: {
title: "Research keywords (bulk)",
description:
- "Research keyword data (search volume, difficulty, CPC, related ideas) for 1-5 seed keywords in one call. Charges credits per seed (~30-100 credits each, varies by source; flat ~96 for countries served from Google Ads data, where difficulty/intent are unavailable). Returns per-seed results — a single bad seed won't fail the batch.",
+ "Research keyword data (search volume, difficulty, CPC, related ideas) for 1-5 seed keywords in one call. Charges credits per seed (~54 at the default result limit, ~110 at 500, plus ~40 more (~95 at 500) when an obscure seed needs a fallback lookup; flat ~96 for countries served from Google Ads data, where difficulty/intent are unavailable). Returns per-seed results — a single bad seed won't fail the batch.",
inputSchema,
outputSchema: z.looseObject({
results: z.array(
@@ -172,7 +174,7 @@ export const researchKeywordsTool = {
return `${header}\n${formatMcpTable(r.rows, RESEARCH_COLUMNS)}`;
})
.join("\n\n") +
- `\n\nResearched ${okCount} of ${results.length} seeds${failCount > 0 ? ` (${failCount} failed)` : ""}. Columns: volume = monthly searches, KD = keyword difficulty (0-100), CPC in USD, competition = paid competition (0-1); "—" = unavailable.`;
+ `\n\nResearched ${okCount} of ${results.length} seeds${failCount > 0 ? ` (${failCount} failed)` : ""}. Columns: volume = monthly searches, KD = keyword difficulty (0-100), CPC in USD, competition = paid competition (0-1); "—" = unavailable. Google Ads close variants may share search volumes; do not add their volumes together.`;
return mcpResponse({
text,
diff --git a/web/src/routes/_marketing/pricing.tsx b/web/src/routes/_marketing/pricing.tsx
index 4a7865bd..2b66e936 100644
--- a/web/src/routes/_marketing/pricing.tsx
+++ b/web/src/routes/_marketing/pricing.tsx
@@ -42,9 +42,12 @@ const RAW_COST_USD = {
// Scheduled checks use the queued API. The app defaults to one device and
// the top 40 results: $0.0006 for page one + $0.00045 per extra page.
rankCheck: 0.0006 + (DEFAULT_RANK_DEPTH / 10 - 1) * 0.00045,
- // A 150–300 result Labs search is currently $0.030–$0.048 raw. Use the
- // midpoint so the customer estimate is a memorable $0.05 per search.
- keywordLabs: 0.039,
+ // Labs live costs $0.012/task + $0.00012/row (measured Sep 2026). Auto mode
+ // blends two half-limit calls (suggestions + ideas), so the default
+ // 150-result search is 2 x (0.012 + 75 x 0.00012) = $0.042; 300 results is
+ // $0.060 and 500 is $0.084. Price the default, which is what nearly every
+ // search uses.
+ keywordLabs: 0.042,
// The MCP-only local SERP tool defaults to a live Google Maps/Local Finder
// request with 20 results: $0.002 for page one + $0.0015 for page two.
localSerp: 0.002 + (DEFAULT_LOCAL_SERP_DEPTH / 10 - 1) * 0.0015,
@@ -68,7 +71,7 @@ function creditsForRaw(rawUsd: number): number {
// Credits charged per unit of each action (computed once from the model above).
const CREDITS_PER_UNIT = {
- keywordLabs: creditsForRaw(RAW_COST_USD.keywordLabs), // 50
+ keywordLabs: creditsForRaw(RAW_COST_USD.keywordLabs), // 54
localSerp: creditsForRaw(RAW_COST_USD.localSerp), // 5
backlinkProfile: creditsForRaw(RAW_COST_USD.backlinkProfile), // 79
aiCitation: creditsForRaw(RAW_COST_USD.aiCitationPerPlatform), // 1088
@@ -98,7 +101,7 @@ const PRESETS: Record<"business" | "freelancer", Inputs> = {
backlinks: 20,
aiScans: 0,
},
- // About $25/mo of usage: an agency checking 15 client sites weekly.
+ // About $27/mo of usage: an agency checking 15 client sites weekly.
freelancer: {
sites: 15,
keywordsPerSite: 20,