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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(action-center): open a Fix action for a live page that links products no longer for sale, and close it once fixed (shopping path, part 7b) (#1616)
Cihan75ec934f3a83
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex bb61de07a..46e4e9a1e 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -209,6 +209,7 @@ Most actions are generated from signals each night. You can also send work to th| **AI Traffic** | On the [AI Traffic Analytics](/guides/ai-traffic-analytics) pages list, select pages under *Cited, not clicked* or *No AI traffic* and click **Send to Action Center**. Traffic drops and strong or weak landing pages also arrive as signals. || **Insights** | **Send action** on a topic in Insights' Opportunities opens a Growth action for it. || **Prompts** | **Send Actions** on a prompt's Improve tab sends the selected suggestions as one action. |+| **Product catalog** | After each catalog sync, a published page that links products that are sold out, refused by Merchant Center or gone from your catalog gets a Fix action with one task: swap them for products in stock. The next sync, or **Check now** on the task, closes it once the live page links none of them. See [Content Editor](/guides/content-editor). |Sending the same thing twice doesn't create a second action: the page says it is already in the Action Center, with its action number (for example `AC-42`).diff --git a/server/src/lib/action-center/from-shopping-check.js b/server/src/lib/action-center/from-shopping-check.jsnew file mode 100644index 000000000..cd9c7c0ac--- /dev/null+++ b/server/src/lib/action-center/from-shopping-check.js@@ -0,0 +1,325 @@+/**+ * A published page that links products no longer for sale (shopping path,+ * part 7): after each catalog sync the shopping check reads the live page+ * again (shopping-check.js), and a page linking a product that is sold out,+ * refused by Merchant Center or gone from the catalog gets a Fix action with+ * one task: swap them for products that sell, the page's own shopping path+ * naming the ones in stock.+ *+ * The same check closes it, after a sync or by Check now on its task+ * (action-center/task-checks.js): once the live page links none of them,+ * its task is completed as checked automatically (AC-010's task_checked),+ * and the action too unless someone added work to it, each in its History.+ * One open action per page (its draft). A page whose action+ * someone dismissed isn't raised again for the same products; one closed+ * while they still don't sell waits REST_DAYS. Nothing is measured+ * afterwards (no KPI): the page links them or it doesn't.+ */++import supabaseAdmin from '../../config/supabase.js';+import { priorityOnCreate } from './priority-data.js';++export const SHOPPING_LINKS_ACTION_KIND = 'shopping_links';++/** A completed action's products, still linked, wait this long for a new one. */+export const REST_DAYS = 7;++const ACTIVE = ['new', 'in_progress', 'on_hold'];+const OPEN_TASKS = ['todo', 'in_progress'];+const DAY_MS = 86_400_000;+/** The products a task names; the rest it counts. */+const NAMED = 3;+/** A product's name in a task's text. */+const NAME_CHARS = 60;+/** The task this module writes, by its details' source: the one the check completes. */+const TASK_SOURCE = 'shopping_check';++/** One open action per page: its draft's. */+export function shoppingLinksDedupKey(draftId) {+ return `${SHOPPING_LINKS_ACTION_KIND}:${draftId}`;+}++const STATE_TEXT = {+ sold_out: 'is sold out',+ refused: 'is refused by Merchant Center',+ gone: 'is no longer in your catalog',+};++const nameOf = (product) => {+ const title = String(product?.title ?? '').trim() || 'A product';+ return title.length > NAME_CHARS ? `${title.slice(0, NAME_CHARS - 1)}…` : title;+};++/** "A", "A and B", "A, B and C", "A, B, C and 2 more". */+function names(products) {+ const named = products.slice(0, NAMED).map(nameOf);+ const more = products.length - named.length;+ if (more > 0) return `${named.join(', ')} and ${more} more`;+ if (named.length < 2) return named.join('');+ return `${named.slice(0, -1).join(', ')} and ${named.at(-1)}`;+}++/**+ * The task: what no longer sells and why, the steps, the products of the+ * page's path to link instead, and how it's done. Checked by the next+ * catalog sync's shopping check, or now by Check now on its draft+ * (`draftId`), not by the nightly page sweep: it reads no change text.+ *+ * @param {{ draftId: string, pageUrl: string, bad: Array<{ title: string, state: string }>,+ * swaps: Array<{ title: string }> }} page+ */+export function shoppingLinksTask({ draftId, pageUrl, bad, swaps }) {+ const reasons = bad+ .slice(0, NAMED)+ .map((p) => `${nameOf(p)} ${STATE_TEXT[p.state] ?? STATE_TEXT.gone}`)+ .join('; ');+ const more = bad.length > NAMED ? `; and ${bad.length - NAMED} more` : '';+ return {+ title:+ bad.length === 1+ ? 'Swap the product that no longer sells'+ : `Swap the ${bad.length} products that no longer sell`,+ details: {+ source: TASK_SOURCE,+ draftId,+ url: pageUrl,+ where: pageUrl,+ why: `${reasons}${more}. Readers and AI answers that follow those links land on a product they can't buy.`,+ how: [+ 'Open the page in the Content Editor.',+ `Remove or replace the links to ${names(bad)}.`,+ ...(swaps.length+ ? [`Link ${names(swaps)} instead: in stock, from the page's shopping path.`]+ : []),+ 'Publish the page again.',+ ],+ doneWhen:+ 'The page links no product that is sold out, refused or gone. Checked automatically after the next catalog sync.',+ check: 'auto',+ type: 'content',+ effort: '~15m',+ role: 'Content editor',+ },+ };+}++/** Whether a closed action already named every one of these products. */+function named(action, ids) {+ const before = new Set(+ Array.isArray(action.payload?.productIds) ? action.payload.productIds : [],+ );+ return ids.every((id) => before.has(id));+}++/**+ * The products each draft's open action names, by draft id. The check+ * counts them on its page even once its path has dropped them (a rebuild+ * keeps the products in stock): the action closes only when the page links+ * none of them that still doesn't sell.+ *+ * @param {string[]} draftIds+ * @returns {Promise<Map<string, string[]>>}+ */+export async function openActionProducts(db, brandId, draftIds) {+ const byDraft = new Map();+ if (!draftIds.length) return byDraft;+ const drafts = new Map(draftIds.map((id) => [shoppingLinksDedupKey(id), id]));+ const { data, error } = await db+ .from('actions')+ .select('dedup_key, payload')+ .eq('brand_id', brandId)+ .eq('kind', SHOPPING_LINKS_ACTION_KIND)+ .in('status', ACTIVE)+ .in('dedup_key', [...drafts.keys()]);+ if (error) throw new Error(`actions read: ${error.message}`);+ for (const action of data ?? []) {+ const draftId = drafts.get(action.dedup_key);+ const ids = action.payload?.productIds;+ if (!draftId || !Array.isArray(ids)) continue;+ byDraft.set(draftId, [+ ...new Set([...(byDraft.get(draftId) ?? []), ...ids.filter((id) => typeof id === 'string')]),+ ]);+ }+ return byDraft;+}++/** The page's actions, newest first: the open one, else the last closed. */+async function pageActions(db, brandId, dedupKey) {+ const { data, error } = await db+ .from('actions')+ .select('id, action_no, status, completed_at, updated_at, created_at, payload')+ .eq('brand_id', brandId)+ .eq('dedup_key', dedupKey)+ .order('created_at', { ascending: false })+ .limit(20);+ if (error) throw new Error(`actions read: ${error.message}`);+ return data ?? [];+}++/**+ * Completes the check's open task as checked automatically on `pageUrl`+ * (its card's last check, and AC-010's task_checked line in the History)+ * and, when no other work is open on it, the action, with its line too. A+ * task or an action someone changed meanwhile is left as it is.+ */+async function closeAction(db, action, pageUrl, now) {+ const at = now.toISOString();+ const { data: tasks, error } = await db+ .from('action_tasks')+ .select('id, title, status, details')+ .eq('action_id', action.id)+ .in('status', OPEN_TASKS);+ if (error) throw new Error(`action_tasks read: ${error.message}`);+ const own = (tasks ?? []).filter((task) => task.details?.source === TASK_SOURCE);+ let completed = 0;+ for (const task of own) {+ const autoCheck = { at, triedAt: at, url: pageUrl, passed: true, missing: [] };+ const { data: changed, error: taskErr } = await db+ .from('action_tasks')+ .update({+ status: 'completed',+ skip_reason: null,+ details: { ...task.details, autoCheck },+ updated_at: at,+ })+ .eq('id', task.id)+ .eq('status', task.status)+ .select('id');+ if (taskErr) throw new Error(`action_tasks write: ${taskErr.message}`);+ if (!changed?.length) continue;+ completed += 1;+ // Best effort, as the drawer's: a missing History line doesn't undo the change.+ await db.from('action_events').insert({+ action_id: action.id,+ event: 'task_checked',+ data: { taskId: task.id, task: null, title: task.title ?? null },+ actor_id: null,+ });+ }+ // Someone's own work on it is theirs to finish; the action moves up its list.+ if ((tasks ?? []).length > own.length) {+ if (completed) await db.from('actions').update({ updated_at: at }).eq('id', action.id);+ return false;+ }+ const { data: closed, error: closeErr } = await db+ .from('actions')+ .update({ status: 'completed', completed_at: at, updated_at: at })+ .eq('id', action.id)+ .eq('status', action.status)+ .select('id');+ if (closeErr) throw new Error(`actions write: ${closeErr.message}`);+ if (!closed?.length) return false;+ await db.from('action_events').insert({+ action_id: action.id,+ event: 'status_changed',+ data: { to: 'completed', source: TASK_SOURCE },+ actor_id: null,+ });+ return true;+}++/**+ * Opens the page's action from its live page's check, keeps it, or closes+ * it. Returns 'opened', 'closed', 'kept' (still open: it links them still,+ * or someone's work on it is open), 'resting' (dismissed for these products,+ * or closed less than REST_DAYS ago), 'held' (none opened: `open` is false)+ * or 'none'.+ *+ * @param {string} brandId+ * @param {{ draft: { id: string, title?: string|null }, pageUrl: string,+ * check: { bad: Array<{ id: string, title: string, state: string }>,+ * swaps: Array<{ id: string, title: string }> } }} page+ * @param {{ db?: object, now?: Date, open?: boolean }} [opts]+ * `open` false: the run's new actions are spent, only close or keep.+ */+export async function syncShoppingLinksAction(+ brandId,+ { draft, pageUrl, check },+ { db = supabaseAdmin, now = new Date(), open = true } = {},+) {+ const dedupKey = shoppingLinksDedupKey(draft.id);+ const actions = await pageActions(db, brandId, dedupKey);+ const active = actions.find((a) => ACTIVE.includes(a.status));+ if (!check.bad.length) {+ if (!active) return 'none';+ return (await closeAction(db, active, pageUrl, now)) ? 'closed' : 'kept';+ }+ if (active) return 'kept';++ const ids = check.bad.map((p) => p.id);+ const last = actions[0];+ if (last && named(last, ids)) {+ if (last.status === 'dismissed') return 'resting';+ const closedAt = Date.parse(last.completed_at ?? last.updated_at ?? '') || 0;+ if (now.getTime() - closedAt < REST_DAYS * DAY_MS) return 'resting';+ }+ if (!open) return 'held';++ const title = String(draft.title ?? '').trim() || null;+ const payload = {+ source: TASK_SOURCE,+ draftId: draft.id,+ title,+ pageUrl,+ // Its page, for the drawer and the task's check (AC-010's onePage).+ pages: [pageUrl],+ products: check.bad,+ productIds: ids,+ soldOut: check.bad.every((p) => p.state === 'sold_out'),+ swaps: check.swaps,+ targetEntity: 'pages',+ targetCount: 1,+ targetIds: [pageUrl],+ targets: [{ id: pageUrl, label: title ?? pageUrl }],+ };+ const category = 'fix';+ const impact = check.bad.length >= 3 ? 'high' : 'medium';+ const { data: action, error } = await db+ .from('actions')+ .insert({+ brand_id: brandId,+ category,+ kind: SHOPPING_LINKS_ACTION_KIND,+ definition_version: 1,+ impact,+ status: 'new',+ payload,+ kpi_keys: [],+ baseline: { capturedAt: now.toISOString(), products: ids.length },+ dedup_key: dedupKey,+ ...(await priorityOnCreate(+ { kind: SHOPPING_LINKS_ACTION_KIND, category, impact, payload },+ now,+ )),+ })+ .select('id, action_no')+ .single();+ if (error) {+ // A check running beside this one opened it (the open-action dedup index, 00084).+ if (error.code === '23505') return 'kept';+ throw new Error(`actions write: ${error.message}`);+ }++ const task = shoppingLinksTask({+ draftId: draft.id,+ pageUrl,+ bad: check.bad,+ swaps: check.swaps,+ });+ const { error: taskErr } = await db.from('action_tasks').insert({+ action_id: action.id,+ position: 1,+ title: task.title,+ details: task.details,+ status: 'todo',+ });+ if (taskErr) throw new Error(`action_tasks write: ${taskErr.message}`);++ await db.from('action_events').insert({+ action_id: action.id,+ event: 'created',+ actor_id: null,+ data: { source: TASK_SOURCE, draftId: draft.id, products: ids.length, taskCount: 1 },+ });+ return 'opened';+}diff --git a/server/src/lib/action-center/from-shopping-check.test.js b/server/src/lib/action-center/from-shopping-check.test.jsnew file mode 100644index 000000000..242563957--- /dev/null+++ b/server/src/lib/action-center/from-shopping-check.test.js@@ -0,0 +1,289 @@+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 {+ REST_DAYS,+ SHOPPING_LINKS_ACTION_KIND,+ shoppingLinksDedupKey,+ shoppingLinksTask,+ syncShoppingLinksAction,+} from './from-shopping-check.js';++/** A live page linking products that no longer sell (shopping path, part 7). */++const BRAND = 'brand-1';+const NOW = new Date('2026-10-27T09:00:00Z');+const PAGE = 'https://shop.example/blog/rain-jackets';+const DRAFT = { id: 'd1', title: 'Best rain jackets for 2026' };++const bad = (id, state = 'sold_out', title = `Jacket ${id}`) => ({ id, title, state });+const page = (badProducts, swaps = []) => ({+ draft: DRAFT,+ pageUrl: PAGE,+ check: { bad: badProducts, swaps },+});++describe('shoppingLinksTask', () => {+ it("names what no longer sells and why, the path's products to link instead, and how it's done", () => {+ const task = shoppingLinksTask({+ draftId: 'd1',+ pageUrl: PAGE,+ bad: [bad('p1', 'sold_out', 'Storm Shell 2'), bad('p2', 'refused', 'Pack-Lite Jacket')],+ swaps: [+ { id: 'p3', title: 'Storm Shell 3' },+ { id: 'p4', title: 'Pack-Lite Pro' },+ ],+ });+ expect(task.title).toBe('Swap the 2 products that no longer sell');+ expect(task.details).toMatchObject({+ source: 'shopping_check',+ draftId: 'd1',+ url: PAGE,+ where: PAGE,+ check: 'auto',+ type: 'content',+ });+ expect(task.details.why).toBe(+ "Storm Shell 2 is sold out; Pack-Lite Jacket is refused by Merchant Center. Readers and AI answers that follow those links land on a product they can't buy.",+ );+ expect(task.details.how).toEqual([+ 'Open the page in the Content Editor.',+ 'Remove or replace the links to Storm Shell 2 and Pack-Lite Jacket.',+ "Link Storm Shell 3 and Pack-Lite Pro instead: in stock, from the page's shopping path.",+ 'Publish the page again.',+ ]);+ expect(task.details.doneWhen).toMatch(/after the next catalog sync/);+ // No change text: the nightly page sweep (AC-010) leaves it to the shopping check.+ expect(task.details.change).toBeUndefined();+ });++ it('names three products and counts the rest, and has no swap step without products to swap in', () => {+ const task = shoppingLinksTask({+ pageUrl: PAGE,+ bad: [bad('a'), bad('b'), bad('c'), bad('d', 'gone'), bad('e', 'sold_out', '')],+ swaps: [],+ });+ expect(task.title).toBe('Swap the 5 products that no longer sell');+ expect(task.details.why).toMatch(+ /^Jacket a is sold out; Jacket b .*; Jacket c .*; and 2 more\./,+ );+ expect(task.details.how).toEqual([+ 'Open the page in the Content Editor.',+ 'Remove or replace the links to Jacket a, Jacket b, Jacket c and 2 more.',+ 'Publish the page again.',+ ]);+ const one = shoppingLinksTask({ pageUrl: PAGE, bad: [bad('a', 'gone', '')], swaps: [] });+ expect(one.title).toBe('Swap the product that no longer sells');+ expect(one.details.why).toMatch(/^A product is no longer in your catalog\./);+ });++ it('keeps a long name short in the steps', () => {+ const task = shoppingLinksTask({+ pageUrl: PAGE,+ bad: [bad('a', 'sold_out', 'x'.repeat(200))],+ swaps: [],+ });+ expect(task.details.how[1].length).toBeLessThan(120);+ });+});++describe('syncShoppingLinksAction', () => {+ it('opens a Fix action with one task and a History line for a live page linking a sold-out product', async () => {+ const fake = fakeDb();+ const result = await syncShoppingLinksAction(+ BRAND,+ page([bad('p1', 'sold_out', 'Storm Shell 2')], [{ id: 'p3', title: 'Storm Shell 3' }]),+ { db: fake.db, now: NOW },+ );+ expect(result).toBe('opened');+ const [action] = fake.rows('actions');+ expect(action).toMatchObject({+ brand_id: BRAND,+ kind: SHOPPING_LINKS_ACTION_KIND,+ category: 'fix',+ impact: 'medium',+ kpi_keys: [],+ dedup_key: shoppingLinksDedupKey('d1'),+ payload: {+ source: 'shopping_check',+ draftId: 'd1',+ title: 'Best rain jackets for 2026',+ pageUrl: PAGE,+ pages: [PAGE],+ productIds: ['p1'],+ soldOut: true,+ swaps: [{ id: 'p3', title: 'Storm Shell 3' }],+ targetEntity: 'pages',+ targetCount: 1,+ targets: [{ id: PAGE, label: 'Best rain jackets for 2026' }],+ },+ });+ expect(action.priority_score).toEqual(expect.any(Number));+ const [task] = fake.rows('action_tasks');+ expect(task).toMatchObject({+ action_id: action.id,+ position: 1,+ title: 'Swap the product that no longer sells',+ status: 'todo',+ });+ expect(fake.rows('action_events')).toEqual([+ expect.objectContaining({ action_id: action.id, event: 'created', actor_id: null }),+ ]);+ });++ it('weighs three or more products as high impact, and says when not all are sold out', async () => {+ const fake = fakeDb();+ await syncShoppingLinksAction(BRAND, page([bad('a'), bad('b', 'refused'), bad('c')]), {+ db: fake.db,+ now: NOW,+ });+ expect(fake.rows('actions')[0]).toMatchObject({+ impact: 'high',+ payload: { soldOut: false },+ });+ });++ it('keeps the open action while the page still links them: no second one', async () => {+ const fake = fakeDb();+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: NOW });+ const again = await syncShoppingLinksAction(BRAND, page([bad('p1'), bad('p2')]), {+ db: fake.db,+ now: NOW,+ });+ expect(again).toBe('kept');+ expect(fake.rows('actions')).toHaveLength(1);+ expect(fake.rows('action_tasks')).toHaveLength(1);+ });++ it('completes its task as checked automatically and the action, each in its History, once the page links none', async () => {+ const fake = fakeDb();+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: NOW });+ fake.rows('actions')[0].status = 'in_progress';+ const later = new Date('2026-10-28T09:00:00Z');+ const result = await syncShoppingLinksAction(BRAND, page([]), { db: fake.db, now: later });+ expect(result).toBe('closed');+ expect(fake.rows('actions')[0]).toMatchObject({+ status: 'completed',+ completed_at: later.toISOString(),+ });+ const [task] = fake.rows('action_tasks');+ expect(task).toMatchObject({ status: 'completed', skip_reason: null });+ // Its card's last check, as AC-010's checks keep it; the task's own details stay.+ expect(task.details).toMatchObject({+ source: 'shopping_check',+ draftId: 'd1',+ autoCheck: {+ at: later.toISOString(),+ triedAt: later.toISOString(),+ url: PAGE,+ passed: true,+ missing: [],+ },+ });+ // AC-010's line: "Checked automatically and done: {task}{title}".+ expect(fake.rows('action_events').map((e) => [e.event, e.data])).toEqual([+ ['created', expect.any(Object)],+ [+ 'task_checked',+ { taskId: task.id, task: null, title: 'Swap the product that no longer sells' },+ ],+ ['status_changed', { to: 'completed', source: 'shopping_check' }],+ ]);+ });++ it("leaves the action open when someone's own task on it is still open", async () => {+ const fake = fakeDb();+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: NOW });+ const [action] = fake.rows('actions');+ fake.rows('action_tasks').push({+ id: 't-own',+ action_id: action.id,+ position: 2,+ title: 'Tell the store team',+ status: 'todo',+ details: null,+ });+ const later = new Date('2026-10-28T09:00:00Z');+ const result = await syncShoppingLinksAction(BRAND, page([]), { db: fake.db, now: later });+ expect(result).toBe('kept');+ expect(action.status).toBe('new');+ // Its task done, the action moves up its list.+ expect(action.updated_at).toBe(later.toISOString());+ const statuses = Object.fromEntries(fake.rows('action_tasks').map((t) => [t.title, t.status]));+ expect(statuses).toEqual({+ 'Swap the product that no longer sells': 'completed',+ 'Tell the store team': 'todo',+ });+ });++ it("opens nothing for a page that links none, and none past the run's cap", async () => {+ const fake = fakeDb();+ expect(await syncShoppingLinksAction(BRAND, page([]), { db: fake.db, now: NOW })).toBe('none');+ expect(+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), {+ db: fake.db,+ now: NOW,+ open: false,+ }),+ ).toBe('held');+ expect(fake.rows('actions')).toHaveLength(0);+ });++ it("doesn't raise the same products again once dismissed; a newly sold-out one does", async () => {+ const fake = fakeDb();+ await syncShoppingLinksAction(BRAND, page([bad('p1'), bad('p2')]), { db: fake.db, now: NOW });+ Object.assign(fake.rows('actions')[0], {+ status: 'dismissed',+ created_at: '2026-10-27T09:00:00Z',+ });+ const month = new Date('2026-11-27T09:00:00Z');+ expect(+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: month }),+ ).toBe('resting');+ expect(+ await syncShoppingLinksAction(BRAND, page([bad('p1'), bad('p9')]), {+ db: fake.db,+ now: month,+ }),+ ).toBe('opened');+ expect(fake.rows('actions')).toHaveLength(2);+ });++ it(`raises a closed action's products again only after ${REST_DAYS} days`, async () => {+ const fake = fakeDb();+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: NOW });+ // Marked done by hand while the page still links it.+ Object.assign(fake.rows('actions')[0], {+ status: 'completed',+ completed_at: NOW.toISOString(),+ created_at: NOW.toISOString(),+ });+ const soon = new Date(NOW.getTime() + (REST_DAYS - 1) * 86_400_000);+ expect(+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: soon }),+ ).toBe('resting');+ const after = new Date(NOW.getTime() + (REST_DAYS + 1) * 86_400_000);+ expect(+ await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: after }),+ ).toBe('opened');+ });++ it("reads only this brand's actions for the page", async () => {+ const fake = fakeDb();+ fake.rows('actions').push({+ id: 'other',+ brand_id: 'brand-2',+ dedup_key: shoppingLinksDedupKey('d1'),+ status: 'new',+ payload: {},+ });+ expect(await syncShoppingLinksAction(BRAND, page([bad('p1')]), { db: fake.db, now: NOW })).toBe(+ 'opened',+ );+ });+});diff --git a/server/src/lib/action-center/priority.js b/server/src/lib/action-center/priority.jsindex e42a8b5ba..8ad5724f5 100644--- a/server/src/lib/action-center/priority.js+++ b/server/src/lib/action-center/priority.js@@ -329,7 +329,8 @@ function confidenceOf(signals) {/*** What an action sent by a person rests on, without detection signals: an* Improve action names its platforms and their state, a content opportunity- * its prompts. Read from the action's own payload.+ * its prompts. Read from the action's own payload. The shopping check's+ * actions (from-shopping-check.js) have no signals either.*/function sentByHand(action) {const p = action.payload ?? {};@@ -364,6 +365,17 @@ function sentByHand(action) {subject: { entity: p.targetEntity ?? 'prompts', count: p.targetCount ?? null },};}+ // A live page linking products that no longer sell (shopping path, part 7):+ // the catalog says so, and swapping the links is quick work.+ if (action.kind === 'shopping_links') {+ return {+ change: 'issue',+ severity: 0.6,+ confidence: 0.9,+ recoverability: 0.9,+ subject: { entity: 'pages', count: 1 },+ };+ }// Pages sent from AI Traffic (AT-006). Answers citing a page nobody clicks// rest on two sources, citations and traffic, and the page already earns// the answer; a page AI skips rests on traffic alone.diff --git a/server/src/lib/action-center/priority.test.js b/server/src/lib/action-center/priority.test.jsindex 449659384..b4a790fad 100644--- a/server/src/lib/action-center/priority.test.js+++ b/server/src/lib/action-center/priority.test.js@@ -363,6 +363,26 @@ describe('scorePriority', () => {expect(sent('no_ai_traffic', { valueSignal: 'revenue' }).reason.commercial).toBe(true);});+ it('scores a live page linking products that no longer sell as a sure, quick fix (shopping path, part 7)', () => {+ const linked = scorePriority(+ {+ action: action({+ kind: 'shopping_links',+ category: 'fix',+ impact: 'medium',+ created_at: daysAgo(0),+ payload: { source: 'shopping_check', targetEntity: 'pages', targetCount: 1 },+ }),+ },+ NOW,+ );+ expect(linked.reason).toMatchObject({+ change: 'issue',+ subject: { entity: 'pages', count: 1 },+ });+ expect(linked.reason.factors).toMatchObject({ severity: 0.6, confidence: 0.9 });+ });+it('stays within 0–100 and returns whole numbers', () => {for (const impact of ['high', 'medium', 'low', 'unknown']) {const { score } = scorePriority({ action: action({ impact }), signals: [] }, NOW);diff --git a/server/src/lib/action-center/task-checks.js b/server/src/lib/action-center/task-checks.jsindex aea6cc395..3968e7699 100644--- a/server/src/lib/action-center/task-checks.js+++ b/server/src/lib/action-center/task-checks.js@@ -14,7 +14,10 @@* rotating quote moving (optimize, refresh, strengthen, the call to* action): the first look keeps a sketch of the page's words, and* enough of them must have changed;- * - a written task's new text is on it, and the text it replaces gone.+ * - a written task's new text is on it, and the text it replaces gone;+ * - a shopping links task's page links no product that no longer sells,+ * read as the catalog sync's shopping check reads it (shopping-check.js;+ * Check now only: the sync checks it, not the sweep).** A task that passes is completed, with the check kept on it and a line in* the action's History; one that doesn't keeps what is missing, for its@@ -29,6 +32,7 @@ import * as cheerio from 'cheerio';import supabaseAdmin from '../../config/supabase.js';import { logger } from '../logger.js';import { fetchPage } from '../safe-fetch.js';+import { checkShoppingDraft } from '../shopping-check.js';import { furnitureNamed } from '../page-content.js';import { onBrandDomain } from '../audit/host.js';import { aiBotAccess } from '../audit/signals/trust.js';@@ -101,10 +105,14 @@ const PASS_ONLY = new Set(['json-ld-validity']);const text = (value) => (typeof value === 'string' ? value.trim() : '');+/** A shopping links task's mark (action-center/from-shopping-check.js). */+const SHOPPING_SOURCE = 'shopping_check';+/** What a task's check reads, or null when it has none here. */export function checkKind(task) {const d = task.details ?? {};if (d.check !== 'auto' || !text(d.url)) return null;+ if (d.source === SHOPPING_SOURCE) return 'shoppingLinks';if (task.task_key) return CHECKS[task.task_key] ?? null;return text(d.change?.after) ? 'text' : null;}@@ -475,6 +483,46 @@ async function writeCheck(task, details, { completes = false, now }) {return Boolean(updated?.length);}+/**+ * A shopping links task: its draft's page checked again as the catalog sync+ * checks it (checkShoppingDraft), which keeps the Library's row and, once+ * the live page links no product that no longer sells, completes the task+ * with its check kept and closes the action, each in its History+ * (from-shopping-check.js). A page read from its draft (not reached, too+ * short to be the page, off the brand's site) is no answer; a draft with no+ * shopping path left (archived, its path removed) has nothing to check.+ */+async function checkShoppingTask(task, action, { fetch, now }) {+ const d = task.details ?? {};+ if (!text(d.draftId)) return { reason: 'not_checkable' };+ const found = await checkShoppingDraft(action.brand_id, d.draftId, { readPage: fetch, now });+ if (!found) return { reason: 'no_shopping_path' };+ if (found.readFrom !== 'page') {+ await writeCheck(+ task,+ { ...d, autoCheck: { ...(d.autoCheck ?? {}), triedAt: now.toISOString() } },+ { now },+ );+ return { reason: 'no_answer' };+ }+ const autoCheck = {+ at: now.toISOString(),+ triedAt: now.toISOString(),+ url: found.pageUrl,+ passed: !found.bad.length,+ missing: found.bad.length ? ['links_not_for_sale'] : [],+ };+ // Passed: the check completed the task, its autoCheck kept, unless+ // someone changed it meanwhile.+ if (autoCheck.passed) {+ return found.action === 'closed' || found.action === 'kept'+ ? { autoCheck }+ : { reason: 'changed' };+ }+ if (!(await writeCheck(task, { ...d, autoCheck }, { now }))) return { reason: 'changed' };+ return { autoCheck };+}+/*** Checks one task and keeps what it found on it (`details.autoCheck`, with* the page it read): passed, it is completed and the action's History says@@ -483,7 +531,8 @@ async function writeCheck(task, details, { completes = false, now }) {* sweep leaves it (the call is theirs). Returns `{ autoCheck }`, or* `{ reason }` when nothing was checked: 'not_checkable' (no check here),* 'not_open' (done or skipped), 'no_answer' (the page couldn't be read),- * 'changed' (someone changed the task meanwhile).+ * 'changed' (someone changed the task meanwhile), 'no_shopping_path' (a+ * shopping links task whose draft has no path left to check).** @param {{ id: string, action_id: string, task_key: string|null, title?: string|null,* status: string, details: object|null, updated_at?: string }} task@@ -493,6 +542,7 @@ export async function runTaskCheck(task, action, { fetch = fetchPage, now = newconst kind = checkKind(task);if (!kind) return { reason: 'not_checkable' };if (!OPEN.includes(task.status)) return { reason: 'not_open' };+ if (kind === 'shoppingLinks') return checkShoppingTask(task, action, { fetch, now });const d = task.details ?? {};const domains = await brandDomains(action.brand_id);const url = pageAddress(d.url, storedHost(domains[0]));@@ -600,9 +650,15 @@ export async function sweepTaskChecks({if (error) throw new Error(error.message);const since = now.getTime() - RECHECK_AFTER_MS;- const due = (rows ?? []).filter(- (row) => checkKind(row) && !(Date.parse(row.details?.autoCheck?.triedAt ?? '') >= since),- );+ // A shopping links task is checked after each catalog sync, not here.+ const due = (rows ?? []).filter((row) => {+ const kind = checkKind(row);+ return (+ kind &&+ kind !== 'shoppingLinks' &&+ !(Date.parse(row.details?.autoCheck?.triedAt ?? '') >= since)+ );+ });let checked = 0;let passed = 0;for (const row of due) {diff --git a/server/src/lib/action-center/task-checks.test.js b/server/src/lib/action-center/task-checks.test.jsindex 7a4be556e..ba970b5b2 100644--- a/server/src/lib/action-center/task-checks.test.js+++ b/server/src/lib/action-center/task-checks.test.js@@ -48,6 +48,9 @@ function table(name) {vi.mock('../../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));vi.mock('../logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));+// A shopping links task's check: the catalog sync's, on its one draft (shopping-check.js).+const checkShoppingDraft = vi.hoisted(() => vi.fn());+vi.mock('../shopping-check.js', () => ({ checkShoppingDraft }));const {CHANGED_BELOW,@@ -119,6 +122,10 @@ describe('checkKind', () => {).toBeNull();expect(checkKind({ task_key: 'publish_content', details: { check: 'auto' } })).toBeNull();expect(checkKind({ task_key: null, details: auto })).toBeNull();+ // A shopping links task: checked on its draft's page, as the catalog sync checks it.+ expect(+ checkKind({ task_key: null, details: { ...auto, source: 'shopping_check', draftId: 'd1' } }),+ ).toBe('shoppingLinks');});it('puts a path on the brand’s domain, and reads a bare host and path as https', () => {@@ -658,6 +665,99 @@ describe('runTaskCheck', () => {});});+describe('runTaskCheck on a shopping links task', () => {+ const action = { brand_id: 'b1' };+ const LIVE = 'https://acme.example/blog/boots';+ const task = (over = {}) => ({+ id: 't1',+ action_id: 'a1',+ task_key: null,+ title: 'Swap the product that no longer sells',+ status: 'todo',+ updated_at: '2026-10-26T10:00:00Z',+ details: { check: 'auto', url: LIVE, source: 'shopping_check', draftId: 'd1' },+ ...over,+ });+ const now = new Date('2026-10-27T03:00:00Z');+ const at = now.toISOString();+ const fetch = vi.fn();++ beforeEach(() => {+ checkShoppingDraft.mockReset();+ });++ it('checks its draft as the catalog sync does; passed, that check completed it', async () => {+ checkShoppingDraft.mockResolvedValue({+ readFrom: 'page',+ pageUrl: LIVE,+ bad: [],+ action: 'closed',+ });+ expect(await runTaskCheck(task(), action, { fetch, now })).toEqual({+ autoCheck: { at, triedAt: at, url: LIVE, passed: true, missing: [] },+ });+ expect(checkShoppingDraft).toHaveBeenCalledWith('b1', 'd1', { readPage: fetch, now });+ // The task, its History and the action are the shopping check's to write.+ expect(ops).toEqual([]);+ expect(reads.some((r) => r.table === 'brand_domains')).toBe(false);+ });++ it('keeps what is missing on a page that still links a product that no longer sells', async () => {+ checkShoppingDraft.mockResolvedValue({+ readFrom: 'page',+ pageUrl: LIVE,+ bad: [{ id: 'p2', title: 'Boot', state: 'sold_out' }],+ action: 'kept',+ });+ const result = await runTaskCheck(task(), action, { fetch, now });+ expect(result).toEqual({+ autoCheck: { at, triedAt: at, url: LIVE, passed: false, missing: ['links_not_for_sale'] },+ });+ const update = ops.find((op) => op.table === 'action_tasks');+ expect(update.payload).toMatchObject({+ details: { source: 'shopping_check', draftId: 'd1', autoCheck: { passed: false } },+ });+ expect(update.payload.status).toBeUndefined();+ expect(update.filters).toContainEqual(['updated_at', '2026-10-26T10:00:00Z']);+ expect(ops.some((op) => op.table === 'action_events')).toBe(false);+ });++ it("says the page couldn't be read when only its draft was, and keeps the try", async () => {+ checkShoppingDraft.mockResolvedValue({+ readFrom: 'draft',+ pageUrl: null,+ bad: [{ id: 'p2', title: 'Boot', state: 'sold_out' }],+ action: null,+ });+ expect(await runTaskCheck(task(), action, { fetch, now })).toEqual({ reason: 'no_answer' });+ expect(ops.find((op) => op.table === 'action_tasks').payload).toMatchObject({+ details: { autoCheck: { triedAt: at } },+ });+ });++ it('says why nothing was checked: no path left, no draft named, or changed meanwhile', async () => {+ checkShoppingDraft.mockResolvedValue(null);+ expect(await runTaskCheck(task(), action, { fetch, now })).toEqual({+ reason: 'no_shopping_path',+ });+ expect(+ await runTaskCheck(+ task({ details: { check: 'auto', url: LIVE, source: 'shopping_check' } }),+ action,+ { fetch, now },+ ),+ ).toEqual({ reason: 'not_checkable' });+ checkShoppingDraft.mockResolvedValue({+ readFrom: 'page',+ pageUrl: LIVE,+ bad: [],+ action: 'none',+ });+ expect(await runTaskCheck(task(), action, { fetch, now })).toEqual({ reason: 'changed' });+ expect(checkShoppingDraft).toHaveBeenCalledTimes(2);+ });+});+describe('sweepTaskChecks', () => {const now = new Date('2026-10-27T03:00:00Z');const row = (id, over = {}) => ({@@ -701,4 +801,16 @@ describe('sweepTaskChecks', () => {expect(await sweepTaskChecks({ fetch, now })).toEqual({ checked: 1, passed: 1 });expect(fetch).toHaveBeenCalledTimes(1);});++ it('leaves a shopping links task to the catalog sync', async () => {+ db.action_tasks = [+ row('t1', {+ task_key: null,+ details: { check: 'auto', url: PAGE, source: 'shopping_check', draftId: 'd1' },+ }),+ ];+ checkShoppingDraft.mockReset();+ expect(await sweepTaskChecks({ fetch: fetchOf({}), now })).toEqual({ checked: 0, passed: 0 });+ expect(checkShoppingDraft).not.toHaveBeenCalled();+ });});diff --git a/server/src/lib/shopping-check.js b/server/src/lib/shopping-check.jsindex 5fe81a019..bccc9ac5f 100644--- a/server/src/lib/shopping-check.js+++ b/server/src/lib/shopping-check.js@@ -1,5 +1,9 @@import * as cheerio from 'cheerio';import supabaseAdmin from '../config/supabase.js';+import {+ openActionProducts,+ syncShoppingLinksAction,+} from './action-center/from-shopping-check.js';import { isBrandActive } from './active-subscriptions.js';import { onBrandDomain } from './audit/host.js';import { brandSite } from './catalog/category-pages.js';@@ -22,6 +26,9 @@ import { readIn, readShoppingPath, refuses } from './shopping-path.js';* stock), refused (Merchant Center refuses every variant in stock in its free* listings) or gone from the catalog. What it finds is kept per draft in* content_shopping_checks, for the Content Library's Shopping path column.+ * A live page that links one that no longer sells gets a Fix action in the+ * Action Center, closed by the check that finds it fixed+ * (action-center/from-shopping-check.js).** A live page is read only on the brand's site (brandSite), and only when* it reads as the page: one with fewer than MIN_WORDS words (an empty@@ -48,12 +55,16 @@ const PAGE_BYTES = 1024 * 1024;export const MIN_WORDS = 20;/** A check stops reading live pages after this, and reads the rest from their drafts. */export const LIVE_PAGES_DEADLINE_MS = 3 * 60 * 1000;+/** New Action Center actions one check opens at most: the rest wait for the next sync. */+export const MAX_NEW_ACTIONS = 5;/** A link longer than this isn't read: no page's address is (as content_drafts caps its own). */export const MAX_HREF_CHARS = 2048;const TITLE_CHARS = 200;const MAX_BAD = 40;+/** The path's products that sell and the page doesn't link, named to swap in. */+const MAX_SWAPS = 5;/*** Every link's address in a page's HTML, and in the HTML blocks the editor@@ -179,7 +190,8 @@ export function pathProductIds(path) {* (web lib/content/shopping-check.ts): how many of its category pages and* of its products that sell it links, and the products it links that no* longer sell. A product the person removed or the path left out counts- * only when it no longer sells: the page may still link it.+ * only when it no longer sells: the page may still link it. `swaps`: the+ * path's products that sell and the page doesn't link, in its order.** @param {{ states: Map<string, string>, pages: Map<string, string>,* titles?: Map<string, string> }} catalog@@ -226,6 +238,10 @@ export function linkCheck(hrefs, path, { states, pages, titles = new Map() }) {.filter((p) => p.state !== 'ok').map(({ inPath: _inPath, ...p }) => p).slice(0, MAX_BAD),+ swaps: path.products+ .filter((p) => p.url && (states.get(p.id) ?? 'gone') === 'ok' && !keys.has(linkKey(p.url)))+ .slice(0, MAX_SWAPS)+ .map((p) => ({ id: p.id, title: String(p.title ?? '').slice(0, TITLE_CHARS) })),};}@@ -283,11 +299,15 @@ async function primarySite(db, brandId) {return /^https?:\/\//i.test(data.domain) ? data.domain : `https://${data.domain}`;}+/** What a draft's check reads of it. */+const DRAFT_COLUMNS =+ 'id, title, status, method, source_url, published_url, body_html, shopping_path';+/** The brand's drafts with a shopping path, a batch at a time, in id order. */async function draftBatch(db, brandId, from) {const { data, error } = await db.from('content_drafts')- .select('id, status, method, source_url, published_url, body_html, shopping_path')+ .select(DRAFT_COLUMNS).eq('brand_id', brandId).is('archived_at', null).not('shopping_path', 'is', null)@@ -317,12 +337,83 @@ async function dropStale(db, brandId, kept) {}/**- * Checks a brand's pages' shopping links and keeps what it finds.+ * The products each draft's open action names (openActionProducts), or the+ * read's error: then no action of these drafts is synced.+ */+async function heldProducts(db, brandId, draftIds) {+ try {+ return { held: await openActionProducts(db, brandId, draftIds), heldErr: null };+ } catch (err) {+ return { held: new Map(), heldErr: err };+ }+}++/**+ * A path with its open action's products counted as ones the person+ * removed: on its page only while they still don't sell. So a rebuild that+ * dropped them doesn't close the action while the page links them.+ */+function withHeld(path, ids = []) {+ const extra = ids.filter((id) => !path.removed.includes(id));+ return extra.length ? { ...path, removed: [...path.removed, ...extra] } : path;+}++/** Whether a draft's live page may be read: it has one, on the brand's site. */+function readable(draft, domains) {+ const url = livePage(draft);+ return Boolean(url) && onBrandDomain(url, domains);+}++/**+ * A draft's links checked against its path: its live page's when `readLive`+ * and it reads as the page, else the draft's; with its+ * content_shopping_checks row.+ */+async function checkDraft(+ draft,+ path,+ { brandId, catalog, site, domains, readPage, readLive, now },+) {+ const url = livePage(draft);+ const read = readLive ? await liveHrefs(url, readPage, domains) : null;+ // A draft's relative link ("/products/x") is read against its page, else the brand's site.+ const base = url ?? draft.source_url ?? site;+ const inDraft = linkCheck(pageHrefs(draft.body_html, base), path, catalog);+ const onPage = read ? linkCheck(read, path, catalog) : null;+ // A live page that links none of the path while its draft does wasn't+ // read as it is (a shell its script fills, a page served to bots): its+ // draft is read.+ const fromPage = Boolean(onPage) && (linksPath(onPage) || !linksPath(inDraft));+ const check = fromPage ? onPage : inDraft;+ return {+ url,+ fromPage,+ check,+ row: {+ draft_id: draft.id,+ brand_id: brandId,+ read_from: fromPage ? 'page' : 'draft',+ page_url: fromPage ? url : null,+ categories: check.categories,+ categories_linked: check.categoriesLinked,+ products: check.products,+ products_linked: check.productsLinked,+ bad: check.bad,+ checked_at: now.toISOString(),+ },+ };+}++/**+ * Checks a brand's pages' shopping links and keeps what it finds; a live+ * page's Action Center action is opened or closed by what it found. A+ * failure there is logged and the check goes on.** @param {string} brandId* @param {{ db?: object, now?: Date, readPage?: Function, livePages?: number }} [opts]* `readPage` reads a live page (safe-fetch's fetchPage); tests pass their own.- * @returns {Promise<{ drafts: number, live: number, attention: number, dropped: number }>}+ * @returns {Promise<{ drafts: number, live: number, attention: number, dropped: number,+ * opened: number, closed: number }>}*/export async function checkShoppingLinks(brandId,@@ -334,52 +425,48 @@ export async function checkShoppingLinks(const kept = new Set();let live = 0;let attention = 0;+ let opened = 0;+ let closed = 0;// Whether every draft with a path was read: only then is a row no draft// was read for a stale one.let complete = false;for (let from = 0; from < MAX_DRAFTS; from += DRAFT_BATCH) {const drafts = await draftBatch(db, brandId, from);- const paths = drafts+ const read = drafts.map((d) => ({ draft: d, path: readShoppingPath(d.shopping_path, { draftId: d.id }) })).filter((d) => d.path);+ const { held, heldErr } = await heldProducts(+ db,+ brandId,+ read.map((d) => d.draft.id),+ );+ const paths = read.map((d) => ({ ...d, path: withHeld(d.path, held.get(d.draft.id)) }));const catalog = await productStates(db,brandId,paths.flatMap((d) => pathProductIds(d.path)),);const rows = [];+ const livePagesRead = [];for (const { draft, path } of paths) {- const url = livePage(draft);const canRead =- url &&- onBrandDomain(url, domains) &&+ readable(draft, domains) &&live < livePages &&Date.now() - started < LIVE_PAGES_DEADLINE_MS;- const read = canRead ? await liveHrefs(url, readPage, domains) : null;if (canRead) live += 1;- // A draft's relative link ("/products/x") is read against its page, else the brand's site.- const base = url ?? draft.source_url ?? site;- const inDraft = linkCheck(pageHrefs(draft.body_html, base), path, catalog);- const onPage = read ? linkCheck(read, path, catalog) : null;- // A live page that links none of the path while its draft does wasn't- // read as it is (a shell its script fills, a page served to bots): its- // draft is read.- const fromPage = Boolean(onPage) && (linksPath(onPage) || !linksPath(inDraft));- const check = fromPage ? onPage : inDraft;+ const { url, fromPage, check, row } = await checkDraft(draft, path, {+ brandId,+ catalog,+ site,+ domains,+ readPage,+ readLive: canRead,+ now,+ });if (check.bad.length) attention += 1;+ if (fromPage) livePagesRead.push({ draft, pageUrl: url, check });kept.add(draft.id);- rows.push({- draft_id: draft.id,- brand_id: brandId,- read_from: fromPage ? 'page' : 'draft',- page_url: fromPage ? url : null,- categories: check.categories,- categories_linked: check.categoriesLinked,- products: check.products,- products_linked: check.productsLinked,- bad: check.bad,- checked_at: now.toISOString(),- });+ rows.push(row);}if (rows.length) {const { error } = await db@@ -387,13 +474,87 @@ export async function checkShoppingLinks(.upsert(rows, { onConflict: 'draft_id' });if (error) throw new Error(`content_shopping_checks write: ${error.message}`);}+ // Only a live page read now opens or closes its action: a draft isn't+ // what readers see, and a page that couldn't be read says nothing.+ for (const page of livePagesRead) {+ try {+ // Without its open action's products, a check can't tell it's fixed.+ if (heldErr) throw heldErr;+ const done = await syncShoppingLinksAction(brandId, page, {+ db,+ now,+ open: opened < MAX_NEW_ACTIONS,+ });+ if (done === 'opened') opened += 1;+ if (done === 'closed') closed += 1;+ } catch (err) {+ logger.warn(+ { err: { name: err?.name, message: err?.message }, brandId, draftId: page.draft.id },+ '[shopping-check] Action Center action not synced',+ );+ }+ }if (drafts.length < DRAFT_BATCH) {complete = true;break;}}const dropped = complete ? await dropStale(db, brandId, kept) : 0;- return { drafts: kept.size, live, attention, dropped };+ return { drafts: kept.size, live, attention, dropped, opened, closed };+}++/**+ * Checks one draft's page now, as the catalog sync does (Check now on its+ * Action Center task, action-center/task-checks.js): keeps what it finds,+ * and from a live page read opens, keeps or closes its action. A failure+ * there is thrown, for the person who asked. Null when the draft has no+ * shopping path to check (none, archived, or not the brand's).+ *+ * @param {string} brandId+ * @param {string} draftId+ * @param {{ db?: object, now?: Date, readPage?: Function }} [opts]+ * @returns {Promise<null | { readFrom: 'page'|'draft', pageUrl: string|null,+ * bad: Array<{ id: string, title: string, state: string }>, action: string|null }>}+ * `action`: what syncShoppingLinksAction did; null for a draft read.+ */+export async function checkShoppingDraft(+ brandId,+ draftId,+ { db = supabaseAdmin, now = new Date(), readPage = fetchPage } = {},+) {+ const { data: draft, error } = await db+ .from('content_drafts')+ .select(DRAFT_COLUMNS)+ .eq('brand_id', brandId)+ .eq('id', draftId)+ .is('archived_at', null)+ .maybeSingle();+ if (error) throw new Error(`content_drafts read: ${error.message}`);+ const own = draft ? readShoppingPath(draft.shopping_path, { draftId: draft.id }) : null;+ if (!own) return null;+ const { held, heldErr } = await heldProducts(db, brandId, [draft.id]);+ const path = withHeld(own, held.get(draft.id));+ const site = await primarySite(db, brandId);+ const domains = await siteDomains(db, brandId);+ const catalog = await productStates(db, brandId, pathProductIds(path));+ const { url, fromPage, check, row } = await checkDraft(draft, path, {+ brandId,+ catalog,+ site,+ domains,+ readPage,+ readLive: readable(draft, domains),+ now,+ });+ const { error: writeErr } = await db+ .from('content_shopping_checks')+ .upsert([row], { onConflict: 'draft_id' });+ if (writeErr) throw new Error(`content_shopping_checks write: ${writeErr.message}`);+ if (fromPage && heldErr) throw heldErr;+ const action = fromPage+ ? await syncShoppingLinksAction(brandId, { draft, pageUrl: url, check }, { db, now })+ : null;+ return { readFrom: row.read_from, pageUrl: row.page_url, bad: check.bad, action };}/** Brands waiting for their check, with the check's options. */diff --git a/server/src/lib/shopping-check.test.js b/server/src/lib/shopping-check.test.jsindex 7dc7b01d8..7638b3524 100644--- a/server/src/lib/shopping-check.test.js+++ b/server/src/lib/shopping-check.test.js@@ -16,7 +16,9 @@ import {MAX_DRAFTS,MAX_HREF_CHARS,MAX_LIVE_PAGES,+ MAX_NEW_ACTIONS,MIN_WORDS,+ checkShoppingDraft,checkShoppingLinks,linkCheck,linksPath,@@ -268,9 +270,31 @@ describe('linkCheck', () => {products: 1,productsLinked: 1,bad: [{ id: 'p2', title: 'Boot p2', state: 'sold_out' }],+ swaps: [],});});+ it("names the path's products that sell and the page doesn't link, to swap in", () => {+ const check = linkCheck(+ ['https://shop.example/products/p1', 'https://shop.example/products/p2'],+ path([product('p1'), product('p2'), product('p3'), product('p4'), product('p5')]),+ {+ states: new Map([+ ['p1', 'ok'],+ ['p2', 'sold_out'],+ ['p3', 'ok'],+ ['p4', 'refused'],+ ['p5', 'ok'],+ ]),+ pages: new Map(),+ },+ );+ expect(check.swaps).toEqual([+ { id: 'p3', title: 'Boot p3' },+ { id: 'p5', title: 'Boot p5' },+ ]);+ });+it('counts a removed or left-out product the page still links, only when it no longer sells', () => {const removedPath = {...path([product('p1')]),@@ -406,7 +430,14 @@ describe('checkShoppingLinks', () => {html: livePageHtml('<a href="/products/p1">one</a>'),});const result = await checkShoppingLinks(BRAND, { db: fake.db, now: NOW, readPage });- expect(result).toEqual({ drafts: 2, live: 1, attention: 1, dropped: 0 });+ expect(result).toEqual({+ drafts: 2,+ live: 1,+ attention: 1,+ dropped: 0,+ opened: 0,+ closed: 0,+ });expect(readPage).toHaveBeenCalledOnce();expect(readPage.mock.calls[0][0]).toBe('https://shop.example/blog/boots');const rows = Object.fromEntries(@@ -656,6 +687,124 @@ describe('checkShoppingLinks', () => {expect(fake.rows('content_shopping_checks')).toHaveLength(DRAFT_BATCH + 3);});+ it('opens an Action Center action for a live page linking a product that no longer sells, and closes it once fixed', async () => {+ const fake = setup();+ fake.rows('content_drafts').push(+ draft('d1', {+ title: 'Best boots',+ status: 'published',+ published_url: 'https://shop.example/blog/boots',+ }),+ );+ const live = (html) => vi.fn(async (url) => ({ url, status: 200, html: livePageHtml(html) }));+ const first = await checkShoppingLinks(BRAND, {+ db: fake.db,+ now: NOW,+ readPage: live(`${link('p1')} ${link('p2')}`),+ });+ expect(first).toMatchObject({ opened: 1, closed: 0 });+ const [action] = fake.rows('actions');+ expect(action).toMatchObject({+ kind: 'shopping_links',+ dedup_key: 'shopping_links:d1',+ status: 'new',+ payload: {+ title: 'Best boots',+ pageUrl: 'https://shop.example/blog/boots',+ products: [{ id: 'p2', title: 'Boot p2', state: 'sold_out' }],+ },+ });++ const fixed = await checkShoppingLinks(BRAND, {+ db: fake.db,+ now: NOW,+ readPage: live(link('p1')),+ });+ expect(fixed).toMatchObject({ opened: 0, closed: 1 });+ expect(action.status).toBe('completed');+ });++ it('keeps an action open while the page links its products, though a rebuilt path dropped them', async () => {+ const fake = setup();+ catalog(fake, [['p3', [['in_stock', 'c']]]]);+ for (const row of fake.rows('catalog_products')) {+ row.url = `https://shop.example/products/${row.id}`;+ }+ fake.rows('content_drafts').push(+ draft('d1', {+ status: 'published',+ published_url: 'https://shop.example/blog/boots',+ }),+ );+ const live = (html) => vi.fn(async (url) => ({ url, status: 200, html: livePageHtml(html) }));+ const page = `${link('p1')} ${link('p2')}`;+ await checkShoppingLinks(BRAND, { db: fake.db, now: NOW, readPage: live(page) });+ const [action] = fake.rows('actions');+ expect(action.payload.productIds).toEqual(['p2']);++ // A rebuild keeps the products in stock: sold-out p2 drops out of the path.+ fake.rows('content_drafts')[0].shopping_path = path([product('p1'), product('p3')]);+ const synced = await checkShoppingLinks(BRAND, { db: fake.db, now: NOW, readPage: live(page) });+ expect(synced).toMatchObject({ attention: 1, closed: 0 });+ expect(action.status).toBe('new');+ expect(fake.rows('content_shopping_checks')[0].bad).toEqual([+ { id: 'p2', title: 'Boot p2', state: 'sold_out' },+ ]);+ const now = await checkShoppingDraft(BRAND, 'd1', {+ db: fake.db,+ now: NOW,+ readPage: live(page),+ });+ expect(now).toMatchObject({ action: 'kept' });+ expect(action.status).toBe('new');++ const fixed = await checkShoppingDraft(BRAND, 'd1', {+ db: fake.db,+ now: NOW,+ readPage: live(link('p1')),+ });+ expect(fixed).toMatchObject({ bad: [], action: 'closed' });+ expect(action.status).toBe('completed');+ });++ it(`opens none from a draft, and at most ${MAX_NEW_ACTIONS} a run`, async () => {+ const fake = setup();+ fake+ .rows('content_drafts')+ .push(+ draft('d-draft'),+ ...Array.from({ length: MAX_NEW_ACTIONS + 2 }, (_, i) =>+ draft(`d${i}`, { status: 'published', published_url: `https://shop.example/${i}` }),+ ),+ );+ const readPage = vi.fn(async (url) => ({ url, status: 200, html: livePageHtml(link('p2')) }));+ const result = await checkShoppingLinks(BRAND, { db: fake.db, now: NOW, readPage });+ expect(result).toMatchObject({ attention: MAX_NEW_ACTIONS + 3, opened: MAX_NEW_ACTIONS });+ expect(fake.rows('actions')).toHaveLength(MAX_NEW_ACTIONS);+ expect(fake.rows('actions').some((a) => a.payload.draftId === 'd-draft')).toBe(false);+ });++ it("logs an action it can't open and keeps the check", async () => {+ const fake = setup();+ fake+ .rows('content_drafts')+ .push(draft('d1', { status: 'published', published_url: 'https://shop.example/a' }));+ const db = {+ from: (table) => {+ if (table === 'actions') throw new Error('actions unavailable');+ return fake.db.from(table);+ },+ };+ const readPage = vi.fn(async (url) => ({ url, status: 200, html: livePageHtml(link('p2')) }));+ const result = await checkShoppingLinks(BRAND, { db, now: NOW, readPage });+ expect(result).toMatchObject({ drafts: 1, attention: 1, opened: 0 });+ expect(fake.rows('content_shopping_checks')).toHaveLength(1);+ expect(logger.warn).toHaveBeenCalledWith(+ expect.objectContaining({ draftId: 'd1' }),+ '[shopping-check] Action Center action not synced',+ );+ });+it("reads a path it can't read as none, and logs it", async () => {const fake = setup();fake@@ -665,6 +814,96 @@ describe('checkShoppingLinks', () => {expect(result.drafts).toBe(0);expect(logger.warn).toHaveBeenCalled();});++ describe('checkShoppingDraft (Check now on its task)', () => {+ const live = (html) => vi.fn(async (url) => ({ url, status: 200, html: livePageHtml(html) }));++ it('checks one draft as the sync does, keeps its row, and closes its action once fixed', async () => {+ const fake = setup();+ fake+ .rows('content_drafts')+ .push(+ draft('d1', { status: 'published', published_url: 'https://shop.example/blog/boots' }),+ draft('d2'),+ );+ await checkShoppingLinks(BRAND, {+ db: fake.db,+ now: NOW,+ readPage: live(`${link('p1')} ${link('p2')}`),+ });+ expect(fake.rows('actions')).toHaveLength(1);+ const later = new Date('2026-10-28T09:00:00Z');+ const readPage = live(link('p1'));+ const found = await checkShoppingDraft(BRAND, 'd1', { db: fake.db, now: later, readPage });+ expect(found).toEqual({+ readFrom: 'page',+ pageUrl: 'https://shop.example/blog/boots',+ bad: [],+ action: 'closed',+ });+ expect(readPage).toHaveBeenCalledOnce();+ expect(fake.rows('actions')[0].status).toBe('completed');+ const rows = Object.fromEntries(+ fake.rows('content_shopping_checks').map((r) => [r.draft_id, r]),+ );+ expect(rows.d1).toMatchObject({+ read_from: 'page',+ bad: [],+ checked_at: later.toISOString(),+ });+ // The brand's other rows are left as they were: none is stale.+ expect(rows.d2.checked_at).toBe(NOW.toISOString());+ });++ it('reads a page that is no page from its draft, and touches no action', async () => {+ const fake = setup();+ fake+ .rows('content_drafts')+ .push(draft('d1', { status: 'published', published_url: 'https://shop.example/a' }));+ const readPage = vi.fn(async (url) => ({ url, status: 200, html: '<div id="root"></div>' }));+ const found = await checkShoppingDraft(BRAND, 'd1', { db: fake.db, now: NOW, readPage });+ expect(found).toEqual({+ readFrom: 'draft',+ pageUrl: null,+ bad: [{ id: 'p2', title: 'Boot p2', state: 'sold_out' }],+ action: null,+ });+ expect(fake.rows('actions')).toHaveLength(0);+ });++ it("has nothing to check for an archived draft, one without a path, or another brand's", async () => {+ const fake = setup();+ fake+ .rows('content_drafts')+ .push(+ draft('d-archived', { archived_at: '2026-10-20T00:00:00Z' }),+ draft('d-none', { shopping_path: null }),+ draft('d-other', { brand_id: 'brand-2' }),+ );+ for (const id of ['d-archived', 'd-none', 'd-other', 'd-missing']) {+ expect(await checkShoppingDraft(BRAND, id, { db: fake.db, now: NOW })).toBeNull();+ }+ expect(fake.rows('content_shopping_checks')).toEqual([]);+ });++ it("throws an action it can't sync, for the person who asked", async () => {+ const fake = setup();+ fake+ .rows('content_drafts')+ .push(draft('d1', { status: 'published', published_url: 'https://shop.example/a' }));+ const db = {+ from: (table) => {+ if (table === 'actions') throw new Error('actions unavailable');+ return fake.db.from(table);+ },+ };+ await expect(+ checkShoppingDraft(BRAND, 'd1', { db, now: NOW, readPage: live(link('p2')) }),+ ).rejects.toThrow('actions unavailable');+ // The check itself is kept.+ expect(fake.rows('content_shopping_checks')).toHaveLength(1);+ });+ });});describe('queueShoppingCheck', () => {diff --git a/web/messages/en.json b/web/messages/en.jsonindex 4ff94a268..876621b05 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1366,7 +1366,8 @@"not_open": "This task is already done or skipped.","no_answer": "Couldn't read the page. Try again later.","changed": "The task changed while it was checked. Try again.",- "closed": "This action is closed."+ "closed": "This action is closed.",+ "no_shopping_path": "This page's draft has no shopping path left to check: it was archived, or its path was removed."},"checkFailed": "Couldn't check the task. Try again.","type": "Type",@@ -1458,6 +1459,7 @@"noSignalsTopicOpportunity": "This action was sent from Insights' Opportunities, so it has no detection signals. Its evidence is the topic and suggested prompts on the Overview tab.","noSignalsMentionReview": "This action was sent from Mentions, so it has no detection signals. Its evidence is the answers quoted on the Overview tab.","noSignalsTrafficPages": "This action was sent from AI Traffic Analytics, so it has no detection signals. Its evidence is the pages and figures on the Overview tab.",+ "noSignalsShoppingLinks": "This action comes from the catalog check after each sync, so it has no detection signals. Its evidence is the page and the products on the Overview tab.","topicOpportunity": {"source": "Source","sourceValue": "Insights › Opportunities",@@ -1479,6 +1481,20 @@"prompts": "Prompts it should answer","promptsValue": "{count, plural, one {# prompt} other {# prompts}}"},+ "shoppingLinks": {+ "source": "Source",+ "sourceValue": "The catalog check after each sync",+ "openDraft": "Swap in the editor",+ "page": "Page",+ "products": "Products it links that no longer sell",+ "states": {+ "sold_out": "Sold out",+ "refused": "Refused by Merchant Center",+ "gone": "Gone from your catalog"+ },+ "swaps": "In stock, from its shopping path",+ "check": "Checked again after each catalog sync, or now with Check now on its task: the action closes once the page links none of them."+ },"mentionReview": {"source": "Source","sourceValue": "Mentions & Sentiment › Mentions",@@ -2233,6 +2249,14 @@"optimizeTitle": "Optimize: {title}","description": "Sent from the Content Editor: a draft for someone on the team to write, with its page type and the prompts it should answer.","goal": "Publish the page and get the brand into AI answers for these prompts."+ },+ "shopping_links": {+ "title": "Swap the products that no longer sell on {targets}",+ "titleGeneric": "Swap the products that no longer sell",+ "soldOutTitle": "{page}: {count, plural, one {# product is sold out} other {# products are sold out}}",+ "namedTitle": "{page}: {count, plural, one {# product no longer sells} other {# products no longer sell}}",+ "description": "From the catalog: the page links {count, plural, one {a product} other {# products}} you can't buy now. Readers and AI answers that follow those links land on a dead end.",+ "goal": "Link only products that sell, so readers can buy what the page recommends."}},"actionTasks": {@@ -2474,7 +2498,8 @@"not_changed": "the page hasn't changed since the first look","change_not_found": "the new text isn't on the page","old_text_still_there": "the text it replaces is still on the page",- "off_site": "the page isn't on the brand's site"+ "off_site": "the page isn't on the brand's site",+ "links_not_for_sale": "the page still links products that no longer sell"},"taskChecks": {"auto": "Automatic: we fetch the page again",diff --git a/web/src/components/action-center/action-drawer.tsx b/web/src/components/action-center/action-drawer.tsxindex ef7ac7992..375656c33 100644--- a/web/src/components/action-center/action-drawer.tsx+++ b/web/src/components/action-center/action-drawer.tsx@@ -74,6 +74,7 @@ import { TopicOpportunityContext } from './topic-opportunity-context';import { MentionReviewContext } from './mention-review-context';import { TrafficPagesContext } from './traffic-pages-context';import { ContentDraftContext } from './content-draft-context';+import { ShoppingLinksContext } from './shopping-links-context';import {TaskDetailForm,TaskDetailView,@@ -673,6 +674,11 @@ export function ActionDrawer({<Separator /><ContentDraftContext payload={action.payload ?? {}} /></>+ ) : action.kind === 'shopping_links' ? (+ <>+ <Separator />+ <ShoppingLinksContext payload={action.payload ?? {}} />+ </>) : opportunityId ? (<><Separator />@@ -777,9 +783,11 @@ export function ActionDrawer({? t('drawer.noSignalsMentionReview'): action.kind === 'traffic_pages'? t('drawer.noSignalsTrafficPages')- : opportunityId- ? t('drawer.noSignalsOpportunity')- : t('drawer.noSignals')}+ : action.kind === 'shopping_links'+ ? t('drawer.noSignalsShoppingLinks')+ : opportunityId+ ? t('drawer.noSignalsOpportunity')+ : t('drawer.noSignals')}</p>)}{detail.signals.map((signal) => {diff --git a/web/src/components/action-center/shopping-links-context.test.tsx b/web/src/components/action-center/shopping-links-context.test.tsxnew file mode 100644index 000000000..d5938476a--- /dev/null+++ b/web/src/components/action-center/shopping-links-context.test.tsx@@ -0,0 +1,76 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import { ShoppingLinksContext } from './shopping-links-context';++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...props }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++async function render(payload: Record<string, unknown>) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <ShoppingLinksContext payload={payload} />+ </NextIntlClientProvider>,+ );+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('ShoppingLinksContext', () => {+ it('opens the draft to swap them in, and names the page, what no longer sells and what to link instead', async () => {+ await render({+ draftId: 'd9',+ pageUrl: 'https://shop.example/blog/rain-jackets',+ products: [+ { id: 'p1', title: 'Storm Shell 2', state: 'sold_out' },+ { id: 'p2', title: 'Pack-Lite Jacket', state: 'refused' },+ ],+ swaps: [+ { id: 'p3', title: 'Storm Shell 3' },+ { id: 'p4', title: 'Pack-Lite Pro' },+ ],+ });+ const link = container.querySelector('a')!;+ expect(link.getAttribute('href')).toBe('/dashboard/content/editor/d9');+ expect(link.textContent).toContain('Swap in the editor');+ expect(container.textContent).toContain('/blog/rain-jackets');+ expect(container.textContent).toContain('Storm Shell 2Sold out');+ expect(container.textContent).toContain('Pack-Lite JacketRefused by Merchant Center');+ expect(container.textContent).toContain('Storm Shell 3 · Pack-Lite Pro');+ expect(container.textContent).toContain('or now with Check now on its task');+ });++ it('reads a payload of the wrong shape without breaking', async () => {+ await render({ products: 'none', swaps: [null, { title: 5 }] });+ expect(container.querySelector('a')).toBeNull();+ expect(container.textContent).not.toContain('Products it links');+ expect(container.textContent).not.toContain('In stock');+ });+});diff --git a/web/src/components/action-center/shopping-links-context.tsx b/web/src/components/action-center/shopping-links-context.tsxnew file mode 100644index 000000000..00954e55e--- /dev/null+++ b/web/src/components/action-center/shopping-links-context.tsx@@ -0,0 +1,89 @@+'use client';++import { useTranslations } from 'next-intl';+import { ExternalLink } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { contentEditorPath } from '@/lib/content/drafts';+import { pagePath } from '@/lib/content/overlap';++const STATES = ['sold_out', 'refused', 'gone'] as const;+type LinkState = (typeof STATES)[number];++/** The payload's products, read defensively: any may be missing or of the wrong shape. */+function productsOf(raw: unknown): { title: string; state: LinkState | null }[] {+ if (!Array.isArray(raw)) return [];+ return raw+ .map((item) => {+ const p = (item ?? {}) as Record<string, unknown>;+ const state = (STATES as readonly unknown[]).includes(p.state)+ ? (p.state as LinkState)+ : null;+ return { title: typeof p.title === 'string' ? p.title.trim() : '', state };+ })+ .filter((p) => p.title || p.state);+}++/**+ * What the catalog check's action carries (shopping path, part 7): the live+ * page and its draft to swap them in, the products it links that no longer+ * sell and why, and the ones of its shopping path in stock to link instead.+ */+export function ShoppingLinksContext({ payload }: { payload: Record<string, unknown> }) {+ const t = useTranslations('actionCenter.actionsPage.drawer.shoppingLinks');+ const draftId = typeof payload.draftId === 'string' ? payload.draftId : null;+ const page = typeof payload.pageUrl === 'string' ? payload.pageUrl : null;+ const products = productsOf(payload.products);+ const swaps = productsOf(payload.swaps).filter((p) => p.title);++ return (+ <section className="space-y-3">+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('source')}</p>+ <div className="mt-1 flex flex-wrap items-center gap-2">+ <span>{t('sourceValue')}</span>+ {draftId && (+ <Link+ href={contentEditorPath(draftId)}+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('openDraft')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ )}+ </div>+ </div>+ {page && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('page')}</p>+ <p className="mt-1 truncate" title={page}>+ {pagePath(page)}+ </p>+ </div>+ )}+ {products.length > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('products')}</p>+ <ul className="mt-1 space-y-1">+ {products.map((product, i) => (+ <li key={`${product.title}:${i}`} className="flex flex-wrap items-baseline gap-x-2">+ <span className="min-w-0 break-words">{product.title || '—'}</span>+ {product.state && (+ <span className="text-xs text-red-700 dark:text-red-400">+ {t(`states.${product.state}`)}+ </span>+ )}+ </li>+ ))}+ </ul>+ </div>+ )}+ {swaps.length > 0 && (+ <div>+ <p className="text-xs font-medium text-muted-foreground">{t('swaps')}</p>+ <p className="mt-1 break-words">{swaps.map((p) => p.title).join(' · ')}</p>+ </div>+ )}+ <p className="text-xs text-muted-foreground">{t('check')}</p>+ </section>+ );+}diff --git a/web/src/lib/action-center/display.test.ts b/web/src/lib/action-center/display.test.tsindex d331b4c17..94e1dc2aa 100644--- a/web/src/lib/action-center/display.test.ts+++ b/web/src/lib/action-center/display.test.ts@@ -54,8 +54,8 @@ describe('actionTexts', () => {expect(() => actionGoal(kind, t)).not.toThrow();});- it('holds copy for all sixty-two definitions and the seven person-sent kinds', () => {- expect(ACTION_KINDS).toHaveLength(69);+ it("holds copy for all sixty-two definitions, the seven person-sent kinds and the catalog check's", () => {+ expect(ACTION_KINDS).toHaveLength(70);});it('names pages sent from AI Traffic after their list and page, or how many (AT-006)', () => {@@ -210,6 +210,37 @@ describe('actionTexts', () => {).not.toBe('');});+ it('names a live page linking products that no longer sell after it (shopping path, part 7)', () => {+ const products = [+ { id: 'p1', title: 'Storm Shell 2', state: 'sold_out' },+ { id: 'p2', title: 'Pack-Lite Jacket', state: 'sold_out' },+ ];+ const soldOut = actionTexts(+ action({+ kind: 'shopping_links',+ payload: { title: 'Best rain jackets for 2026', products, soldOut: true },+ }),+ t,+ );+ expect(soldOut.title).toBe('Best rain jackets for 2026: 2 products are sold out');+ expect(soldOut.description).toContain('2 products');+ // Not all sold out, and no title: the page's path, and "no longer sells".+ expect(+ actionTexts(+ action({+ kind: 'shopping_links',+ payload: {+ pageUrl: 'https://shop.example/blog/rain-jackets/',+ products,+ soldOut: false,+ },+ }),+ t,+ ).title,+ ).toBe('/blog/rain-jackets: 2 products no longer sell');+ expect(actionContextTags(action({ kind: 'shopping_links', payload: {} }), t)).toEqual([]);+ });+/*** The specification's title rule: "Recover 7 lost citations", never* "Recover citations". Every definition's title names its targets.diff --git a/web/src/lib/action-center/display.ts b/web/src/lib/action-center/display.tsindex 6ae25bd4f..df5d54534 100644--- a/web/src/lib/action-center/display.ts+++ b/web/src/lib/action-center/display.ts@@ -1,5 +1,6 @@import type { ActionEvent, ActionItem } from '@/lib/actions/action-center';import { isActionKind } from '@/lib/action-center/registry';+import { pagePath } from '@/lib/content/overlap';import { formatEstimateRange, guessedVolumeEstimate } from '@/lib/volume-estimate';/**@@ -83,6 +84,21 @@ export function actionTexts(description: t('content_draft.description'),};}+ // A live page linking products that no longer sell (shopping path, part 7)+ // is named after the page and how many.+ if (action.kind === 'shopping_links' && Array.isArray(p.products) && p.products.length) {+ const count = p.products.length;+ const page = str(p, 'title') || pagePath(str(p, 'pageUrl'));+ return {+ title: page+ ? t(p.soldOut === true ? 'shopping_links.soldOutTitle' : 'shopping_links.namedTitle', {+ page,+ count,+ })+ : t('shopping_links.titleGeneric'),+ description: t('shopping_links.description', { count }),+ };+ }// An Improve action carries its own title and "why", written from the// prompt's platform states when it was sent (PROMPT-004).if (action.kind === 'prompt_improve' && typeof p.title === 'string' && p.title) {@@ -241,7 +257,10 @@ export function actionGoal(return isActionKind(kind) ? t(`${kind}.goal`) : t('unknown.goal');}-/** Kinds a person sends rather than a definition raises. */+/**+ * Kinds a person sends rather than a definition raises, and the catalog+ * check's (shopping_links): none rests on detection signals.+ */const PERSON_SENT_KINDS: string[] = ['content_opportunity','prompt_improve',@@ -250,6 +269,7 @@ const PERSON_SENT_KINDS: string[] = ['mention_review','traffic_pages','content_draft',+ 'shopping_links',];/** Compact evidence chips under the title: signal count plus the kind's owndiff --git a/web/src/lib/action-center/registry.ts b/web/src/lib/action-center/registry.tsindex c5cfd84cb..b33d489e2 100644--- a/web/src/lib/action-center/registry.ts+++ b/web/src/lib/action-center/registry.ts@@ -114,7 +114,10 @@ export type ActionKind =// Sent by a person from AI Traffic's Pages section (AT-006).| 'traffic_pages'// Sent by a person from the Content Editor's Start, as Team (CE-015).- | 'content_draft';+ | 'content_draft'+ // Raised by the catalog check for a live page linking products that no+ // longer sell (shopping path, part 7), and closed by it once fixed.+ | 'shopping_links';export type TaskStatus =| 'todo'@@ -251,6 +254,7 @@ export const ACTION_KINDS: readonly ActionKind[] = ['mention_review','traffic_pages','content_draft',+ 'shopping_links',];/**diff --git a/web/src/lib/actions/action-task-check.test.ts b/web/src/lib/actions/action-task-check.test.tsindex 1fa59b4a5..ceb9eee02 100644--- a/web/src/lib/actions/action-task-check.test.ts+++ b/web/src/lib/actions/action-task-check.test.ts@@ -36,6 +36,9 @@ describe('checkActionTask', () => {it('says why nothing was checked, and returns the server’s error rather than throwing', async () => {vi.stubGlobal('fetch', respond(200, { checked: null, reason: 'not_checkable' }));expect(await checkActionTask('t1')).toEqual({ checked: null, reason: 'not_checkable' });+ // A shopping links task whose draft has no path left (shopping path, part 7).+ vi.stubGlobal('fetch', respond(200, { checked: null, reason: 'no_shopping_path' }));+ expect(await checkActionTask('t1')).toEqual({ checked: null, reason: 'no_shopping_path' });vi.stubGlobal('fetch', respond(200, { checked: null, reason: 'something new' }));expect(await checkActionTask('t1')).toEqual({ checked: null, reason: 'no_answer' });vi.stubGlobal('fetch', respond(404, { error: 'Task not found', code: 'not_found' }));diff --git a/web/src/lib/actions/action-task-check.ts b/web/src/lib/actions/action-task-check.tsindex e99777bee..4bcd8799e 100644--- a/web/src/lib/actions/action-task-check.ts+++ b/web/src/lib/actions/action-task-check.ts@@ -4,8 +4,18 @@ import { createClient } from '@/lib/supabase/server';import { API_BASE_URL } from '@/config/api';import type { TaskLastCheck } from '@/lib/action-center/task-details';-/** Why nothing was checked: no check here, done, the page didn't answer, changed meanwhile, a closed action. */-export type CheckSkippedReason = 'not_checkable' | 'not_open' | 'no_answer' | 'changed' | 'closed';+/**+ * Why nothing was checked: no check here, done, the page didn't answer,+ * changed meanwhile, a closed action, or a shopping links task whose draft+ * has no shopping path left.+ */+export type CheckSkippedReason =+ | 'not_checkable'+ | 'not_open'+ | 'no_answer'+ | 'changed'+ | 'closed'+ | 'no_shopping_path';/*** What checking a task now came to (AC-010): the check kept on it, or why@@ -59,6 +69,7 @@ export async function checkActionTask(taskId: string): Promise<CheckTaskResult>'no_answer','changed','closed',+ 'no_shopping_path',];return {checked: null,