Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): pick a draft's shopping path from the brand's catalog (shopping path, part 2) (#1588)

Cihan0e9c1fa9dcad
diff --git a/server/src/lib/catalog/__fixtures__/fake-db.js b/server/src/lib/catalog/__fixtures__/fake-db.js
index d7b658ac1..008d68dc1 100644
--- a/server/src/lib/catalog/__fixtures__/fake-db.js
+++ b/server/src/lib/catalog/__fixtures__/fake-db.js
@@ -1,10 +1,35 @@
import { randomUUID } from 'node:crypto';
+/** A row's value at a column, or at a JSON path in it as PostgREST reads one (`shopping_path->>builtAt`). */
+function valueAt(row, column) {
+ const at = column.indexOf('->>');
+ if (at < 0) return row[column];
+ const value = row[column.slice(0, at)]?.[column.slice(at + 3)];
+ if (value == null) return null;
+ return typeof value === 'string' ? value : JSON.stringify(value);
+}
+
+/** PostgreSQL's order: ascending puts nulls last, descending first, unless told. */
+function compareBy(orders) {
+ return (a, b) => {
+ for (const { column, ascending = true, nullsFirst = !ascending } of orders) {
+ if (a[column] === b[column]) continue;
+ if (a[column] == null) return nullsFirst ? -1 : 1;
+ if (b[column] == null) return nullsFirst ? 1 : -1;
+ const before = a[column] < b[column] ? -1 : 1;
+ return ascending ? before : -before;
+ }
+ return 0;
+ };
+}
+
/**
* An in-memory stand-in for the tables the catalog writes, with PostgREST's
* calls as the sync and the sources make them, counting every write.
+ * `maxRows` caps a read as PostgREST's max_rows does (1000 in
+ * supabase/config.toml): the rest are dropped without an error.
*/
-export function fakeDb() {
+export function fakeDb({ maxRows = Infinity } = {}) {
const tables = new Map();
const rows = (name) => {
if (!tables.has(name)) tables.set(name, []);
@@ -32,19 +57,22 @@ export function fakeDb() {
payload: null,
returning: null,
one: null,
+ order: [],
};
const run = () => {
const all = rows(table);
const match = (row) =>
state.filters.every(([kind, column, value]) => {
- if (kind === 'eq') return row[column] === value;
- if (kind === 'neq') return row[column] !== value;
- return value.includes(row[column]);
+ const at = valueAt(row, column);
+ if (kind === 'eq') return at === value;
+ if (kind === 'neq') return at !== value;
+ if (kind === 'is') return value === null ? at == null : at === value;
+ return value.includes(at);
});
if (state.op === 'select') {
- const found = all.filter(match).sort((a, b) => (a.id < b.id ? -1 : 1));
+ const found = all.filter(match).sort(compareBy([...state.order, { column: 'id' }]));
const [start, end] = state.range ?? [0, found.length];
- const data = found.slice(start, end + 1);
+ const data = found.slice(start, end + 1).slice(0, state.one ? undefined : maxRows);
if (state.one) return { data: data[0] ?? null, error: null };
return { data, error: null };
}
@@ -74,8 +102,9 @@ export function fakeDb() {
return { data: state.one ? added[0] : null, error: null };
}
if (state.op === 'update') {
- for (const row of all.filter(match)) Object.assign(row, state.payload);
- return { data: null, error: null };
+ const changed = all.filter(match);
+ for (const row of changed) Object.assign(row, state.payload);
+ return { data: state.returning ? changed : null, error: null };
}
if (state.op === 'delete') {
tables.set(
@@ -87,7 +116,11 @@ export function fakeDb() {
throw new Error(`unexpected ${state.op}`);
};
const builder = {
- select: () => builder,
+ // After a write, the rows it wrote, as PostgREST returns them.
+ select: () => {
+ if (state.op !== 'select') state.returning = true;
+ return builder;
+ },
eq: (column, value) => {
state.filters.push(['eq', column, value]);
return builder;
@@ -96,6 +129,10 @@ export function fakeDb() {
state.filters.push(['neq', column, value]);
return builder;
},
+ is: (column, value) => {
+ state.filters.push(['is', column, value]);
+ return builder;
+ },
single: () => {
state.one = 'single';
return builder;
@@ -108,7 +145,10 @@ export function fakeDb() {
state.filters.push(['in', column, values]);
return builder;
},
- order: () => builder,
+ order: (column, options) => {
+ state.order.push({ column, ...options });
+ return builder;
+ },
// The sweep's due filter: the tests' rows are all due.
or: () => builder,
limit: (n) => {
diff --git a/server/src/lib/catalog/stock.js b/server/src/lib/catalog/stock.js
new file mode 100644
index 000000000..afdcdca06
--- /dev/null
+++ b/server/src/lib/catalog/stock.js
@@ -0,0 +1,23 @@
+/**
+ * A catalog variant's stock, read one way everywhere: as the editor's feed
+ * match reads it (web/src/lib/content/feed-match.ts, feedStock) and as
+ * catalog_category_counts (00350) counts it. Feeds and stores spell it many
+ * ways ("in stock", "IN_STOCK", "limited-availability"), so it is read
+ * lowercased, with spaces and hyphens as "_". stock.test.js checks the three
+ * lists stay the same.
+ */
+
+/** The availabilities that are in stock, as `stockKey` spells them. */
+export const IN_STOCK = ['in_stock', 'instock', 'available', 'limited_availability'];
+
+/** A variant's availability lowercased, spaces and hyphens as "_": "In Stock" → "in_stock". */
+export function stockKey(availability) {
+ return String(availability ?? '')
+ .toLowerCase()
+ .replace(/[\s-]+/g, '_');
+}
+
+/** Whether a variant's availability is in stock. */
+export function isInStock(availability) {
+ return IN_STOCK.includes(stockKey(availability));
+}
diff --git a/server/src/lib/catalog/stock.test.js b/server/src/lib/catalog/stock.test.js
new file mode 100644
index 000000000..1dbe39ac8
--- /dev/null
+++ b/server/src/lib/catalog/stock.test.js
@@ -0,0 +1,40 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import { IN_STOCK, isInStock, stockKey } from './stock.js';
+
+/** A catalog variant's stock, one way everywhere (shopping path). */
+
+describe('isInStock', () => {
+ it('reads a feed\'s or a store\'s spelling of "in stock", whatever its case, spaces or hyphens', () => {
+ for (const value of [
+ 'in_stock',
+ 'In Stock',
+ 'IN_STOCK',
+ 'instock',
+ 'available',
+ 'limited_availability',
+ 'Limited-Availability',
+ ]) {
+ expect(isInStock(value)).toBe(true);
+ }
+ for (const value of ['out_of_stock', 'out of stock', 'preorder', 'backorder', '', null]) {
+ expect(isInStock(value)).toBe(false);
+ }
+ expect(stockKey('Limited Availability')).toBe('limited_availability');
+ });
+
+ it("is the editor's feed match's list and catalog_category_counts' (00350), read the same way", () => {
+ const read = (path) => readFileSync(new URL(`../../../../${path}`, import.meta.url), 'utf8');
+ const words = (list) => [...list.matchAll(/'([a-z_]+)'/g)].map((m) => m[1]);
+ const web = read('web/src/lib/content/feed-match.ts');
+ const sql = read('supabase/migrations/00350_catalog_category_pages.sql');
+ expect(words(web.match(/return \[([^\]]*)\]\.includes\(a\)/)[1])).toEqual(IN_STOCK);
+ expect(words(sql.match(/'_', 'g'\)\)\s+in \(([^)]*)\)/)[1])).toEqual(IN_STOCK);
+ // Lowercased, spaces and hyphens as "_", on all three sides.
+ expect(web).toMatch(/toLowerCase\(\)\.replace\(\/\[\\s-\]\+\/g, '_'\)/);
+ expect(sql).toMatch(/lower\(regexp_replace\(v\.availability, '\[\\s-\]\+', '_', 'g'\)\)/);
+ expect(
+ readFileSync(new URL('./stock.js', import.meta.url), 'utf8').replace(/\s+/g, ''),
+ ).toContain(".toLowerCase().replace(/[\\s-]+/g,'_')");
+ });
+});
diff --git a/server/src/lib/shopping-path.js b/server/src/lib/shopping-path.js
new file mode 100644
index 000000000..b114458f6
--- /dev/null
+++ b/server/src/lib/shopping-path.js
@@ -0,0 +1,636 @@
+import { z } from 'zod';
+import supabaseAdmin from '../config/supabase.js';
+import { categoryPages, leafName, wordsOf } from './catalog/category-pages.js';
+import { isInStock, stockKey } from './catalog/stock.js';
+import { selectInChunks } from './chunked-in.js';
+import { siteTypeOf } from './content-page-types.js';
+import { logger } from './logger.js';
+import { readAllRpcRows } from './rpc-pages.js';
+
+/**
+ * A draft's shopping path (shopping path, 00351): on an online shop, the
+ * category pages and the catalog products a buying guide, a best-of list or
+ * a comparison links, so its readers, and the AI answers that quote it,
+ * reach a page that sells.
+ *
+ * Picked from the brand's catalog for the draft's topic: its title, the
+ * brief's keywords, goal and headings. A category is a candidate when it has
+ * a page on the site (catalog/category-pages.js) and products in stock; a
+ * product when it has a link, a variant in stock, and Google Merchant
+ * Center doesn't refuse that variant in its free listings
+ * (catalog_item_issues, see `refuses`). Products of the picked categories
+ * come first. The best products the rules leave out are kept with why (sold
+ * out, refused, no link, gone from the catalog), for the Brief tab to say so.
+ *
+ * A rebuild keeps the person's choices: locked and added products stay
+ * whatever their score, removed ones never come back.
+ */
+
+/** The page types a shopping path fits, and how many products each links. */
+export const PRODUCTS_FOR = {
+ best_of: 8,
+ buying_guide: 5,
+ comparison: 4,
+ alternatives: 4,
+ guide: 4,
+ blog_post: 3,
+};
+/** Category pages a path links at most. */
+export const MAX_CATEGORIES = 2;
+/** Products read to score, at most, and scored products read in full. */
+export const SCORED_PRODUCTS = 2000;
+export const DETAILED_PRODUCTS = 40;
+/** Products left out a path keeps, with why: the best of the others, and the person's own. */
+export const LEFT_OUT = 3;
+/**
+ * The path's caps, the Brief tab's schema's (web/src/lib/content/shopping-path.ts):
+ * products, issues a product, left out, the person's locks and additions, and removals.
+ */
+export const MAX_PRODUCTS = 40;
+export const MAX_ISSUES = 20;
+export const MAX_LEFT_OUT = 10;
+export const MAX_KEPT = 40;
+export const MAX_REMOVED = 200;
+/** A product's or a page's title in the path, in characters at most. */
+export const TITLE_CHARS = 200;
+/** The path's size at most, under the column's 64 KB (00351) with room to spare. */
+export const MAX_PATH_BYTES = 64000;
+/** Characters of a product's description kept to score, and its words scored, as AI shopping reads its opening. */
+const DESCRIPTION_CHARS = 400;
+const DESCRIPTION_WORDS = 40;
+
+/**
+ * Words that say what kind of page it is, or join others, and not what it
+ * is about: "How to choose the best waterproof boots" is about "waterproof"
+ * and "boots". Read as `wordsOf` reads them (folded, a plural's "s" dropped).
+ * "Top" and "pick" name products too (a shop's tops, guitar picks): only
+ * "top 10" is dropped, by TOP_N.
+ */
+const NOT_TOPIC = new Set(
+ wordsOf(
+ [
+ 'how to choose choosing best guide guides buying buyer buyers buy',
+ 'vs versus compare compared comparing comparison comparisons review reviews reviewed',
+ 'alternative alternatives list ranked rated ultimate complete tips ideas',
+ 'the a an for and or with without of in on at by from to into about',
+ 'your you our my we is are be what which why when where who should can do does',
+ 'it its this that these those than vs new latest year',
+ 'en iyi nasil secilir secimi rehber rehberi icin ve ile karsilastirma',
+ ].join(' '),
+ ),
+);
+/** A year ("2026") dates a list; it isn't what the list is about. */
+const YEAR = /^(19|20)\d\d$/;
+/** A list's size: "Top 10", "top-5". */
+const TOP_N = /\btop[\s-]*\d+\b/gi;
+
+/**
+ * The draft's topic as weighted words: the title's count 3, the brief's
+ * keywords 2, its goal and headings 1.
+ *
+ * @returns {Map<string, number>}
+ */
+export function topicWords({ title, brief }) {
+ const words = new Map();
+ const add = (text, weight) => {
+ for (const word of wordsOf(String(text ?? '').replace(TOP_N, ' '))) {
+ if (NOT_TOPIC.has(word) || YEAR.test(word)) continue;
+ words.set(word, Math.max(words.get(word) ?? 0, weight));
+ }
+ };
+ for (const heading of brief?.outline ?? []) add(heading?.heading, 1);
+ add(brief?.goal, 1);
+ for (const keyword of brief?.keywords ?? []) add(keyword, 2);
+ add(title, 3);
+ return words;
+}
+
+/** How much of the topic a text holds: the weights of its topic words, each once. */
+export function topicScore(topic, text) {
+ let score = 0;
+ for (const word of new Set(wordsOf(text))) score += topic.get(word) ?? 0;
+ return score;
+}
+
+/** A title as the path keeps it: TITLE_CHARS at most. */
+function titleOf(title) {
+ return title == null ? null : String(title).slice(0, TITLE_CHARS);
+}
+
+/**
+ * The categories to link: with a page and products in stock, the best for
+ * the topic first; a second one only when it scores half the first's.
+ */
+export function pickCategories(categories, topic, max = MAX_CATEGORIES) {
+ const scored = categories
+ .filter((c) => c.page && c.inStock > 0)
+ .map((c) => ({
+ category: c,
+ score: topicScore(topic, leafName(c.name)) * 2 + topicScore(topic, c.page.title ?? ''),
+ }))
+ .filter((c) => c.score > 0)
+ .sort((a, b) => b.score - a.score || b.category.inStock - a.category.inStock);
+ if (!scored.length) return [];
+ const top = scored[0].score;
+ return scored
+ .filter((c, i) => i === 0 || c.score >= top / 2)
+ .slice(0, max)
+ .map(({ category }) => ({
+ name: category.name,
+ url: category.page.url,
+ title: titleOf(category.page.title),
+ }));
+}
+
+/**
+ * Whether a Merchant Center issue refuses the variant. Decision: only a
+ * disapproval in the free listings (reporting_context FREE_LISTINGS), or
+ * one that names no context, does. AI shopping answers draw on the free,
+ * organic listings; a disapproval for ads (SHOPPING_ADS, DISPLAY_ADS…)
+ * leaves the product there, so it is listed as the other issues are.
+ */
+export function refuses(issue) {
+ if (issue.severity !== 'disapproved') return false;
+ const context = String(issue.reporting_context ?? '')
+ .trim()
+ .toUpperCase();
+ return context === '' || context === 'FREE_LISTINGS';
+}
+
+/**
+ * A product as the path offers it, or why it can't be: a variant in stock
+ * that Merchant Center doesn't refuse, its lowest price, and the issues
+ * Merchant Center reports for it that don't refuse it.
+ */
+export function offerOf(product) {
+ const url = product.url ?? product.variants.find((v) => v.url)?.url ?? null;
+ const inStock = product.variants.filter((v) => isInStock(v.availability));
+ const usable = inStock.filter((v) => !v.issues.some(refuses));
+ const reason = !url
+ ? 'no_link'
+ : !inStock.length
+ ? 'sold_out'
+ : !usable.length
+ ? 'refused'
+ : null;
+ if (reason) return { reason };
+ const cheapest = usable
+ .filter((v) => v.price != null)
+ .sort((a, b) => (a.sale_price ?? a.price) - (b.sale_price ?? b.price))[0];
+ const variant = cheapest ?? usable[0];
+ const issues = [
+ ...new Map(
+ variant.issues.map((i) => [
+ `${i.code}|${i.attribute ?? ''}`,
+ { code: i.code, attribute: i.attribute ?? null },
+ ]),
+ ).values(),
+ ].slice(0, MAX_ISSUES);
+ return {
+ offer: {
+ id: product.id,
+ title: titleOf(product.title),
+ url,
+ price: variant.price ?? null,
+ salePrice: variant.sale_price ?? null,
+ currency: variant.currency ?? null,
+ // As stock.js spells it: "limited_availability" whatever the feed wrote.
+ availability: stockKey(variant.availability),
+ image: product.image ?? null,
+ issues,
+ },
+ };
+}
+
+/** A product's score for the topic: its title twice, its type, its description's opening. */
+export function productScore(topic, product) {
+ const opening = String(product.description ?? '')
+ .split(/\s+/)
+ .slice(0, DESCRIPTION_WORDS)
+ .join(' ');
+ return (
+ topicScore(topic, product.title) * 2 +
+ topicScore(topic, product.product_type ?? '') +
+ topicScore(topic, opening)
+ );
+}
+
+/**
+ * The products to link, the best for the topic first: `max` of them, the
+ * person's locked and added ones first and counted in it (all of them
+ * when there are more, MAX_PRODUCTS at most), removed ones never; and
+ * those left out, with why: the person's own, and the best LEFT_OUT of the
+ * others. `scored` items carry the product, its `score` and `offerOf`
+ * result ({ reason: 'gone' } for a kept product the catalog no longer has).
+ */
+export function pickProducts(scored, { max, locked = [], removed = [], added = [] }) {
+ const keep = new Set([...locked, ...added]);
+ const gone = new Set(removed);
+ const picks = [];
+ const leftOut = [];
+ let others = 0;
+ const ordered = scored
+ .filter((p) => !gone.has(p.product.id))
+ .sort(
+ (a, b) =>
+ Number(keep.has(b.product.id)) - Number(keep.has(a.product.id)) || b.score - a.score,
+ );
+ for (const { product, score, result } of ordered) {
+ const kept = keep.has(product.id);
+ if (!kept && score <= 0) continue;
+ if (result.offer) {
+ if (picks.length < MAX_PRODUCTS && (kept || picks.length < max)) {
+ picks.push({ ...result.offer, score });
+ }
+ } else if (leftOut.length < MAX_LEFT_OUT && (kept || others < LEFT_OUT)) {
+ if (!kept) others += 1;
+ leftOut.push({ id: product.id, title: titleOf(product.title), reason: result.reason });
+ }
+ }
+ return { products: picks, leftOut };
+}
+
+/** A read's rows, in the order `page` asks, past PostgREST's 1000-row cap (rpc-pages.js); `limit` at most. */
+async function readRows(what, page, limit = Infinity) {
+ const { data, error } = await readAllRpcRows(what, (from, to) =>
+ from >= limit ? { data: [], error: null } : page(from, Math.min(to, limit - 1)),
+ );
+ if (error) throw new Error(`${what} read: ${error.message}`);
+ return data;
+}
+
+/**
+ * Rows of `table` whose `column` is one of `ids`: 100 ids a request
+ * (chunked-in.js), each read to its end in `order` (a unique key, so no
+ * row is read twice or missed across pages).
+ */
+async function readIn(db, table, columns, column, ids, { order, more = (q) => q }) {
+ const { data, error } = await selectInChunks(ids, (chunk) =>
+ readAllRpcRows(table, (from, to) =>
+ more(db.from(table).select(columns).in(column, chunk)).order(order).range(from, to),
+ ),
+ );
+ if (error) throw new Error(`${table} read: ${error.message}`);
+ return data;
+}
+
+const PRODUCT_FIELDS = 'id, title, url, product_type, description';
+
+/** A product row as the path scores it: its description's opening only. */
+function scoredRow(product) {
+ return { ...product, description: String(product.description ?? '').slice(0, DESCRIPTION_CHARS) };
+}
+
+/** The live products to score: the picked categories' first, then the brand's. */
+async function candidateProducts(db, brandId, categories) {
+ let products = [];
+ if (categories.length) {
+ const { data: rows, error } = await db
+ .from('catalog_categories')
+ .select('id')
+ .eq('brand_id', brandId)
+ .in(
+ 'name',
+ categories.map((c) => c.name),
+ );
+ if (error) throw new Error(`catalog_categories read: ${error.message}`);
+ const categoryIds = (rows ?? []).map((r) => r.id);
+ const links = categoryIds.length
+ ? await readRows(
+ 'catalog_product_categories',
+ (from, to) =>
+ db
+ .from('catalog_product_categories')
+ .select('product_id')
+ .in('category_id', categoryIds)
+ .order('product_id')
+ .order('category_id')
+ .range(from, to),
+ SCORED_PRODUCTS,
+ )
+ : [];
+ const ids = [...new Set(links.map((l) => l.product_id))];
+ products = (
+ await readIn(db, 'catalog_products', PRODUCT_FIELDS, 'id', ids, {
+ order: 'id',
+ more: (q) => q.eq('brand_id', brandId).is('removed_at', null),
+ })
+ ).map((p) => ({ ...scoredRow(p), inCategory: true }));
+ }
+ if (products.length < SCORED_PRODUCTS) {
+ const rows = await readRows(
+ 'catalog_products',
+ (from, to) =>
+ db
+ .from('catalog_products')
+ .select(PRODUCT_FIELDS)
+ .eq('brand_id', brandId)
+ .is('removed_at', null)
+ .order('id')
+ .range(from, to),
+ SCORED_PRODUCTS,
+ );
+ const seen = new Set(products.map((p) => p.id));
+ products.push(...rows.filter((p) => !seen.has(p.id)).map(scoredRow));
+ }
+ return products;
+}
+
+/** The person's locked and added products as the brand's catalog has them now, removed or not. */
+async function keptProducts(db, brandId, ids) {
+ const rows = await readIn(db, 'catalog_products', `${PRODUCT_FIELDS}, removed_at`, 'id', ids, {
+ order: 'id',
+ more: (q) => q.eq('brand_id', brandId),
+ });
+ return rows.map(scoredRow);
+}
+
+/** Each product's live variants, first image and Merchant Center issues, read for the best ones. */
+async function withDetails(db, brandId, products) {
+ const ids = products.map((p) => p.id);
+ const [variants, images] = await Promise.all([
+ readIn(
+ db,
+ 'catalog_variants',
+ 'id, product_id, external_id, url, price, sale_price, currency, availability',
+ 'product_id',
+ ids,
+ { order: 'id', more: (q) => q.is('removed_at', null) },
+ ),
+ readIn(db, 'catalog_images', 'id, product_id, url, position', 'product_id', ids, {
+ order: 'id',
+ }),
+ ]);
+ const issues = await readIn(
+ db,
+ 'catalog_item_issues',
+ 'id, external_id, code, severity, attribute, reporting_context',
+ 'external_id',
+ [...new Set(variants.map((v) => v.external_id))],
+ { order: 'id', more: (q) => q.eq('brand_id', brandId) },
+ );
+ const issuesOf = new Map();
+ for (const issue of issues) {
+ issuesOf.set(issue.external_id, [...(issuesOf.get(issue.external_id) ?? []), issue]);
+ }
+ return products.map((p) => ({
+ ...p,
+ variants: variants
+ .filter((v) => v.product_id === p.id)
+ .map((v) => ({ ...v, issues: issuesOf.get(v.external_id) ?? [] })),
+ image:
+ images
+ .filter((i) => i.product_id === p.id)
+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))[0]?.url ?? null,
+ }));
+}
+
+const productId = z.string().min(1).max(100);
+const address = z.string().max(2048);
+
+/**
+ * The path as content_drafts.shopping_path keeps it, with the Brief tab's
+ * caps (web/src/lib/content/shopping-path.ts). `savedAt` is the person's
+ * last change: a build writes only over the path it read, by its
+ * `builtAt` and `savedAt`.
+ */
+export const shoppingPathSchema = z.object({
+ version: z.literal(1),
+ builtAt: z.string().min(1).max(40),
+ savedAt: z.string().min(1).max(40).nullish(),
+ pageType: z.string().nullable(),
+ categories: z
+ .array(z.object({ name: z.string(), url: address, title: z.string().nullable() }))
+ .max(5),
+ products: z
+ .array(
+ z.object({
+ id: productId,
+ title: z.string(),
+ url: address,
+ price: z.number().nullable(),
+ salePrice: z.number().nullable(),
+ currency: z.string().nullable(),
+ availability: z.string(),
+ image: address.nullable(),
+ issues: z
+ .array(z.object({ code: z.string(), attribute: z.string().nullable() }))
+ .max(MAX_ISSUES),
+ score: z.number(),
+ }),
+ )
+ .max(MAX_PRODUCTS),
+ leftOut: z
+ .array(
+ z.object({
+ id: productId,
+ // Null for a kept product the catalog no longer has, and no path named.
+ title: z.string().nullable(),
+ reason: z.enum(['sold_out', 'refused', 'no_link', 'gone']),
+ }),
+ )
+ .max(MAX_LEFT_OUT),
+ locked: z.array(productId).max(MAX_KEPT),
+ removed: z.array(productId).max(MAX_REMOVED),
+ added: z.array(productId).max(MAX_KEPT),
+});
+
+/**
+ * A draft's stored shopping path, or null when it has none or one that
+ * isn't a path (a member's broken write): read as if it had none, and
+ * logged, so a build or the agent goes on without it.
+ */
+export function readShoppingPath(value, { draftId } = {}) {
+ if (value == null) return null;
+ const parsed = shoppingPathSchema.safeParse(value);
+ if (parsed.success) return parsed.data;
+ logger.warn(
+ { draftId, issues: parsed.error.issues.slice(0, 5).map((i) => i.path.join('.')) },
+ '[shopping-path] stored path unreadable; read as none',
+ );
+ return null;
+}
+
+/** A value's bytes as the column stores it: jsonb's text, ", " and ": " between items. */
+export function storedSize(value) {
+ if (Array.isArray(value)) {
+ return 2 + value.reduce((n, v, i) => n + (i ? 2 : 0) + storedSize(v), 0);
+ }
+ if (value && typeof value === 'object') {
+ return (
+ 2 +
+ Object.entries(value).reduce(
+ (n, [k, v], i) =>
+ n + (i ? 2 : 0) + Buffer.byteLength(JSON.stringify(k)) + 2 + storedSize(v),
+ 0,
+ )
+ );
+ }
+ return Buffer.byteLength(JSON.stringify(value ?? null));
+}
+
+/** The path within MAX_PATH_BYTES: fewer issues a product first, then fewer products, the last first. */
+export function fitted(path) {
+ let out = path;
+ for (const issues of [5, 1, 0]) {
+ if (storedSize(out) <= MAX_PATH_BYTES) return out;
+ out = {
+ ...out,
+ products: out.products.map((p) => ({ ...p, issues: p.issues.slice(0, issues) })),
+ };
+ }
+ while (out.products.length && storedSize(out) > MAX_PATH_BYTES) {
+ out = { ...out, products: out.products.slice(0, -1) };
+ }
+ return out;
+}
+
+/**
+ * Why a draft has no shopping path: the brand isn't a shop, the page type
+ * doesn't take one, no catalog, or nothing in it matches the topic.
+ */
+export class NoShoppingPath extends Error {
+ constructor(reason) {
+ super(`No shopping path: ${reason}`);
+ this.name = 'NoShoppingPath';
+ this.reason = reason;
+ }
+}
+
+/**
+ * Builds the draft's shopping path and saves it on the draft. Throws
+ * NoShoppingPath ('not_a_shop', 'page_type', 'no_catalog', 'no_match') when
+ * it doesn't fit; a 404 when the draft isn't the brand's; a 409 'changed'
+ * when the path changed while it was built (the person's change, or
+ * another build), so neither is lost.
+ */
+export async function buildShoppingPath(
+ { draftId, brandId },
+ { db = supabaseAdmin, now = new Date() } = {},
+) {
+ const [draftRead, brandRead] = await Promise.all([
+ db
+ .from('content_drafts')
+ .select('id, brand_id, title, page_type, brief, shopping_path')
+ .eq('id', draftId)
+ .maybeSingle(),
+ db
+ .from('brands')
+ .select('site_type, industry, shopping_mode_enabled')
+ .eq('id', brandId)
+ .maybeSingle(),
+ ]);
+ if (draftRead.error) throw new Error(`content_drafts read: ${draftRead.error.message}`);
+ if (brandRead.error) throw new Error(`brands read: ${brandRead.error.message}`);
+ const draft = draftRead.data;
+ if (!draft || draft.brand_id !== brandId) {
+ throw Object.assign(new Error('Draft not found'), { status: 404 });
+ }
+ const brand = brandRead.data ?? {};
+ const siteType = siteTypeOf({
+ siteType: brand.site_type,
+ industry: brand.industry,
+ shoppingModeEnabled: brand.shopping_mode_enabled,
+ });
+ if (siteType !== 'ecommerce') throw new NoShoppingPath('not_a_shop');
+ const max = Object.hasOwn(PRODUCTS_FOR, draft.page_type ?? '')
+ ? PRODUCTS_FOR[draft.page_type]
+ : 0;
+ if (!max) throw new NoShoppingPath('page_type');
+
+ // The stored path as read, to write only over it.
+ const read = draft.shopping_path ?? null;
+ const before = readShoppingPath(read, { draftId });
+ const choices = {
+ locked: before?.locked ?? [],
+ removed: before?.removed ?? [],
+ added: before?.added ?? [],
+ };
+ const topic = topicWords({ title: draft.title, brief: draft.brief });
+ const categories = pickCategories(await categoryPages(brandId, { db }), topic);
+ const candidates = await candidateProducts(db, brandId, categories);
+ if (!candidates.length) throw new NoShoppingPath('no_catalog');
+
+ const removed = new Set(choices.removed);
+ const keepIds = [...new Set([...choices.locked, ...choices.added])].filter(
+ (id) => !removed.has(id),
+ );
+ const keep = new Set(keepIds);
+ // A product of a picked category is worth one more of the topic's words.
+ const scoreOf = (product) =>
+ productScore(topic, product) + (product.inCategory && categories.length ? 1 : 0);
+ const best = candidates
+ .filter((p) => !keep.has(p.id) && !removed.has(p.id))
+ .map((product) => ({ product, score: scoreOf(product) }))
+ .filter((s) => s.score > 0)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, DETAILED_PRODUCTS);
+ if (!categories.length && !best.length && !keepIds.length) throw new NoShoppingPath('no_match');
+
+ // The person's products, read by id: kept whatever their score, and
+ // said to be gone when the catalog removed them or no longer has them.
+ const kept = new Map((await keptProducts(db, brandId, keepIds)).map((p) => [p.id, p]));
+ const candidateOf = new Map(candidates.map((p) => [p.id, p]));
+ const titleBefore = new Map(
+ [...(before?.products ?? []), ...(before?.leftOut ?? [])].map((p) => [p.id, p.title]),
+ );
+ const live = keepIds
+ .map((id) => kept.get(id))
+ .filter((p) => p && p.removed_at == null)
+ .map((product) => ({ product, score: scoreOf(candidateOf.get(product.id) ?? product) }));
+ const gone = keepIds
+ .filter((id) => !kept.get(id) || kept.get(id).removed_at != null)
+ .map((id) => ({
+ product: { id, title: kept.get(id)?.title ?? titleBefore.get(id) ?? null },
+ score: 0,
+ result: { reason: 'gone' },
+ }));
+
+ const toDetail = [...live, ...best];
+ const detailed = await withDetails(
+ db,
+ brandId,
+ toDetail.map((s) => s.product),
+ );
+ const byId = new Map(detailed.map((p) => [p.id, p]));
+ const scored = toDetail.map(({ product, score }) => {
+ const full = byId.get(product.id);
+ return { product: full, score, result: offerOf(full) };
+ });
+ const { products, leftOut } = pickProducts([...scored, ...gone], { max, ...choices });
+
+ const path = fitted({
+ version: 1,
+ builtAt: now.toISOString(),
+ pageType: draft.page_type,
+ categories,
+ products,
+ leftOut,
+ ...choices,
+ });
+ // Written only over the path read: a person's change, or another build,
+ // since then is never overwritten. A path no one could read (a broken
+ // write, logged above) is built over.
+ let write = db
+ .from('content_drafts')
+ .update({ shopping_path: path })
+ .eq('id', draftId)
+ .eq('brand_id', brandId);
+ if (before) {
+ write = write.eq('shopping_path->>builtAt', before.builtAt);
+ write = before.savedAt
+ ? write.eq('shopping_path->>savedAt', before.savedAt)
+ : write.is('shopping_path->>savedAt', null);
+ } else if (read == null) {
+ write = write.is('shopping_path', null);
+ }
+ const { data, error } = await write.select('id');
+ if (error) throw new Error(`content_drafts write: ${error.message}`);
+ if (!data?.length) {
+ throw Object.assign(new Error('The shopping path changed while it was built'), {
+ status: 409,
+ code: 'changed',
+ });
+ }
+ return path;
+}
diff --git a/server/src/lib/shopping-path.test.js b/server/src/lib/shopping-path.test.js
new file mode 100644
index 000000000..1637d8e55
--- /dev/null
+++ b/server/src/lib/shopping-path.test.js
@@ -0,0 +1,697 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+vi.mock('./logger.js', () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import { fakeDb } from './catalog/__fixtures__/fake-db.js';
+import { logger } from './logger.js';
+import {
+ LEFT_OUT,
+ MAX_ISSUES,
+ MAX_PATH_BYTES,
+ MAX_PRODUCTS,
+ NoShoppingPath,
+ PRODUCTS_FOR,
+ TITLE_CHARS,
+ buildShoppingPath,
+ fitted,
+ offerOf,
+ pickCategories,
+ pickProducts,
+ readShoppingPath,
+ refuses,
+ shoppingPathSchema,
+ storedSize,
+ topicScore,
+ topicWords,
+} from './shopping-path.js';
+
+/** A draft's shopping path (shopping path, 00351). */
+
+const BRIEF = {
+ goal: 'Help hikers pick a waterproof boot',
+ keywords: ['waterproof hiking boots', 'gore-tex'],
+ outline: [{ heading: 'How to choose: fit and weight' }],
+};
+
+/** A path as a build leaves it, with the person's choices. */
+const stored = (choices = {}) => ({
+ version: 1,
+ builtAt: '2026-10-26T09:00:00.000Z',
+ pageType: 'buying_guide',
+ categories: [],
+ products: [],
+ leftOut: [],
+ locked: [],
+ removed: [],
+ added: [],
+ ...choices,
+});
+
+describe('topicWords', () => {
+ it("weighs the title's words most, then the keywords, then the goal and headings", () => {
+ const topic = topicWords({ title: 'How to choose waterproof hiking boots', brief: BRIEF });
+ expect(topic.get('waterproof')).toBe(3);
+ expect(topic.get('gore')).toBe(2);
+ expect(topic.get('fit')).toBe(1);
+ expect(topicScore(topic, 'Waterproof Boot, Gore-Tex')).toBe(3 + 3 + 2 + 2);
+ });
+
+ it("leaves out the words that say what kind of page it is, a list's size and its year", () => {
+ const topic = topicWords({
+ title: 'Top 10 best waterproof hiking boots of 2026: a buying guide and review',
+ brief: { keywords: ['boots vs shoes for the trail'], outline: [{ heading: 'How to buy' }] },
+ });
+ expect([...topic.keys()].sort()).toEqual(['boot', 'hiking', 'shoe', 'trail', 'waterproof']);
+ // "Top" alone and "pick" are products in some shops.
+ expect([
+ ...topicWords({ title: 'Best summer tops and guitar picks', brief: null }).keys(),
+ ]).toEqual(['summer', 'top', 'guitar', 'pick']);
+ expect(topicWords({ title: 'How to choose the best: a guide', brief: null }).size).toBe(0);
+ });
+
+ it('folds the letters Unicode keeps whole, as category pages do', () => {
+ const topic = topicWords({ title: 'En iyi kadın botları nasıl seçilir', brief: null });
+ expect([...topic.keys()]).toEqual(['kadin', 'botlari']);
+ });
+});
+
+describe('pickCategories', () => {
+ const topic = topicWords({ title: 'How to choose waterproof hiking boots', brief: null });
+ const category = (name, inStock, url = `https://s.example/c/${name}`, title = null) => ({
+ name,
+ products: 10,
+ inStock,
+ page: url ? { url, title } : null,
+ });
+
+ it('links the best category with a page and stock, and a second only close to it', () => {
+ expect(
+ pickCategories(
+ [
+ category('Shoes > Hiking Boots', 18),
+ category('Boots', 4),
+ category('Rain Jackets', 12),
+ category('Hiking Socks', 0),
+ category('Hiking Poles', 9, null),
+ ],
+ topic,
+ ),
+ ).toEqual([
+ {
+ name: 'Shoes > Hiking Boots',
+ url: 'https://s.example/c/Shoes > Hiking Boots',
+ title: null,
+ },
+ { name: 'Boots', url: 'https://s.example/c/Boots', title: null },
+ ]);
+ expect(pickCategories([category('Rain Jackets', 12)], topic)).toEqual([]);
+ });
+
+ it("takes a second one at half the first's score, not below", () => {
+ // "Hiking Boots": (3 + 3) × 2 = 12; "Boot Laces": 3 × 2 = 6; "Laces" titled "Boot laces": 3.
+ const names = (categories) => pickCategories(categories, topic, 3).map((c) => c.name);
+ expect(
+ names([
+ category('Hiking Boots', 5),
+ category('Boot Laces', 5),
+ category('Laces', 5, 'https://s.example/c/laces', 'Boot laces'),
+ ]),
+ ).toEqual(['Hiking Boots', 'Boot Laces']);
+ });
+});
+
+describe('offerOf', () => {
+ const variant = (availability, extra = {}) => ({
+ external_id: 'v',
+ url: null,
+ price: 100,
+ sale_price: null,
+ currency: 'USD',
+ availability,
+ issues: [],
+ ...extra,
+ });
+ const product = (variants, url = 'https://s.example/p/boot') => ({
+ id: 'p1',
+ title: 'Boot',
+ url,
+ image: null,
+ variants,
+ });
+
+ it('offers the cheapest variant in stock that Merchant Center accepts, with its issues', () => {
+ const { offer } = offerOf(
+ product([
+ variant('in_stock', { price: 189 }),
+ variant('in_stock', {
+ price: 149,
+ sale_price: 129,
+ issues: [{ code: 'missing_gtin', severity: 'demoted', attribute: 'gtin' }],
+ }),
+ variant('in_stock', {
+ price: 99,
+ issues: [{ code: 'price_mismatch', severity: 'disapproved', attribute: 'price' }],
+ }),
+ variant('out_of_stock', { price: 50 }),
+ ]),
+ );
+ expect(offer).toMatchObject({
+ price: 149,
+ salePrice: 129,
+ currency: 'USD',
+ issues: [{ code: 'missing_gtin', attribute: 'gtin' }],
+ });
+ });
+
+ it("says why a product can't be offered", () => {
+ expect(offerOf(product([variant('out_of_stock')]))).toEqual({ reason: 'sold_out' });
+ expect(
+ offerOf(product([variant('in_stock', { issues: [{ code: 'x', severity: 'disapproved' }] })])),
+ ).toEqual({ reason: 'refused' });
+ expect(offerOf(product([variant('in_stock')], null))).toEqual({ reason: 'no_link' });
+ });
+
+ it('reads limited availability and every spelling of in stock as in stock, spelled one way', () => {
+ for (const availability of ['limited_availability', 'Limited Availability']) {
+ expect(offerOf(product([variant(availability)])).offer.availability).toBe(
+ 'limited_availability',
+ );
+ }
+ for (const availability of ['IN_STOCK', 'in stock', 'instock', 'available']) {
+ expect(offerOf(product([variant(availability)])).offer).toBeTruthy();
+ }
+ expect(offerOf(product([variant('preorder')]))).toEqual({ reason: 'sold_out' });
+ });
+
+ it('orders the variants by their sale price where they have one', () => {
+ const { offer } = offerOf(
+ product([
+ variant('in_stock', { external_id: 'a', price: 80 }),
+ variant('in_stock', { external_id: 'b', price: 100, sale_price: 60 }),
+ ]),
+ );
+ expect(offer).toMatchObject({ price: 100, salePrice: 60 });
+ });
+
+ it("links a variant's page when the product has none, and offers a variant with no price", () => {
+ const { offer } = offerOf(
+ product(
+ [variant('in_stock', { price: null, url: 'https://s.example/p/boot?variant=42' })],
+ null,
+ ),
+ );
+ expect(offer).toMatchObject({
+ url: 'https://s.example/p/boot?variant=42',
+ price: null,
+ salePrice: null,
+ });
+ });
+
+ it('counts a disapproval only in the free listings, or in none named: an ad refusal is an issue', () => {
+ const disapproved = (reporting_context) => ({
+ code: 'policy',
+ severity: 'disapproved',
+ attribute: null,
+ reporting_context,
+ });
+ expect(refuses(disapproved('FREE_LISTINGS'))).toBe(true);
+ expect(refuses(disapproved(null))).toBe(true);
+ expect(refuses(disapproved(''))).toBe(true);
+ expect(refuses(disapproved('SHOPPING_ADS'))).toBe(false);
+ expect(refuses({ ...disapproved(null), severity: 'demoted' })).toBe(false);
+ const { offer } = offerOf(
+ product([variant('in_stock', { issues: [disapproved('SHOPPING_ADS')] })]),
+ );
+ expect(offer.issues).toEqual([{ code: 'policy', attribute: null }]);
+ expect(
+ offerOf(product([variant('in_stock', { issues: [disapproved('FREE_LISTINGS')] })])),
+ ).toEqual({ reason: 'refused' });
+ });
+
+ it("keeps a title and a product's issues within the path's caps", () => {
+ const issues = Array.from({ length: 30 }, (_, i) => ({
+ code: `code_${i}`,
+ severity: 'demoted',
+ attribute: null,
+ }));
+ const { offer } = offerOf({
+ ...product([variant('in_stock', { issues })]),
+ title: 'B'.repeat(900),
+ });
+ expect(offer.issues).toHaveLength(MAX_ISSUES);
+ expect(offer.title).toHaveLength(TITLE_CHARS);
+ });
+});
+
+describe('pickProducts', () => {
+ const item = (id, score, reason = null) => ({
+ product: { id, title: `Product ${id}` },
+ score,
+ result: reason ? { reason } : { offer: { id, title: `Product ${id}` } },
+ });
+
+ it('takes the best offers up to the page type, and keeps the best left out with why', () => {
+ const { products, leftOut } = pickProducts(
+ [item('a', 9), item('b', 8, 'sold_out'), item('c', 7), item('d', 6), item('e', 0)],
+ { max: 2 },
+ );
+ expect(products.map((p) => p.id)).toEqual(['a', 'c']);
+ expect(leftOut).toEqual([{ id: 'b', title: 'Product b', reason: 'sold_out' }]);
+ });
+
+ it("keeps the person's locked and added products, in the page's count, and never a removed one", () => {
+ const items = [item('a', 9), item('b', 8), item('c', 0), item('d', 1)];
+ const choices = { locked: ['d'], removed: ['a'], added: ['c'] };
+ const ids = (max) =>
+ pickProducts(items, { max, ...choices })
+ .products.map((p) => p.id)
+ .sort();
+ expect(ids(2)).toEqual(['c', 'd']);
+ expect(ids(3)).toEqual(['b', 'c', 'd']);
+ // More kept than the page takes: all of them stay.
+ expect(ids(1)).toEqual(['c', 'd']);
+ });
+
+ it("says why each of the person's products is left out, beside the best of the others", () => {
+ const kept = ['k1', 'k2', 'k3', 'k4'];
+ const { leftOut } = pickProducts(
+ [
+ ...kept.map((id) => item(id, 0, id === 'k4' ? 'gone' : 'sold_out')),
+ ...['x1', 'x2', 'x3', 'x4'].map((id) => item(id, 5, 'refused')),
+ ],
+ { max: 3, locked: kept },
+ );
+ expect(leftOut.map((l) => l.id)).toEqual(['k1', 'k2', 'k3', 'k4', 'x1', 'x2', 'x3']);
+ expect(leftOut.filter((l) => l.id.startsWith('x'))).toHaveLength(LEFT_OUT);
+ expect(leftOut.find((l) => l.id === 'k4').reason).toBe('gone');
+ });
+
+ it('links MAX_PRODUCTS at most, however many the person keeps', () => {
+ const ids = Array.from({ length: 60 }, (_, i) => `k${i}`);
+ const { products } = pickProducts(
+ ids.map((id) => item(id, 0)),
+ { max: 5, locked: ids.slice(0, 40), added: ids.slice(40) },
+ );
+ expect(products).toHaveLength(MAX_PRODUCTS);
+ });
+});
+
+describe('readShoppingPath', () => {
+ it("reads a stored path, and one that isn't a path as none, logged", () => {
+ expect(readShoppingPath(null)).toBeNull();
+ expect(readShoppingPath(stored({ locked: ['p1'] }))).toMatchObject({ locked: ['p1'] });
+ logger.warn.mockClear();
+ for (const broken of [
+ { locked: ['p1'] },
+ stored({ locked: 'p1' }),
+ stored({ products: [null] }),
+ stored({ categories: {} }),
+ stored({ removed: Array.from({ length: 201 }, (_, i) => `r${i}`) }),
+ 'a path',
+ ]) {
+ expect(readShoppingPath(broken, { draftId: 'd1' })).toBeNull();
+ }
+ expect(logger.warn).toHaveBeenCalledTimes(6);
+ expect(logger.warn.mock.calls[0][0]).toMatchObject({ draftId: 'd1' });
+ });
+});
+
+describe('fitted', () => {
+ it("measures a value as the column's jsonb text does", () => {
+ expect(storedSize({ a: [1, 'x'], b: null, c: { d: 'é' } })).toBe(
+ Buffer.byteLength('{"a": [1, "x"], "b": null, "c": {"d": "é"}}'),
+ );
+ });
+
+ it('brings the largest path under 64 KB: fewer issues first, then fewer products', () => {
+ const long = (n) => `https://s.example/${'x'.repeat(n)}`;
+ const product = (i) => ({
+ id: `p${i}`,
+ title: 'T'.repeat(TITLE_CHARS),
+ url: long(2000),
+ price: 10,
+ salePrice: null,
+ currency: 'USD',
+ availability: 'in_stock',
+ image: long(2000),
+ issues: Array.from({ length: MAX_ISSUES }, (_, j) => ({
+ code: `c${j}`.padEnd(150, 'c'),
+ attribute: 'a'.repeat(150),
+ })),
+ score: 1,
+ });
+ const big = stored({ products: Array.from({ length: MAX_PRODUCTS }, (_, i) => product(i)) });
+ expect(storedSize(big)).toBeGreaterThan(65536);
+ const out = fitted(big);
+ expect(storedSize(out)).toBeLessThanOrEqual(MAX_PATH_BYTES);
+ expect(out.products[0].issues).toEqual([]);
+ expect(out.products.length).toBeLessThan(MAX_PRODUCTS);
+ expect(out.products[0].id).toBe('p0');
+ expect(shoppingPathSchema.safeParse(out).success).toBe(true);
+ // A path under the cap is left as it is.
+ const small = stored({ products: [product(1)] });
+ expect(fitted(small)).toBe(small);
+ });
+});
+
+describe('buildShoppingPath', () => {
+ const NOW = new Date('2026-10-27T12:00:00Z');
+
+ /**
+ * A shop: draft d1 (a buying guide for waterproof hiking boots) of brand
+ * b1, its category "Shoes > Hiking Boots" with a page, and products.
+ * `add` puts more products in the catalog.
+ */
+ function setup({
+ siteType = 'ecommerce',
+ pageType = 'buying_guide',
+ path = null,
+ products = true,
+ page = true,
+ maxRows,
+ } = {}) {
+ const fake = fakeDb({ maxRows });
+ fake.rows('content_drafts').push({
+ id: 'd1',
+ brand_id: 'b1',
+ title: 'How to choose waterproof hiking boots',
+ page_type: pageType,
+ brief: BRIEF,
+ shopping_path: path,
+ });
+ fake.rows('brands').push({ id: 'b1', site_type: siteType, shopping_mode_enabled: false });
+ if (page) {
+ fake.rows('site_pages').push({
+ id: 's1',
+ brand_id: 'b1',
+ url: 'https://s.example/collections/hiking-boots',
+ title: 'Hiking boots',
+ });
+ }
+ fake
+ .rows('catalog_categories')
+ .push({ id: 'c1', brand_id: 'b1', name: 'Shoes > Hiking Boots' });
+ const add = (
+ id,
+ title,
+ {
+ availability = 'in_stock',
+ severity = null,
+ inCategory = true,
+ brand = 'b1',
+ removed = false,
+ variants = 1,
+ price = 100,
+ type = inCategory ? 'Shoes > Hiking Boots' : 'Other',
+ } = {},
+ ) => {
+ fake.rows('catalog_products').push({
+ id,
+ brand_id: brand,
+ title,
+ url: `https://s.example/products/${id}`,
+ product_type: type,
+ description: null,
+ removed_at: removed ? '2026-10-20T00:00:00Z' : null,
+ });
+ if (inCategory) {
+ fake
+ .rows('catalog_product_categories')
+ .push({ brand_id: brand, product_id: id, category_id: 'c1' });
+ }
+ for (let n = 0; n < variants; n += 1) {
+ fake.rows('catalog_variants').push({
+ id: `v-${id}-${String(n).padStart(4, '0')}`,
+ product_id: id,
+ external_id: `${id}-${n}`,
+ url: null,
+ price,
+ sale_price: null,
+ currency: 'USD',
+ // Only a product's last variant is in stock, when it is.
+ availability: n === variants - 1 ? availability : 'out_of_stock',
+ removed_at: null,
+ });
+ }
+ if (severity) {
+ fake.rows('catalog_item_issues').push({
+ id: `i-${id}`,
+ brand_id: brand,
+ external_id: `${id}-${variants - 1}`,
+ code: severity === 'demoted' ? 'missing_gtin' : 'price_mismatch',
+ severity,
+ attribute: severity === 'demoted' ? 'gtin' : 'price',
+ reporting_context: null,
+ });
+ }
+ };
+ if (products) {
+ add('p1', 'Summit Waterproof Hiking Boot');
+ add('p2', 'Trail Mid Waterproof Boot', { severity: 'demoted' });
+ add('p3', 'Canyon Low Waterproof Hiker', { availability: 'out_of_stock' });
+ add('p4', 'Ridge Waterproof Hiking Boot', { severity: 'disapproved' });
+ add('p5', 'Wool Hiking Sock', { inCategory: false });
+ }
+ const rpc = vi.fn(async () => ({
+ data: [
+ { category: 'Shoes > Hiking Boots', products: 4, in_stock: 3 },
+ { category: 'Socks', products: 1, in_stock: 1 },
+ ],
+ error: null,
+ }));
+ const db = { ...fake.db, rpc };
+ const build = () => buildShoppingPath({ draftId: 'd1', brandId: 'b1' }, { db, now: NOW });
+ return { fake, db, rpc, add, build, draft: () => fake.rows('content_drafts')[0] };
+ }
+
+ it('picks the category page and the products in stock Merchant Center accepts, and saves them', async () => {
+ const { fake, build } = setup();
+ const path = await build();
+ expect(path).toMatchObject({
+ version: 1,
+ builtAt: '2026-10-27T12:00:00.000Z',
+ pageType: 'buying_guide',
+ categories: [
+ {
+ name: 'Shoes > Hiking Boots',
+ url: 'https://s.example/collections/hiking-boots',
+ title: 'Hiking boots',
+ },
+ ],
+ locked: [],
+ removed: [],
+ added: [],
+ });
+ expect(path.products.map((p) => p.id)).toEqual(expect.arrayContaining(['p1', 'p2']));
+ expect(path.products.map((p) => p.id)).not.toContain('p3');
+ expect(path.products.map((p) => p.id)).not.toContain('p4');
+ expect(path.products.find((p) => p.id === 'p2').issues).toEqual([
+ { code: 'missing_gtin', attribute: 'gtin' },
+ ]);
+ expect(path.leftOut).toEqual(
+ expect.arrayContaining([
+ { id: 'p3', title: 'Canyon Low Waterproof Hiker', reason: 'sold_out' },
+ { id: 'p4', title: 'Ridge Waterproof Hiking Boot', reason: 'refused' },
+ ]),
+ );
+ expect(fake.rows('content_drafts')[0].shopping_path).toEqual(path);
+ expect(shoppingPathSchema.parse(path)).toEqual(path);
+ });
+
+ it("gives a product of the picked category one more point: it is offered, another brand's isn't", async () => {
+ const { add, build } = setup();
+ add('p6', 'Model X', { type: 'Misc' });
+ add('p7', 'Garden Hose', { inCategory: false });
+ const path = await build();
+ const ids = path.products.map((p) => p.id);
+ expect(ids).toContain('p6');
+ expect(path.products.find((p) => p.id === 'p6').score).toBe(1);
+ expect(ids).not.toContain('p7');
+ });
+
+ const COUNTS = [
+ ['best_of', 8],
+ ['buying_guide', 5],
+ ['comparison', 4],
+ ['alternatives', 4],
+ ['guide', 4],
+ ['blog_post', 3],
+ ];
+
+ it('takes a path on these page types only', () => {
+ expect(Object.keys(PRODUCTS_FOR).sort()).toEqual(COUNTS.map(([type]) => type).sort());
+ });
+
+ it.each(COUNTS)('links as many products as a %s takes (%i)', async (pageType, count) => {
+ const { add, build } = setup({ pageType, products: false });
+ for (let i = 0; i < 12; i += 1) add(`p${String(i).padStart(2, '0')}`, 'Waterproof Boot');
+ expect((await build()).products).toHaveLength(count);
+ });
+
+ it("keeps the person's choices when it builds again", async () => {
+ const { build } = setup({ path: stored({ locked: ['p5'], removed: ['p1'] }) });
+ const path = await build();
+ const ids = path.products.map((p) => p.id);
+ expect(ids).toContain('p5');
+ expect(ids).not.toContain('p1');
+ expect(path.locked).toEqual(['p5']);
+ expect(path.removed).toEqual(['p1']);
+ });
+
+ it('keeps an added product past the best scored, and keeps it on every build after (a gift card among 60 boots)', async () => {
+ const { add, build, draft } = setup({ products: false });
+ for (let i = 0; i < 60; i += 1) {
+ add(`b${String(i).padStart(2, '0')}`, `Waterproof Hiking Boot ${i}`);
+ }
+ add('gift', 'Gift card', { inCategory: false });
+ // The person adds it in the Brief tab: saved as the path's own.
+ draft().shopping_path = stored({ added: ['gift'] });
+ for (let n = 0; n < 2; n += 1) {
+ const path = await build();
+ expect(path.products.map((p) => p.id)).toContain('gift');
+ expect(path.products).toHaveLength(PRODUCTS_FOR.buying_guide);
+ expect(path.added).toEqual(['gift']);
+ }
+ });
+
+ it('says why a locked product is left out: sold out since, or gone from the catalog', async () => {
+ const { add, build } = setup({
+ path: stored({
+ locked: ['p3', 'p8', 'p9', 'x1'],
+ products: [
+ {
+ id: 'p9',
+ title: 'Old Boot',
+ url: 'https://s.example/products/p9',
+ price: 1,
+ salePrice: null,
+ currency: 'USD',
+ availability: 'in_stock',
+ image: null,
+ issues: [],
+ score: 3,
+ },
+ ],
+ }),
+ });
+ add('p8', 'Retired Waterproof Boot', { removed: true });
+ // Another brand's product, its id written in by hand: never read.
+ add('x1', 'Their Boot', { brand: 'b2', inCategory: false });
+ // p9 was deleted from the catalog: no row at all.
+ const path = await build();
+ expect(path.locked).toEqual(['p3', 'p8', 'p9', 'x1']);
+ expect(path.leftOut).toEqual(
+ expect.arrayContaining([
+ { id: 'p3', title: 'Canyon Low Waterproof Hiker', reason: 'sold_out' },
+ { id: 'p8', title: 'Retired Waterproof Boot', reason: 'gone' },
+ { id: 'p9', title: 'Old Boot', reason: 'gone' },
+ { id: 'x1', title: null, reason: 'gone' },
+ ]),
+ );
+ for (const id of ['p3', 'p8', 'p9', 'x1']) {
+ expect(path.products.map((p) => p.id)).not.toContain(id);
+ }
+ expect(shoppingPathSchema.safeParse(path).success).toBe(true);
+ });
+
+ it("reads past PostgREST's 1000 rows: the links, the products, the variants and the issues", async () => {
+ const { add, build, fake } = setup({ products: false, maxRows: 1000 });
+ for (let i = 0; i < 1500; i += 1) {
+ add(`q${String(i).padStart(4, '0')}`, `Plain Item ${i}`, { variants: 0, type: 'Misc' });
+ }
+ // Past the first 1000 links and products, and its stock past its first 1000 variants.
+ add('q9000', 'Summit Waterproof Hiking Boot', { variants: 1200, price: 89 });
+ // Past its first 1000 issues, a refusal in the free listings.
+ add('q9001', 'Ridge Waterproof Hiking Boot');
+ for (let i = 0; i < 1001; i += 1) {
+ fake.rows('catalog_item_issues').push({
+ id: `j-${String(i).padStart(4, '0')}`,
+ brand_id: 'b1',
+ external_id: 'q9001-0',
+ code: i === 1000 ? 'policy' : `note_${i}`,
+ severity: i === 1000 ? 'disapproved' : 'not_impacted',
+ attribute: null,
+ reporting_context: i === 1000 ? 'FREE_LISTINGS' : null,
+ });
+ }
+ const path = await build();
+ expect(path.products.map((p) => [p.id, p.price])).toEqual([['q9000', 89]]);
+ expect(path.leftOut[0]).toEqual({
+ id: 'q9001',
+ title: 'Ridge Waterproof Hiking Boot',
+ reason: 'refused',
+ });
+ });
+
+ it("reads past PostgREST's 1000 rows for a brand with no category page, too", async () => {
+ const { add, build } = setup({ products: false, page: false, maxRows: 1000 });
+ for (let i = 0; i < 1500; i += 1) {
+ add(`q${String(i).padStart(4, '0')}`, `Plain Item ${i}`, { variants: 0 });
+ }
+ add('q9000', 'Summit Waterproof Hiking Boot');
+ const path = await build();
+ expect(path.categories).toEqual([]);
+ expect(path.products.map((p) => p.id)).toEqual(['q9000']);
+ });
+
+ it("refuses to write over a person's change, or another build, made while it built", async () => {
+ // A person's save (its savedAt) while the build reads the catalog.
+ const saved = setup({ path: stored({ locked: ['p5'] }) });
+ saved.rpc.mockImplementationOnce(async () => {
+ saved.draft().shopping_path = stored({
+ locked: ['p5'],
+ removed: ['p2'],
+ savedAt: '2026-10-27T11:59:59.000Z',
+ });
+ return { data: [], error: null };
+ });
+ await expect(saved.build()).rejects.toMatchObject({ status: 409, code: 'changed' });
+ expect(saved.draft().shopping_path.removed).toEqual(['p2']);
+
+ // Another build, from another tab.
+ const other = setup();
+ other.rpc.mockImplementationOnce(async () => {
+ other.draft().shopping_path = stored({ builtAt: '2026-10-27T11:59:59.000Z' });
+ return { data: [], error: null };
+ });
+ await expect(other.build()).rejects.toMatchObject({ status: 409, code: 'changed' });
+
+ // Unchanged since it was read, a path the person saved builds over.
+ const ok = setup({ path: stored({ savedAt: '2026-10-27T11:00:00.000Z', locked: ['p5'] }) });
+ expect((await ok.build()).locked).toEqual(['p5']);
+ });
+
+ it("builds over a stored path that isn't one, as if there were none", async () => {
+ logger.warn.mockClear();
+ const { build, draft } = setup({ path: { locked: 'p1', products: [null] } });
+ const path = await build();
+ expect(path.locked).toEqual([]);
+ expect(draft().shopping_path).toEqual(path);
+ expect(logger.warn).toHaveBeenCalledTimes(1);
+ });
+
+ it("has none for a brand that isn't a shop, a page type that takes none, no catalog, or no match", async () => {
+ await expect(setup({ siteType: 'b2b' }).build()).rejects.toMatchObject({
+ reason: 'not_a_shop',
+ });
+ await expect(setup({ pageType: 'product_page' }).build()).rejects.toBeInstanceOf(
+ NoShoppingPath,
+ );
+ await expect(setup({ pageType: 'constructor' }).build()).rejects.toMatchObject({
+ reason: 'page_type',
+ });
+ await expect(setup({ products: false }).build()).rejects.toMatchObject({
+ reason: 'no_catalog',
+ });
+ const unrelated = setup({ products: false, page: false });
+ unrelated.add('g1', 'Garden Hose', { inCategory: false });
+ await expect(unrelated.build()).rejects.toMatchObject({ reason: 'no_match' });
+ expect(unrelated.draft().shopping_path).toBeNull();
+ await expect(
+ buildShoppingPath({ draftId: 'd1', brandId: 'b2' }, { db: setup().db }),
+ ).rejects.toMatchObject({ status: 404 });
+ });
+});
diff --git a/server/src/middleware/rate-limiter.js b/server/src/middleware/rate-limiter.js
index 2ab69cb6a..b780d0ff6 100644
--- a/server/src/middleware/rate-limiter.js
+++ b/server/src/middleware/rate-limiter.js
@@ -146,6 +146,22 @@ export const catalogCategoryLimiter = rateLimit({
},
});
+// A draft's shopping path built from the brand's catalog (shopping path,
+// 00351): each build reads up to 2,000 products and their details, and the
+// Brief tab asks on a person's click (Pick again, Swap, Add), so a bucket of
+// its own.
+export const shoppingPathLimiter = rateLimit({
+ windowMs: 15 * 60 * 1000,
+ max: 30,
+ keyGenerator: apiLimiterKey,
+ standardHeaders: true,
+ legacyHeaders: false,
+ message: {
+ success: false,
+ message: 'Too many requests, please try again later.',
+ },
+});
+
// A brand's CMS connection (Send to CMS, #1331): each call reaches Webflow
// through Composio, so a member's are few.
export const cmsLimiter = rateLimit({
diff --git a/server/src/middleware/rate-limiter.test.js b/server/src/middleware/rate-limiter.test.js
index f1d0b93fa..ff6e12e9b 100644
--- a/server/src/middleware/rate-limiter.test.js
+++ b/server/src/middleware/rate-limiter.test.js
@@ -5,8 +5,10 @@ import {
botIngestKey,
catalogCategoryLimiter,
catalogLimiter,
+ cmsLimiter,
isJourneyBeacon,
journeyEventKey,
+ shoppingPathLimiter,
webhookCallbackKey,
} from './rate-limiter.js';
import {
@@ -170,3 +172,30 @@ describe('rate-limiter – catalog buckets', () => {
}
});
});
+
+describe('rate-limiter – shopping path builds', () => {
+ it("gives a draft's shopping path builds a bucket of their own: 30 a quarter-hour", async () => {
+ const app = express();
+ app.post('/shopping-path', shoppingPathLimiter, (_req, res) => res.json({}));
+ app.post('/cms', cmsLimiter, (_req, res) => res.json({}));
+ const server = await new Promise((resolve) => {
+ const listening = app.listen(0, '127.0.0.1', () => resolve(listening));
+ });
+ const base = `http://127.0.0.1:${server.address().port}`;
+ const statuses = async (path, n) => {
+ const out = [];
+ for (let i = 0; i < n; i += 1)
+ out.push((await fetch(base + path, { method: 'POST' })).status);
+ return out;
+ };
+ try {
+ const builds = await statuses('/shopping-path', 31);
+ expect(new Set(builds.slice(0, 30))).toEqual(new Set([200]));
+ expect(builds.at(-1)).toBe(429);
+ // The other buckets keep theirs.
+ expect(await statuses('/cms', 1)).toEqual([200]);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+ });
+});
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index 7a25f1599..b201f7cc4 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -5,10 +5,11 @@ import { fixDraftRules, fixRulesInput } from '../lib/content-agent.js';
import { handOffDraft, handOffInput } from '../lib/content-handoff.js';
import { qualityPhase } from '../lib/content-quality.js';
import { briefRules, rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';
+import { NoShoppingPath, buildShoppingPath } from '../lib/shopping-path.js';
import { DeliveryError, sendContentPages, sendInput } from '../lib/content-delivery.js';
import { checkWebflowPublished } from '../lib/cms/webflow-status.js';
import { liveAddress, publishDraft } from '../lib/content-published.js';
-import { cmsLimiter } from '../middleware/rate-limiter.js';
+import { cmsLimiter, shoppingPathLimiter } from '../middleware/rate-limiter.js';
import { stopDraftRun } from '../lib/content-runs.js';
import { startDraftWriting, writeDraftInput } from '../lib/content-writer.js';
import supabaseAdmin from '../config/supabase.js';
@@ -205,6 +206,40 @@ router.post('/:draftId/brief', async (req, res) => {
}
});
+/**
+ * POST /api/content-drafts/:draftId/shopping-path
+ * Body: { brandId }
+ * Builds the draft's shopping path from the brand's catalog and saves it
+ * (shopping path, 00351): { path }, or { path: null, reason } when it
+ * doesn't fit ('not_a_shop', 'page_type', 'no_catalog', 'no_match'). A 409
+ * 'changed' when the path changed while it was built; a 429 past its
+ * bucket (shoppingPathLimiter).
+ */
+router.post('/:draftId/shopping-path', shoppingPathLimiter, async (req, res) => {
+ const draftId = z.guid().safeParse(req.params.draftId);
+ const body = z.object({ brandId: z.guid() }).safeParse(req.body ?? {});
+ if (!draftId.success || !body.success) {
+ return res.status(400).json({ error: 'Invalid request', code: 'invalid' });
+ }
+ try {
+ await assertBrandAccess(body.data.brandId, req.user.id);
+ const path = await buildShoppingPath({ draftId: draftId.data, brandId: body.data.brandId });
+ return res.json({ path });
+ } catch (err) {
+ if (err instanceof NoShoppingPath) return res.json({ path: null, reason: err.reason });
+ if (ERROR_CODES[err?.status]) {
+ return res
+ .status(err.status)
+ .json({ error: err.message, code: err.code ?? ERROR_CODES[err.status] });
+ }
+ req.log.error(
+ { err: { name: err?.name, message: err?.message } },
+ 'content draft shopping path error',
+ );
+ return res.status(502).json({ error: 'The shopping path could not be built', code: 'failed' });
+ }
+});
+
const fixBody = fixRulesInput.extend({ brandId: z.guid() });
/**
diff --git a/server/src/routes/content-drafts.test.js b/server/src/routes/content-drafts.test.js
index 5faba020b..a156ba80e 100644
--- a/server/src/routes/content-drafts.test.js
+++ b/server/src/routes/content-drafts.test.js
@@ -17,6 +17,7 @@ const startDraftWriting = vi.fn();
const fixDraftRules = vi.fn();
const assertBrandAccess = vi.fn();
const stopDraftRun = vi.fn();
+const buildShoppingPath = vi.fn();
/** A Start's claim on the draft (its agent_state_at), as its run carries it. */
const CLAIM = '2026-10-23T10:00:00.000+00:00';
/** The draft Stop reads, to check it is the brand's. */
@@ -56,11 +57,27 @@ vi.mock('../lib/content-agent.js', async (importOriginal) => ({
...(await importOriginal()),
fixDraftRules: (...args) => fixDraftRules(...args),
}));
+vi.mock('../lib/shopping-path.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ buildShoppingPath: (...args) => buildShoppingPath(...args),
+}));
vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));
+/** Whether the shopping path's bucket is spent: its limiter answers as express-rate-limit does then. */
+let shoppingPathSpent = false;
+vi.mock('../middleware/rate-limiter.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ shoppingPathLimiter: (_req, res, next) =>
+ shoppingPathSpent
+ ? res
+ .status(429)
+ .json({ success: false, message: 'Too many requests, please try again later.' })
+ : next(),
+}));
const { default: router } = await import('./content-drafts.js');
const { PlanLimitError } = await import('../lib/plan-guard.js');
const { RunStoppedError } = await import('../lib/content-runs.js');
+const { NoShoppingPath } = await import('../lib/shopping-path.js');
let server;
let baseUrl;
@@ -71,6 +88,8 @@ beforeEach(async () => {
fixDraftRules.mockReset().mockResolvedValue({ count: 2, batchId: 'b1' });
assertBrandAccess.mockReset().mockResolvedValue({});
stopDraftRun.mockReset().mockResolvedValue([{ id: 'run-1', claimed_at: CLAIM }]);
+ buildShoppingPath.mockReset().mockResolvedValue({ version: 1, products: [] });
+ shoppingPathSpent = false;
stopDraft = { brand_id: BRAND };
letGo = [];
const app = express();
@@ -415,3 +434,63 @@ describe('POST /api/content-drafts/:draftId/stop', () => {
expect(await res.json()).toMatchObject({ code: 'stopped' });
});
});
+
+describe('POST /api/content-drafts/:draftId/shopping-path', () => {
+ const build = (body, draftId = DRAFT) =>
+ fetch(`${baseUrl}/${draftId}/shopping-path`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+ it("builds the draft's shopping path for a member of the brand", async () => {
+ const res = await build({ brandId: BRAND });
+ expect(res.status).toBe(200);
+ await expect(res.json()).resolves.toEqual({ path: { version: 1, products: [] } });
+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');
+ expect(buildShoppingPath).toHaveBeenCalledWith({ draftId: DRAFT, brandId: BRAND });
+ });
+
+ it("says why a draft has none, and refuses another brand's draft", async () => {
+ buildShoppingPath.mockRejectedValueOnce(new NoShoppingPath('page_type'));
+ await expect((await build({ brandId: BRAND })).json()).resolves.toEqual({
+ path: null,
+ reason: 'page_type',
+ });
+ buildShoppingPath.mockRejectedValueOnce(
+ Object.assign(new Error('Draft not found'), { status: 404 }),
+ );
+ expect((await build({ brandId: BRAND })).status).toBe(404);
+ expect((await build({ brandId: 'nope' })).status).toBe(400);
+ });
+
+ it('says when the path changed while it was built, and when the bucket is spent', async () => {
+ buildShoppingPath.mockRejectedValueOnce(
+ Object.assign(new Error('The shopping path changed while it was built'), {
+ status: 409,
+ code: 'changed',
+ }),
+ );
+ const changed = await build({ brandId: BRAND });
+ expect(changed.status).toBe(409);
+ expect(await changed.json()).toMatchObject({ code: 'changed' });
+ buildShoppingPath.mockRejectedValueOnce(new NoShoppingPath('no_match'));
+ await expect((await build({ brandId: BRAND })).json()).resolves.toEqual({
+ path: null,
+ reason: 'no_match',
+ });
+ shoppingPathSpent = true;
+ expect((await build({ brandId: BRAND })).status).toBe(429);
+ expect(buildShoppingPath).toHaveBeenCalledTimes(2);
+ });
+
+ it("answers 502 when the path can't be built", async () => {
+ buildShoppingPath.mockRejectedValueOnce(new Error('catalog_variants read: timeout'));
+ const res = await build({ brandId: BRAND });
+ expect(res.status).toBe(502);
+ expect(await res.json()).toEqual({
+ error: 'The shopping path could not be built',
+ code: 'failed',
+ });
+ });
+});
diff --git a/supabase/migrations/00351_content_draft_shopping_path.sql b/supabase/migrations/00351_content_draft_shopping_path.sql
new file mode 100644
index 000000000..87bb11e6a
--- /dev/null
+++ b/supabase/migrations/00351_content_draft_shopping_path.sql
@@ -0,0 +1,28 @@
+-- ============================================================================
+-- 00351: a draft's shopping path (shopping path, part 2)
+-- ============================================================================
+-- On an online shop, a buying guide, a best-of list or a comparison should
+-- send its readers, and the AI answers that quote it, to the right category
+-- page and to products that are in stock and that Google Merchant Center
+-- accepts. The API picks them from the brand's catalog (00278, 00296, 00350)
+-- for the draft's topic; the Brief tab shows them, the person swaps, removes,
+-- locks or adds, and the Content Agent writes with them.
+--
+-- * content_drafts.shopping_path: the path as jsonb — {version, builtAt,
+-- pageType, categories: [{name, url, title}], products: [{id, title,
+-- url, price, salePrice, currency, availability, image, issues, score}],
+-- leftOut: [{id, title, reason}], locked, removed, added}. Null until
+-- built, and for a page or a brand it doesn't fit. A member changes it
+-- like the brief, so it isn't a server column.
+
+alter table public.content_drafts
+ add column if not exists shopping_path jsonb
+ check (
+ shopping_path is null
+ or (jsonb_typeof(shopping_path) = 'object' and octet_length(shopping_path::text) <= 65536)
+ );
+
+comment on column public.content_drafts.shopping_path is
+ 'The draft''s shopping path (shopping path, part 2): the category pages and catalog products the page links, the products left out and why, and the person''s locks, removals and additions. Null until built.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 817bd883b..950462176 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -41755,3 +41755,35 @@ comment on function public.catalog_category_counts(uuid) is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00351_content_draft_shopping_path.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00351: a draft's shopping path (shopping path, part 2)
+-- ============================================================================
+-- On an online shop, a buying guide, a best-of list or a comparison should
+-- send its readers, and the AI answers that quote it, to the right category
+-- page and to products that are in stock and that Google Merchant Center
+-- accepts. The API picks them from the brand's catalog (00278, 00296, 00350)
+-- for the draft's topic; the Brief tab shows them, the person swaps, removes,
+-- locks or adds, and the Content Agent writes with them.
+--
+-- * content_drafts.shopping_path: the path as jsonb — {version, builtAt,
+-- pageType, categories: [{name, url, title}], products: [{id, title,
+-- url, price, salePrice, currency, availability, image, issues, score}],
+-- leftOut: [{id, title, reason}], locked, removed, added}. Null until
+-- built, and for a page or a brand it doesn't fit. A member changes it
+-- like the brief, so it isn't a server column.
+
+alter table public.content_drafts
+ add column if not exists shopping_path jsonb
+ check (
+ shopping_path is null
+ or (jsonb_typeof(shopping_path) = 'object' and octet_length(shopping_path::text) <= 65536)
+ );
+
+comment on column public.content_drafts.shopping_path is
+ 'The draft''s shopping path (shopping path, part 2): the category pages and catalog products the page links, the products left out and why, and the person''s locks, removals and additions. Null until built.';
+
+notify pgrst, 'reload schema';
+