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(cms): mark a page published once its WordPress post is put live, read when the Library opens and daily (#1331) (#1570)
Cihan6b8a7e8b3828
diff --git a/server/src/lib/cms/wordpress-delivery.js b/server/src/lib/cms/wordpress-delivery.jsindex 3ac2bea5f..cd544330f 100644--- a/server/src/lib/cms/wordpress-delivery.js+++ b/server/src/lib/cms/wordpress-delivery.js@@ -1,6 +1,7 @@import * as cheerio from 'cheerio';import supabaseAdmin from '../../config/supabase.js';import { logger } from '../logger.js';+import { markDeliveryPublished } from '../content-published.js';import { readCmsCredentials } from './credentials.js';import { WordPressError, createPost, readPost, updatePost } from './wordpress.js';@@ -32,7 +33,7 @@ const DRAFT_STATUSES = new Set(['draft', 'pending', 'auto-draft']);async function lastPost(draftId, site, deliveryId) {const { data, error } = await supabaseAdmin.from('content_draft_deliveries')- .select('external_id')+ .select('id, draft_id, status, published_url, external_id').eq('draft_id', draftId).eq('target', 'wordpress').eq('target_collection', site)@@ -42,7 +43,25 @@ async function lastPost(draftId, site, deliveryId) {.limit(1).maybeSingle();if (error) throw new Error(error.message);- return data?.external_id ?? null;+ return data?.external_id ? data : null;+}++/**+ * The last send's post, found live by this send before the published check+ * saw it: that send is marked published at the post's link, so the publish+ * isn't lost behind the new draft (the page itself follows its latest send,+ * this new draft, once that is published). Best effort.+ */+async function keepPublished(last, post) {+ if (post.status !== 'publish' || !/^https?:\/\//i.test(post.link ?? '')) return;+ try {+ await markDeliveryPublished(last, post.link);+ } catch (err) {+ logger.warn(+ { err: { name: err?.name }, deliveryId: last.id },+ '[content-delivery] publish not kept',+ );+ }}/**@@ -102,11 +121,13 @@ export async function sendToWordPress({ delivery, page, html, connection, requesrefused: true,};}- const before = await lastPost(page.draftId, site, delivery.id);+ const last = await lastPost(page.draftId, site, delivery.id);+ const before = last?.external_id ?? null;const current = before ? await readPost(site, credentials, before, { request }) : null;const live = Boolean(current && current.status !== 'trash' && !DRAFT_STATUSES.has(current.status),);+ if (live) await keepPublished(last, current);let written = null;if (current && !live && current.status !== 'trash') {try {diff --git a/server/src/lib/cms/wordpress-delivery.test.js b/server/src/lib/cms/wordpress-delivery.test.jsindex 12d9d607a..a3ded7d1a 100644--- a/server/src/lib/cms/wordpress-delivery.test.js+++ b/server/src/lib/cms/wordpress-delivery.test.js@@ -37,6 +37,10 @@ vi.mock('../logger.js', () => ({}));let credentials;vi.mock('./credentials.js', () => ({ readCmsCredentials: async () => credentials }));+const markDeliveryPublished = vi.fn();+vi.mock('../content-published.js', () => ({+ markDeliveryPublished: (...args) => markDeliveryPublished(...args),+}));const wordpress = { createPost: vi.fn(), readPost: vi.fn(), updatePost: vi.fn() };vi.mock('./wordpress.js', async (importOriginal) => ({...(await importOriginal()),@@ -86,6 +90,7 @@ beforeEach(() => {queries.length = 0;updates.length = 0;logged.length = 0;+ markDeliveryPublished.mockReset().mockResolvedValue(undefined);wordpress.createPost.mockReset().mockResolvedValue({ id: 41, status: 'draft', link: null });wordpress.readPost.mockReset().mockResolvedValue({ id: 7, status: 'draft', link: null });wordpress.updatePost.mockReset().mockResolvedValue({ id: 7, status: 'draft', link: null });@@ -165,6 +170,26 @@ describe('sendToWordPress', () => {expect(wordpress.createPost).toHaveBeenCalledTimes(3);});+ it('keeps the publish its last send’s post had, found live before the check saw it', async () => {+ previous = '7';+ wordpress.readPost.mockResolvedValueOnce({+ id: 7,+ status: 'publish',+ link: `${SITE}/cold-brew/`,+ });+ await send();+ expect(markDeliveryPublished).toHaveBeenCalledWith(+ expect.objectContaining({ external_id: '7' }),+ `${SITE}/cold-brew/`,+ );+ // Scheduled isn't live yet.+ previous = '7';+ markDeliveryPublished.mockClear();+ wordpress.readPost.mockResolvedValueOnce({ id: 7, status: 'future', link: `${SITE}/?p=7` });+ await send();+ expect(markDeliveryPublished).not.toHaveBeenCalled();+ });+it('makes a new post when the last one is gone or in the trash', async () => {previous = '7';wordpress.readPost.mockResolvedValueOnce(null);diff --git a/server/src/lib/cms/wordpress-status.js b/server/src/lib/cms/wordpress-status.jsnew file mode 100644index 000000000..35b1c413c--- /dev/null+++ b/server/src/lib/cms/wordpress-status.js@@ -0,0 +1,190 @@+import supabaseAdmin from '../../config/supabase.js';+import { isSubscriptionActive } from '../../config/plans.js';+import { logger } from '../logger.js';+import { credentialsConfigured } from '../catalog/credentials.js';+import { markDeliveryPublished } from '../content-published.js';+import { readCmsCredentials } from './credentials.js';+import { WordPressError, answersAsWordPress, readPostState } from './wordpress.js';++/**+ * Pages sent to WordPress, published there since (Send to CMS #1331, phase+ * 2; 00294): nothing calls back when a post goes live, so Ansvisor reads the+ * posts its sends made. A send writes only to a draft (a live post gets a+ * new draft, cms/wordpress-delivery.js), so a post published now was put+ * live after the send: it is marked published at the post's own link (read+ * as the public sees it when this user can't read it to edit). A post in+ * the trash, or gone while the site answers as WordPress, closes its send;+ * a site answering 404 for every post (moved, its permalinks changed)+ * closes nothing. Read when the Library opens (a brand's newest sends, throttled by+ * its route) and once a day for all, as Webflow's are (webflow-status.js).+ */++/** Posts the Library's check reads: the newest sends. The daily sweep reads the rest. */+export const POSTS_ON_DEMAND = 10;+/** Posts the daily sweep reads a brand. */+export const POSTS_DAILY = 100;+/** Sends older than this aren't read again: a draft left that long stays one. */+const LOOK_BACK_MS = 60 * 24 * 60 * 60 * 1000;+/** Post reads that fail in a row before a check stops: the site is down. */+const FAILURES_IN_A_ROW = 3;+/** Connections the daily sweep reads, shuffled so a deadline doesn't leave the same brands out. */+const SWEEP_CONNECTIONS = 1000;+const SWEEP_DEADLINE_MS = 10 * 60 * 1000;++const none = { checked: 0, published: [] };++/** The sign-in was refused while reading: Settings asks for a new one (as the send read it). */+async function markRefused(connection) {+ const { error } = await supabaseAdmin+ .from('brand_cms_connections')+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })+ .eq('id', connection.id)+ .eq('provider', 'wordpress')+ .eq('updated_at', connection.updated_at);+ if (error) logger.warn({ err: error }, '[wordpress-status] refusal not kept');+}++/** A send whose post is gone from WordPress: closed. The page's next send makes a new post. */+async function closeRemoved(send) {+ const { error } = await supabaseAdmin+ .from('content_draft_deliveries')+ .update({ status: 'failed', error: 'Removed in WordPress' })+ .eq('id', send.id)+ .eq('status', 'sent');+ if (error) {+ logger.warn({ err: error, deliveryId: send.id }, '[wordpress-status] removal not kept');+ }+}++const logged = (err) => ({ name: err?.name, code: err?.code });++/** A post's own link, when it's a web address. */+const linkOf = (post) => (/^https?:\/\//i.test(post?.link ?? '') ? post.link : null);++/**+ * Reads the brand's pages sent to WordPress and not yet seen live (each+ * page's latest such send to the connected site, newest first, up to+ * `limit`), and marks the published ones published. One post's failure+ * doesn't stop the others (three in a row do); a sign-in refused stops the+ * check and marks the connection.+ *+ * @returns {Promise<{ checked: number, published: { draftId: string|null, url: string }[] }>}+ */+export async function checkWordPressPublished(brandId, { limit = POSTS_ON_DEMAND, request } = {}) {+ if (!credentialsConfigured()) return none;+ const { data: connection, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .select('id, brand_id, status, site_url, updated_at')+ .eq('brand_id', brandId)+ .eq('provider', 'wordpress')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!connection || connection.status !== 'connected' || !connection.site_url) return none;++ // The connected site's sends only: a post on a site connected before isn't read with this sign-in.+ const { data: rows, error: rowsError } = await supabaseAdmin+ .from('content_draft_deliveries')+ .select('id, draft_id, status, published_url, external_id, target_collection, sent_at')+ .eq('brand_id', brandId)+ .eq('target', 'wordpress')+ .eq('target_collection', connection.site_url)+ .eq('status', 'sent')+ .not('external_id', 'is', null)+ .gte('sent_at', new Date(Date.now() - LOOK_BACK_MS).toISOString())+ .order('sent_at', { ascending: false })+ .limit(limit * 4);+ if (rowsError) throw new Error(rowsError.message);+ // A page's latest send: an earlier one made the same post, updated since, or one replaced.+ const seen = new Set();+ const sends = [];+ for (const row of rows ?? []) {+ const key = row.draft_id ?? row.id;+ if (seen.has(key)) continue;+ seen.add(key);+ sends.push(row);+ if (sends.length === limit) break;+ }+ if (!sends.length) return none;++ const credentials = await readCmsCredentials(connection.id);+ if (!credentials?.username || !credentials?.password) {+ await markRefused(connection);+ return none;+ }+ const published = [];+ let checked = 0;+ let failures = 0;+ // The site answered as WordPress this check: a post read, or its index.+ let alive = false;+ for (const send of sends) {+ let post;+ try {+ post = await readPostState(connection.site_url, credentials, send.external_id, { request });+ } catch (err) {+ if (err instanceof WordPressError && err.code === 'auth_failed') {+ await markRefused(connection);+ return { checked, published };+ }+ logger.warn({ err: logged(err), deliveryId: send.id }, '[wordpress-status] post not read');+ if (++failures === FAILURES_IN_A_ROW) break;+ continue;+ }+ if (!post && !alive) {+ alive = await answersAsWordPress(connection.site_url, credentials, { request });+ if (!alive) {+ logger.warn({ deliveryId: send.id }, '[wordpress-status] site not answering as WordPress');+ if (++failures === FAILURES_IN_A_ROW) break;+ continue;+ }+ }+ alive = true;+ failures = 0;+ checked++;+ if (!post || post.status === 'trash') {+ await closeRemoved(send);+ continue;+ }+ const url = post.status === 'publish' ? linkOf(post) : null;+ if (!url) continue;+ await markDeliveryPublished(send, url);+ published.push({ draftId: send.draft_id, url });+ }+ return { checked, published };+}++/**+ * The daily check, for brands with WordPress connected (on an active+ * subscription), in a shuffled order so the deadline leaves out different+ * brands each day; one brand's failure is logged and the next goes on.+ */+export async function sweepWordPressPublished() {+ if (!credentialsConfigured()) return { brands: 0, published: 0 };+ const started = Date.now();+ const { data, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .select('brand_id, brands!inner(organizations!inner(subscription_status))')+ .eq('provider', 'wordpress')+ .eq('status', 'connected')+ .limit(SWEEP_CONNECTIONS);+ if (error) throw new Error(`brand_cms_connections read: ${error.message}`);+ const due = (data ?? []).filter((row) =>+ isSubscriptionActive(row.brands?.organizations?.subscription_status),+ );+ for (let i = due.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1));+ [due[i], due[j]] = [due[j], due[i]];+ }+ let brands = 0;+ let published = 0;+ for (const row of due) {+ if (Date.now() - started > SWEEP_DEADLINE_MS) break;+ try {+ const result = await checkWordPressPublished(row.brand_id, { limit: POSTS_DAILY });+ brands++;+ published += result.published.length;+ } catch (err) {+ logger.error({ err: logged(err), brandId: row.brand_id }, '[wordpress-status] check failed');+ }+ }+ return { brands, published };+}diff --git a/server/src/lib/cms/wordpress-status.test.js b/server/src/lib/cms/wordpress-status.test.jsnew file mode 100644index 000000000..84fbc59ef--- /dev/null+++ b/server/src/lib/cms/wordpress-status.test.js@@ -0,0 +1,235 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Pages sent to WordPress, published there since (Send to CMS #1331, phase+ * 2; 00294): read from the posts the sends made, marked published at the+ * post's link.+ */++const db = { connection: null, sends: [], brands: [], queries: [], updates: [] };+vi.mock('../../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const q = { table, filters: [] };+ const result = () => {+ if (q.update) {+ db.updates.push({ table, update: q.update, filters: q.filters });+ return { data: null, error: null };+ }+ if (table === 'brand_cms_connections') {+ return { data: q.single ? db.connection : db.brands, error: null };+ }+ db.queries.push(q);+ return { data: db.sends, error: null };+ };+ const chain = {+ select: () => chain,+ eq: (col, value) => (q.filters.push(['eq', col, value]), chain),+ not: (col, op, value) => (q.filters.push(['not', col, op, value]), chain),+ gte: (col, value) => (q.filters.push(['gte', col, value]), chain),+ order: () => chain,+ limit: () => chain,+ update: (row) => ((q.update = row), chain),+ maybeSingle: async () => ((q.single = true), result()),+ then: (resolve) => resolve(result()),+ };+ return chain;+ },+ },+}));+const configured = vi.hoisted(() => ({ on: true }));+vi.mock('../catalog/credentials.js', () => ({ credentialsConfigured: () => configured.on }));+let credentials;+vi.mock('./credentials.js', () => ({ readCmsCredentials: async () => credentials }));+const markDeliveryPublished = vi.fn();+vi.mock('../content-published.js', () => ({+ markDeliveryPublished: (...args) => markDeliveryPublished(...args),+}));+const readPost = vi.fn();+const answersAsWordPress = vi.fn();+vi.mock('./wordpress.js', async (importOriginal) => ({+ ...(await importOriginal()),+ readPostState: (...args) => readPost(...args),+ answersAsWordPress: (...args) => answersAsWordPress(...args),+}));+const logged = [];+vi.mock('../logger.js', () => ({+ logger: { warn: () => {}, error: (...args) => logged.push(JSON.stringify(args)) },+}));++const { checkWordPressPublished, sweepWordPressPublished } = await import('./wordpress-status.js');+const { WordPressError } = await import('./wordpress.js');++const SITE = 'https://blog.acme.example';+const signIn = { username: 'editor', password: 'abcd efgh ijkl mnop qrst uvwx' };+const send = (id, draftId, over = {}) => ({+ id,+ draft_id: draftId,+ status: 'sent',+ published_url: null,+ external_id: `${id}`,+ target_collection: SITE,+ sent_at: '2026-10-24T10:00:00Z',+ ...over,+});+const post = (id, status, link = `${SITE}/?p=${id}`) => ({ id, status, link });++beforeEach(() => {+ configured.on = true;+ credentials = signIn;+ db.connection = {+ id: 'cn1',+ brand_id: 'b1',+ status: 'connected',+ site_url: SITE,+ updated_at: '2026-10-27T09:00:00Z',+ };+ db.sends = [];+ db.brands = [];+ db.queries = [];+ db.updates = [];+ logged.length = 0;+ markDeliveryPublished.mockReset().mockResolvedValue(undefined);+ readPost.mockReset();+ answersAsWordPress.mockReset().mockResolvedValue(true);+});++describe('checkWordPressPublished', () => {+ it('marks a post put live published at its own link, and leaves a draft as it is', async () => {+ db.sends = [send('41', 'dr1'), send('42', 'dr2')];+ readPost+ .mockResolvedValueOnce(post(41, 'publish', `${SITE}/cold-brew/`))+ .mockResolvedValueOnce(post(42, 'draft'));+ expect(await checkWordPressPublished('b1')).toEqual({+ checked: 2,+ published: [{ draftId: 'dr1', url: `${SITE}/cold-brew/` }],+ });+ expect(markDeliveryPublished).toHaveBeenCalledWith(db.sends[0], `${SITE}/cold-brew/`);+ expect(readPost).toHaveBeenCalledWith(SITE, signIn, '41', { request: undefined });+ // The connected site's sends only.+ expect(db.queries[0].filters).toEqual(+ expect.arrayContaining([+ ['eq', 'target', 'wordpress'],+ ['eq', 'target_collection', SITE],+ ['eq', 'status', 'sent'],+ ]),+ );+ });++ it('waits on a post scheduled or pending, and closes one gone or in the trash', async () => {+ db.sends = [send('41', 'dr1'), send('42', 'dr2'), send('43', 'dr3'), send('44', 'dr4')];+ readPost+ .mockResolvedValueOnce(post(41, 'future'))+ .mockResolvedValueOnce(post(42, 'pending'))+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(post(44, 'trash'));+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 4, published: [] });+ expect(db.updates.map((u) => [u.update.error, u.filters[0][2]])).toEqual([+ ['Removed in WordPress', '43'],+ ['Removed in WordPress', '44'],+ ]);+ });++ it('closes a post gone only once the site answers as WordPress', async () => {+ db.sends = [send('41', 'dr1'), send('42', 'dr2')];+ readPost.mockResolvedValueOnce(null).mockResolvedValueOnce(null);+ await checkWordPressPublished('b1');+ expect(answersAsWordPress).toHaveBeenCalledTimes(1);+ expect(db.updates.map((u) => u.filters[0][2])).toEqual(['41', '42']);+ });++ it('closes nothing while the site answers 404 for every post (moved, its permalinks changed)', async () => {+ db.sends = ['1', '2', '3', '4'].map((id) => send(id, `dr${id}`));+ readPost.mockResolvedValue(null);+ answersAsWordPress.mockResolvedValue(false);+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ expect(db.updates).toEqual([]);+ // Three in a row stop it, as failed reads do.+ expect(readPost).toHaveBeenCalledTimes(3);+ });++ it('marks no published post whose link isn’t a web address', async () => {+ db.sends = [send('41', 'dr1')];+ readPost.mockResolvedValueOnce(post(41, 'publish', '/?p=41'));+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 1, published: [] });+ expect(markDeliveryPublished).not.toHaveBeenCalled();+ });++ it('reads each page’s latest send only', async () => {+ db.sends = [send('42', 'dr1'), send('41', 'dr1', { sent_at: '2026-10-20T10:00:00Z' })];+ readPost.mockResolvedValue(post(42, 'draft'));+ await checkWordPressPublished('b1');+ expect(readPost).toHaveBeenCalledTimes(1);+ expect(readPost.mock.calls[0][2]).toBe('42');+ });++ it('marks the connection refused, as it was read, and stops', async () => {+ db.sends = [send('41', 'dr1'), send('42', 'dr2')];+ readPost.mockRejectedValueOnce(new WordPressError('auth_failed', 'refused'));+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ expect(readPost).toHaveBeenCalledTimes(1);+ expect(db.updates).toEqual([+ {+ table: 'brand_cms_connections',+ update: expect.objectContaining({ status: 'auth_failed' }),+ filters: [+ ['eq', 'id', 'cn1'],+ ['eq', 'provider', 'wordpress'],+ ['eq', 'updated_at', '2026-10-27T09:00:00Z'],+ ],+ },+ ]);+ });++ it('stops after three failed reads in a row, the site down', async () => {+ db.sends = ['1', '2', '3', '4'].map((id) => send(id, `dr${id}`));+ readPost.mockRejectedValue(new WordPressError('unreachable', 'down'));+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ expect(readPost).toHaveBeenCalledTimes(3);+ });++ it('reads nothing without a connection, a connected one, sends or the server’s key', async () => {+ configured.on = false;+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ configured.on = true;+ db.connection = { ...db.connection, status: 'auth_failed' };+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ db.connection = null;+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ expect(readPost).not.toHaveBeenCalled();+ });++ it('asks to connect again when the kept sign-in can’t be read', async () => {+ db.sends = [send('41', 'dr1')];+ credentials = null;+ expect(await checkWordPressPublished('b1')).toEqual({ checked: 0, published: [] });+ expect(readPost).not.toHaveBeenCalled();+ expect(db.updates[0].update.status).toBe('auth_failed');+ });+});++describe('sweepWordPressPublished', () => {+ it('reads the brands of active subscriptions, going on past one that fails', async () => {+ db.brands = [+ { brand_id: 'b1', brands: { organizations: { subscription_status: 'active' } } },+ { brand_id: 'b2', brands: { organizations: { subscription_status: 'canceled' } } },+ { brand_id: 'b3', brands: { organizations: { subscription_status: 'trialing' } } },+ ];+ db.sends = [send('41', 'dr1')];+ readPost.mockResolvedValue(post(41, 'publish'));+ markDeliveryPublished.mockRejectedValueOnce(new Error('down'));+ // On the cloud, where subscriptions count.+ vi.stubEnv('IS_CLOUD', 'true');+ expect(await sweepWordPressPublished()).toEqual({ brands: 1, published: 1 });+ vi.unstubAllEnvs();+ // The brand that failed (the order is shuffled daily) is logged; the other went on.+ expect(logged).toHaveLength(1);+ expect(logged[0]).toMatch(/"brandId":"b[13]"/);+ expect(readPost).toHaveBeenCalledTimes(2);+ });++ it('does nothing on a server that can’t keep a sign-in', async () => {+ configured.on = false;+ expect(await sweepWordPressPublished()).toEqual({ brands: 0, published: 0 });+ });+});diff --git a/server/src/lib/cms/wordpress.js b/server/src/lib/cms/wordpress.jsindex 841126b33..4f6738ce9 100644--- a/server/src/lib/cms/wordpress.js+++ b/server/src/lib/cms/wordpress.js@@ -294,6 +294,58 @@ export async function readPost(site, credentials, id, { request } = {}) {}}+/**+ * A post's status and link, for the published check (cms/wordpress-status.js):+ * null when it's gone (404, 410). A post this user can't read to edit, as+ * a Contributor's once an Editor published it, is read as the public sees+ * it; one it can't read either throws ('failed'), so its send stays open.+ */+export async function readPostState(site, credentials, id, { request } = {}) {+ const path = postId(id);+ if (!path) return null;+ try {+ return postOf(+ await call(site, `/wp/v2/posts/${path}`, {+ credentials,+ query: { context: 'edit' },+ request,+ }),+ );+ } catch (err) {+ if (err instanceof WordPressError && err.code === 'not_found') return null;+ if (!(err instanceof WordPressError && err.code === 'no_access')) throw err;+ }+ try {+ return postOf(+ await call(site, `/wp/v2/posts/${path}`, {+ credentials,+ query: { context: 'view' },+ request,+ }),+ );+ } catch (err) {+ throw new WordPressError('failed', 'This user can’t read the post.', err?.status);+ }+}++/**+ * Whether the site answers as WordPress now, signed in: before a post's+ * 404 closes its send, as a site moved, or its permalinks set to Plain,+ * answers 404 for every post.+ */+export async function answersAsWordPress(site, credentials, { request } = {}) {+ try {+ const index = await call(site, '/', {+ credentials,+ query: { _fields: 'namespaces' },+ request,+ });+ return Array.isArray(index?.namespaces) && index.namespaces.includes('wp/v2');+ } catch {+ return false;+ }+}+/** Writes a post's title, slug, content and excerpt; its status stays as it is. */export async function updatePost(site, credentials, id, post, { request } = {}) {const path = postId(id);diff --git a/server/src/lib/cms/wordpress.test.js b/server/src/lib/cms/wordpress.test.jsindex 3bc646460..83984534b 100644--- a/server/src/lib/cms/wordpress.test.js+++ b/server/src/lib/cms/wordpress.test.js@@ -4,8 +4,17 @@ import { afterEach, describe, expect, it, vi } from 'vitest';vi.mock('../../config/supabase.js', () => ({ default: {} }));const { startFakeApi } = await import('../../connectors/testing.js');-const { WordPressError, checkSite, createPost, readPost, revokePassword, siteAddress, updatePost } =- await import('./wordpress.js');+const {+ WordPressError,+ answersAsWordPress,+ checkSite,+ createPost,+ readPost,+ readPostState,+ revokePassword,+ siteAddress,+ updatePost,+} = await import('./wordpress.js');/*** WordPress's REST API for Send to CMS (#1331, phase 2): a site checked@@ -288,3 +297,42 @@ describe('revokePassword', () => {expect(await revokePassword(site, signIn, { request })).toBe(false);});});++describe('readPostState and answersAsWordPress (the published check)', () => {+ it('reads a post this user can’t edit as the public sees it: a Contributor’s, published', async () => {+ const { site, request } = await start({+ 'GET /wp-json/wp/v2/posts/7': (call) =>+ call.query.context === 'edit'+ ? { status: 403, json: { code: 'rest_forbidden_context' } }+ : { json: { id: 7, status: 'publish', link: 'https://blog.acme.example/cold-brew/' } },+ });+ expect(await readPostState(site, signIn, '7', { request })).toEqual({+ id: 7,+ status: 'publish',+ link: 'https://blog.acme.example/cold-brew/',+ });+ expect(api.calls.map((c) => c.query.context)).toEqual(['edit', 'view']);+ });++ it('throws, never reading as gone, a post it can’t read either way; null for one gone', async () => {+ const { site, request } = await start({+ 'GET /wp-json/wp/v2/posts/7': () => ({ status: 403, json: { code: 'rest_forbidden' } }),+ 'GET /wp-json/wp/v2/posts/8': () => ({ status: 404, json: { code: 'rest_post_invalid_id' } }),+ });+ await expect(readPostState(site, signIn, '7', { request })).rejects.toMatchObject({+ code: 'failed',+ });+ expect(await readPostState(site, signIn, '8', { request })).toBeNull();+ });++ it('says whether the site answers as WordPress now', async () => {+ let checked = await start({ 'GET /wp-json/': () => ({ json: { namespaces: ['wp/v2'] } }) });+ expect(await answersAsWordPress(checked.site, signIn, { request: checked.request })).toBe(true);+ expect(api.calls[0].query).toEqual({ _fields: 'namespaces' });+ api.close();+ checked = await start({});+ expect(await answersAsWordPress(checked.site, signIn, { request: checked.request })).toBe(+ false,+ );+ });+});diff --git a/server/src/routes/content-drafts-send.test.js b/server/src/routes/content-drafts-send.test.jsindex 91e16fa19..402a49c1d 100644--- a/server/src/routes/content-drafts-send.test.js+++ b/server/src/routes/content-drafts-send.test.js@@ -29,6 +29,10 @@ const checkWebflowPublished = vi.fn();vi.mock('../lib/cms/webflow-status.js', () => ({checkWebflowPublished: (...args) => checkWebflowPublished(...args),}));+const checkWordPressPublished = vi.fn();+vi.mock('../lib/cms/wordpress-status.js', () => ({+ checkWordPressPublished: (...args) => checkWordPressPublished(...args),+}));vi.mock('../lib/content-delivery.js', async (importOriginal) => ({...(await importOriginal()),sendContentPages: (...args) => sendContentPages(...args),@@ -181,3 +185,47 @@ describe('POST /api/content-drafts/webflow-status', () => {expect(await failed.json()).toMatchObject({ code: 'failed' });});});++describe('POST /api/content-drafts/wordpress-status (00294)', () => {+ const check = (body) =>+ fetch(`${baseUrl}/wordpress-status`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++ it('reads the brand’s WordPress posts for any member, a brand at most every two minutes', async () => {+ role = 'member';+ const brand = '77777777-7777-7777-7777-777777777777';+ checkWordPressPublished.mockReset().mockResolvedValue({+ checked: 1,+ published: [{ draftId: DRAFT, url: 'https://blog.acme.example/cold-brew/' }],+ });+ expect(await (await check({ brandId: brand })).json()).toEqual({+ checked: 1,+ published: [{ draftId: DRAFT, url: 'https://blog.acme.example/cold-brew/' }],+ });+ expect(assertBrandAccess).toHaveBeenCalledWith(brand, 'u1');+ expect(await (await check({ brandId: brand })).json()).toEqual({+ checked: 0,+ published: [],+ recent: true,+ });+ expect(checkWordPressPublished).toHaveBeenCalledTimes(1);+ });++ it('refuses another workspace’s brand and a malformed one, and names a failure', async () => {+ checkWordPressPublished.mockReset();+ assertBrandAccess.mockRejectedValueOnce(+ Object.assign(new Error('nope'), { status: 403, code: 'not_in_workspace' }),+ );+ const other = await check({ brandId: '99999999-9999-9999-9999-999999999999' });+ expect(other.status).toBe(403);+ expect(checkWordPressPublished).not.toHaveBeenCalled();+ expect((await check({ brandId: 'x' })).status).toBe(400);+ checkWordPressPublished.mockReset().mockRejectedValue(new Error('down'));+ const failed = await check({ brandId: '88888888-8888-8888-8888-888888888888' });+ expect(failed.status).toBe(502);+ expect(await failed.json()).toEqual({ error: 'WordPress could not be read', code: 'failed' });+ });+});diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex 0fa987e77..c9d044f3b 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -8,6 +8,7 @@ import { briefRules, rebuildDraftBrief, rebuildSources } from '../lib/content-brimport { 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 { checkWordPressPublished } from '../lib/cms/wordpress-status.js';import { liveAddress, publishDraft } from '../lib/content-published.js';import { cmsLimiter, shoppingPathLimiter } from '../middleware/rate-limiter.js';import { stopDraftRun } from '../lib/content-runs.js';@@ -167,6 +168,41 @@ router.post('/webflow-status', cmsLimiter, async (req, res) => {}});+/** A brand's WordPress posts read at most this often on demand (the daily sweep reads them too). */+const wordpressChecked = new Map();++/**+ * POST /api/content-drafts/wordpress-status+ * Body: { brandId }. Pages the brand sent to WordPress, published there+ * since, marked published at the post's link (cms/wordpress-status.js). As+ * /webflow-status: any member, a brand at most every two minutes.+ */+router.post('/wordpress-status', cmsLimiter, async (req, res) => {+ const parsed = webflowStatusBody.safeParse(req.body ?? {});+ if (!parsed.success) return res.status(400).json({ error: 'Invalid request', code: 'invalid' });+ const { brandId } = parsed.data;+ try {+ await assertBrandAccess(brandId, req.user.id);+ const last = wordpressChecked.get(brandId) ?? 0;+ if (Date.now() - last < WEBFLOW_STATUS_EVERY_MS) {+ return res.json({ checked: 0, published: [], recent: true });+ }+ wordpressChecked.set(brandId, Date.now());+ return res.json(await checkWordPressPublished(brandId));+ } catch (err) {+ 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, code: err?.code } },+ 'content draft wordpress status error',+ );+ return res.status(502).json({ error: 'WordPress could not be read', code: 'failed' });+ }+});+const rebuildBody = z.object({// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).brandId: z.guid(),diff --git a/server/src/server.js b/server/src/server.jsindex 3c69ed7b1..217947842 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -34,6 +34,7 @@ import { purgeRemovedCatalogProducts } from './lib/catalog/purge.js';import { sweepCatalogSources } from './lib/catalog/sources.js';import { sweepShoppingCardMatches } from './lib/catalog/card-match.js';import { sweepWebflowPublished } from './lib/cms/webflow-status.js';+import { sweepWordPressPublished } from './lib/cms/wordpress-status.js';import { generateBriefForOpportunity } from './routes/content.js';import webhookContentCallbackRoutes from './routes/webhook-content-callback.js';import webhookContentDraftCallbackRoutes from './routes/webhook-content-draft-callback.js';@@ -347,6 +348,10 @@ async function runDailyTracking() {sweepWebflowPublished().catch((err) => {logger.error({ err: { name: err?.name } }, '[webflow-status] daily sweep failed');});+ // And to WordPress (00294), once a day too.+ sweepWordPressPublished().catch((err) => {+ logger.error({ err: { name: err?.name } }, '[wordpress-status] daily sweep failed');+ });// Google Analytics sync (#704) — same contract as the Search Console sync// above: independent, never blocks or fails the tracking run, no-ops when