Skip to content

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

feat(content): mark a page Published at its live address from the API (CE-013, part 1: server) (#1510)

Cihanb0a488618574
diff --git a/server/src/lib/action-center/basket-metrics.js b/server/src/lib/action-center/basket-metrics.js
index 1f5279c0e..1d12c8c9c 100644
--- a/server/src/lib/action-center/basket-metrics.js
+++ b/server/src/lib/action-center/basket-metrics.js
@@ -109,7 +109,29 @@ export async function basketScope(action) {
if (error) throw new Error(error.message);
promptIds = (prompts || []).map((p) => p.id);
}
- return { promptIds, pages: Array.isArray(payload.pages) ? payload.pages : [] };
+ return { promptIds, pages: scopePages(payload) };
+}
+
+/**
+ * The pages an action is measured on: the ones it names, and the addresses
+ * its drafts went live at (publishedPages by draft, CE-013), each once.
+ */
+function scopePages(payload) {
+ const named = Array.isArray(payload.pages) ? payload.pages : [];
+ const live =
+ payload.publishedPages && typeof payload.publishedPages === 'object'
+ ? Object.values(payload.publishedPages)
+ : [];
+ const seen = new Set();
+ const pages = [];
+ for (const url of [...named, ...live]) {
+ if (typeof url !== 'string') continue;
+ const key = pageScope([url]).keys[0] ?? url;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ pages.push(url);
+ }
+ return pages;
}
/** The basket's metrics over one window. */
diff --git a/server/src/lib/action-center/basket-metrics.test.js b/server/src/lib/action-center/basket-metrics.test.js
index c180bfb38..09a469bd0 100644
--- a/server/src/lib/action-center/basket-metrics.test.js
+++ b/server/src/lib/action-center/basket-metrics.test.js
@@ -80,6 +80,19 @@ describe('basketValues', () => {
});
describe('basketScope', () => {
+ it('measures the pages an action names and those its drafts went live at, each once', async () => {
+ expect(
+ (
+ await basketScope({
+ payload: {
+ pages: ['https://www.acme.example/a/'],
+ publishedPages: { d1: 'https://acme.example/a', d2: 'https://acme.example/new' },
+ },
+ })
+ ).pages,
+ ).toEqual(['https://www.acme.example/a/', 'https://acme.example/new']);
+ });
+
it('uses the prompt ids the action was sent with', async () => {
expect(await basketScope({ payload: { promptIds: ['p1'], pages: ['u'] } })).toEqual({
promptIds: ['p1'],
diff --git a/server/src/lib/content-published.js b/server/src/lib/content-published.js
index 4eb7558f5..c20648b43 100644
--- a/server/src/lib/content-published.js
+++ b/server/src/lib/content-published.js
@@ -1,5 +1,6 @@
import supabaseAdmin from '../config/supabase.js';
import { logger } from './logger.js';
+import { onBrandDomain } from './audit/host.js';
/**
* A sent page now live at `url` (Send to CMS #1331), as a webhook's
@@ -42,22 +43,7 @@ export async function markDeliveryPublished(delivery, url, { externalId = null }
.limit(1)
.maybeSingle();
if (latestError) throw new Error(latestError.message);
- if (latest?.id === delivery.id) {
- const { error: draftError } = await supabaseAdmin
- .from('content_drafts')
- .update({ status: 'published', published_url: url, published_at: now })
- .eq('id', delivery.draft_id);
- if (draftError) throw new Error(draftError.message);
- // The page as published, in History (00215 keeps "publish" for the
- // server), unless History's latest version is already this page.
- const { error: keepError } = await supabaseAdmin.rpc('content_draft_snapshot', {
- p_draft_id: delivery.draft_id,
- p_origin: 'publish',
- });
- if (keepError) {
- logger.warn({ err: keepError }, '[content-published] publish version not kept');
- }
- }
+ if (latest?.id === delivery.id) await markDraftPublished(delivery.draft_id, url, { at: now });
}
const { error: deliveryError } = await supabaseAdmin
.from('content_draft_deliveries')
@@ -65,3 +51,279 @@ export async function markDeliveryPublished(delivery, url, { externalId = null }
.eq('id', delivery.id);
if (deliveryError) throw new Error(deliveryError.message);
}
+
+const MAX_URL = 2048;
+/** Tries at writing an action's live pages when another write lands between. */
+const PAGE_WRITES = 3;
+/** A task a person or the system can still complete: not done, skipped, failed or waiting. */
+const OPEN_TASKS = ['todo', 'in_progress'];
+/** The library tasks a draft is the work of, by its method (the web's DRAFT_TASK_KEYS). */
+const DRAFT_TASK_KEYS = {
+ create: ['create_content_draft'],
+ optimize: ['optimize_content', 'refresh_content'],
+};
+/** A task no longer outstanding work (the web's TASK_DONE). */
+const TASK_DONE = ['completed', 'skipped', 'failed'];
+/** A draft whose writing is done. */
+const DRAFT_DONE = ['ready', 'published'];
+
+/**
+ * An http(s) address as the browser reads it (no stray whitespace kept),
+ * without sign-in details (they'd be stored and shown as a link), or null.
+ */
+export function liveAddress(value) {
+ try {
+ const url = new URL(String(value ?? '').trim());
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
+ if (url.username || url.password) return null;
+ return url.href.length <= MAX_URL ? url.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Whether `url` is on one of the brand's domains, where its numbers can be read. */
+export async function onBrandDomains(brandId, url) {
+ const { data, error } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+ return onBrandDomain(
+ url,
+ (data ?? []).map((d) => d.domain),
+ );
+}
+
+/**
+ * The draft's live address in what its action is measured on
+ * (payload.publishedPages, by draft: read beside payload.pages by
+ * basketScope; payload.pages stays the pages the action names, which its
+ * tasks work through). A page published again moves; one off the brand's
+ * domains leaves it, as its numbers can't be read. Written only when the
+ * payload is still as read, read again when another write landed first.
+ */
+async function setLivePage(action, draftId, url) {
+ let current = action;
+ for (let attempt = 0; attempt < PAGE_WRITES; attempt++) {
+ const payload = current.payload && typeof current.payload === 'object' ? current.payload : {};
+ const live =
+ payload.publishedPages && typeof payload.publishedPages === 'object'
+ ? { ...payload.publishedPages }
+ : {};
+ if ((live[draftId] ?? null) === url) return;
+ if (url) live[draftId] = url;
+ else delete live[draftId];
+ const { data, error } = await supabaseAdmin
+ .from('actions')
+ .update({
+ payload: { ...payload, publishedPages: live },
+ updated_at: new Date().toISOString(),
+ })
+ .eq('id', current.id)
+ .eq('updated_at', current.updated_at)
+ .select('id');
+ if (error) throw new Error(error.message);
+ if (data?.length) return;
+ const { data: again, error: readError } = await supabaseAdmin
+ .from('actions')
+ .select('id, payload, updated_at')
+ .eq('id', current.id)
+ .maybeSingle();
+ if (readError) throw new Error(readError.message);
+ if (!again) return;
+ current = again;
+ }
+ throw new Error('the action changed while its live page was written');
+}
+
+/** The brand pages an action names (payload.pages), once each, as the web's actionPages reads them. */
+function namedPages(action) {
+ const pages = action.payload?.pages;
+ if (!Array.isArray(pages)) return [];
+ return [...new Set(pages.filter((p) => typeof p === 'string' && /^https?:\/\//i.test(p)))];
+}
+
+/**
+ * Whether the action's work is all live: a published create draft when it
+ * has a Create task, and a published optimize draft for each page it names
+ * when it has an Optimize or Refresh task (as Ready completes them). Work
+ * whose task someone skipped isn't waited for.
+ */
+function workPublished(action, tasks, drafts) {
+ const keys = new Set(
+ tasks.filter((task) => task.status !== 'skipped').map((task) => task.task_key),
+ );
+ const live = drafts.filter((d) => d.status === 'published');
+ if (keys.has('create_content_draft') && !live.some((d) => d.method === 'create')) return false;
+ if (keys.has('optimize_content') || keys.has('refresh_content')) {
+ const pages = namedPages(action);
+ const optimized = new Set(live.filter((d) => d.method === 'optimize').map((d) => d.source_url));
+ if (pages.some((page) => !optimized.has(page))) return false;
+ if (!pages.length && !live.some((d) => d.method === 'optimize')) return false;
+ }
+ return true;
+}
+
+/**
+ * Completes the tasks as read, each in the action's History naming the
+ * draft (so taking the page back reopens it, as the web's reopenDraftTasks
+ * reads the trail). A task changed meanwhile (skipped in the drawer, say)
+ * is left as it is, with no entry. Returns how many it completed.
+ */
+async function completeTasks(actionId, todo, data, actorId) {
+ const now = new Date().toISOString();
+ let done = 0;
+ for (const task of todo) {
+ const { data: changed, error } = await supabaseAdmin
+ .from('action_tasks')
+ .update({ status: 'completed', skip_reason: null, updated_at: now })
+ .eq('id', task.id)
+ .eq('status', task.status)
+ .select('id');
+ if (error) throw new Error(error.message);
+ if (!changed?.length) continue;
+ done += 1;
+ // Best effort, as the drawer's: a missing trail entry doesn't undo the change.
+ await supabaseAdmin.from('action_events').insert({
+ action_id: actionId,
+ event: 'task_status',
+ data: { taskId: task.id, to: 'completed', ...data },
+ actor_id: actorId,
+ });
+ }
+ return done;
+}
+
+/**
+ * The page's own work, done as Mark ready does it (the web's
+ * completeDraftTasks): its Create task, or its Optimize or Refresh task
+ * once each page the action names has a ready or published draft. A page
+ * published without Mark ready (sent straight to a CMS, or marked live at
+ * an address) doesn't leave open the work Publish depends on.
+ */
+function ownTasks(action, draft, tasks, drafts) {
+ const method = draft.method === 'create' ? 'create' : 'optimize';
+ if (method === 'optimize') {
+ const pages = namedPages(action);
+ const done = new Set(
+ drafts
+ .filter((d) => d.method === 'optimize' && DRAFT_DONE.includes(d.status))
+ .map((d) => d.source_url),
+ );
+ if (pages.length > 1 && pages.some((page) => !done.has(page))) return [];
+ }
+ return tasks.filter(
+ (task) => DRAFT_TASK_KEYS[method].includes(task.task_key) && !TASK_DONE.includes(task.status),
+ );
+}
+
+/**
+ * A linked action, its draft live at `url`: the address joins what it's
+ * measured on (when on the brand's domains), the page's own task is done
+ * (ownTasks), and once all its work is live, its open Publish task is done
+ * too, each in its History. A deleted action (00168) is left as it is.
+ * Returns whether the Publish task was completed.
+ */
+async function completePublishTask(draft, url, { actorId = null, onDomain } = {}) {
+ const { data: action, error } = await supabaseAdmin
+ .from('actions')
+ .select('id, payload, updated_at')
+ .eq('id', draft.action_id)
+ .eq('brand_id', draft.brand_id)
+ .is('deleted_at', null)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!action) return false;
+ const measured = onDomain ?? (await onBrandDomains(draft.brand_id, url));
+ await setLivePage(action, draft.id, measured ? url : null);
+
+ const { data: tasks, error: tasksError } = await supabaseAdmin
+ .from('action_tasks')
+ .select('id, task_key, status')
+ .eq('action_id', action.id);
+ if (tasksError) throw new Error(tasksError.message);
+ const { data: drafts, error: draftsError } = await supabaseAdmin
+ .from('content_drafts')
+ .select('id, method, source_url, status')
+ .eq('action_id', action.id)
+ .is('archived_at', null);
+ if (draftsError) throw new Error(draftsError.message);
+
+ const changed = await completeTasks(
+ action.id,
+ ownTasks(action, draft, tasks ?? [], drafts ?? []),
+ { draftId: draft.id },
+ actorId,
+ );
+ const todo = (tasks ?? []).filter(
+ (task) => task.task_key === 'publish_content' && OPEN_TASKS.includes(task.status),
+ );
+ const publish =
+ todo.length > 0 && workPublished(action, tasks ?? [], drafts ?? [])
+ ? await completeTasks(action.id, todo, { draftId: draft.id, publishedUrl: url }, actorId)
+ : 0;
+ if (changed + publish > 0) {
+ await supabaseAdmin
+ .from('actions')
+ .update({ updated_at: new Date().toISOString() })
+ .eq('id', action.id);
+ }
+ return publish > 0;
+}
+
+/**
+ * A page live at `url` (CE-013): Published, at that address, since `at`,
+ * kept in History as a "publish" version (00215 keeps it for the server)
+ * unless History's latest version is already this page; and its linked
+ * action told (completePublishTask). The page is published whatever the
+ * action's part does: that is logged, not thrown.
+ *
+ * @returns {Promise<{ taskCompleted: boolean }>}
+ */
+export async function markDraftPublished(
+ draftId,
+ url,
+ { at = new Date().toISOString(), actorId = null, onDomain } = {},
+) {
+ const { data: draft, error } = await supabaseAdmin
+ .from('content_drafts')
+ .update({ status: 'published', published_url: url, published_at: at })
+ .eq('id', draftId)
+ .select('id, brand_id, action_id, method')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ const { error: keepError } = await supabaseAdmin.rpc('content_draft_snapshot', {
+ p_draft_id: draftId,
+ p_origin: 'publish',
+ });
+ if (keepError) {
+ logger.warn({ err: keepError }, '[content-published] publish version not kept');
+ }
+ if (!draft?.action_id) return { taskCompleted: false };
+ try {
+ return { taskCompleted: await completePublishTask(draft, url, { actorId, onDomain }) };
+ } catch (err) {
+ logger.warn(
+ { err: { name: err?.name, message: err?.message }, draftId },
+ '[content-published] action not told',
+ );
+ return { taskCompleted: false };
+ }
+}
+
+/**
+ * A person marks a page live at `url` (CE-013): it becomes Published there
+ * (markDraftPublished), so its Live page tab measures that address, and its
+ * linked action is told. Says whether the address is on the brand's
+ * domains: off them, it's kept, but its numbers can't be read.
+ *
+ * @param {{ id: string, brand_id: string }} draft
+ * @returns {Promise<{ publishedUrl: string, publishedAt: string, taskCompleted: boolean, onBrandDomain: boolean }>}
+ */
+export async function publishDraft(draft, url, actorId) {
+ const at = new Date().toISOString();
+ const onDomain = await onBrandDomains(draft.brand_id, url);
+ const { taskCompleted } = await markDraftPublished(draft.id, url, { at, actorId, onDomain });
+ return { publishedUrl: url, publishedAt: at, taskCompleted, onBrandDomain: onDomain };
+}
diff --git a/server/src/lib/content-published.test.js b/server/src/lib/content-published.test.js
new file mode 100644
index 000000000..3bde29de4
--- /dev/null
+++ b/server/src/lib/content-published.test.js
@@ -0,0 +1,299 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * A page marked Published at its live address (CE-013), by a person or a
+ * CMS: the draft, its History version, and a linked action's measured pages
+ * and Publish task. The tables live in memory, their filters applied.
+ */
+
+let tables;
+const clone = (value) => JSON.parse(JSON.stringify(value));
+const rpcs = [];
+const events = [];
+
+function query(name) {
+ const filters = [];
+ let write = null;
+ let returning = false;
+ const rows = () => tables[name].filter((row) => filters.every((f) => f(row)));
+ const run = () => {
+ if (write?.insert) {
+ tables[name].push(write.insert);
+ return { data: null, error: null };
+ }
+ if (write?.update) {
+ const hit = rows();
+ for (const row of hit) Object.assign(row, clone(write.update));
+ return { data: returning ? hit.map((r) => ({ ...r })) : null, error: null };
+ }
+ return { data: rows().map((r) => clone(r)), error: null };
+ };
+ const chain = {
+ select: () => ((returning = true), chain),
+ eq: (col, value) => (filters.push((row) => row[col] === value), chain),
+ neq: (col, value) => (filters.push((row) => row[col] !== value), chain),
+ is: (col, value) => (filters.push((row) => (row[col] ?? null) === value), chain),
+ in: (col, values) => (filters.push((row) => values.includes(row[col])), chain),
+ // The latest delivery is the only one these tests give a draft.
+ order: () => chain,
+ limit: () => chain,
+ update: (row) => ((write = { update: row }), chain),
+ insert: (row) => ((write = { insert: row }), chain),
+ maybeSingle: async () => {
+ const { data } = run();
+ return { data: Array.isArray(data) ? (data[0] ?? null) : data, error: null };
+ },
+ then: (resolve) => resolve(run()),
+ };
+ return chain;
+}
+
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (name) => query(name),
+ rpc: async (fn, args) => {
+ rpcs.push({ fn, args });
+ return { data: 'v1', error: null };
+ },
+ },
+}));
+vi.mock('./logger.js', () => ({
+ logger: { warn: (...args) => events.push(args), error: () => {} },
+}));
+
+const { liveAddress, markDeliveryPublished, publishDraft } = await import('./content-published.js');
+
+const LIVE = 'https://www.acme.example/blog/cold-brew';
+
+const draft = (over = {}) => ({
+ id: 'dr1',
+ brand_id: 'b1',
+ action_id: null,
+ method: 'create',
+ source_url: null,
+ status: 'ready',
+ archived_at: null,
+ ...over,
+});
+const task = (id, key, status = 'todo') => ({ id, action_id: 'a1', task_key: key, status });
+
+beforeEach(() => {
+ tables = {
+ content_drafts: [draft()],
+ actions: [
+ {
+ id: 'a1',
+ brand_id: 'b1',
+ deleted_at: null,
+ updated_at: '2026-10-20T10:00:00Z',
+ payload: { source: 'content_draft', pages: [] },
+ },
+ ],
+ action_tasks: [],
+ action_events: [],
+ brand_domains: [{ brand_id: 'b1', domain: 'acme.example' }],
+ content_draft_deliveries: [],
+ };
+ rpcs.length = 0;
+ events.length = 0;
+});
+
+describe('liveAddress', () => {
+ it('takes an http(s) address as the browser reads it, without sign-in details', () => {
+ expect(liveAddress(' https://Acme.example/blog/x ')).toBe('https://acme.example/blog/x');
+ expect(liveAddress('http://acme.example')).toBe('http://acme.example/');
+ expect(liveAddress('ftp://acme.example/x')).toBeNull();
+ expect(liveAddress('https://user:[email protected]/x')).toBeNull();
+ expect(liveAddress('acme.example/x')).toBeNull();
+ expect(liveAddress(`https://acme.example/${'a'.repeat(2100)}`)).toBeNull();
+ expect(liveAddress(null)).toBeNull();
+ });
+});
+
+describe('publishDraft', () => {
+ it('publishes the page at its address, in History, saying whether it’s on the brand’s domains', async () => {
+ expect(await publishDraft(tables.content_drafts[0], LIVE, 'u1')).toMatchObject({
+ publishedUrl: LIVE,
+ taskCompleted: false,
+ onBrandDomain: true,
+ });
+ expect(tables.content_drafts[0]).toMatchObject({ status: 'published', published_url: LIVE });
+ expect(rpcs).toEqual([
+ { fn: 'content_draft_snapshot', args: { p_draft_id: 'dr1', p_origin: 'publish' } },
+ ]);
+ expect(
+ (await publishDraft(tables.content_drafts[0], 'https://medium.com/@acme/x', 'u1'))
+ .onBrandDomain,
+ ).toBe(false);
+ });
+
+ it('measures the live page with the action, beside the pages it names, and moves it when published again', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.actions[0].payload.pages = ['https://www.acme.example/old'];
+ await publishDraft(tables.content_drafts[0], LIVE, 'u1');
+ expect(tables.actions[0].payload).toEqual({
+ source: 'content_draft',
+ // The pages the action works through stay as they were.
+ pages: ['https://www.acme.example/old'],
+ publishedPages: { dr1: LIVE },
+ });
+ await publishDraft(tables.content_drafts[0], 'https://www.acme.example/blog/cold-brew-2', 'u1');
+ expect(tables.actions[0].payload.publishedPages).toEqual({
+ dr1: 'https://www.acme.example/blog/cold-brew-2',
+ });
+ // Off the brand's domains, its numbers can't be read: it leaves the measurement.
+ await publishDraft(tables.content_drafts[0], 'https://medium.com/@acme/x', 'u1');
+ expect(tables.actions[0].payload.publishedPages).toEqual({});
+ });
+
+ it('completes the Publish task once the action’s work is live, in its History', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.action_tasks = [
+ task('t0', 'create_content_draft', 'completed'),
+ task('t1', 'publish_content'),
+ ];
+ expect((await publishDraft(tables.content_drafts[0], LIVE, 'u1')).taskCompleted).toBe(true);
+ expect(tables.action_tasks[1]).toMatchObject({ status: 'completed', skip_reason: null });
+ expect(tables.action_events).toEqual([
+ {
+ action_id: 'a1',
+ event: 'task_status',
+ data: { taskId: 't1', to: 'completed', draftId: 'dr1', publishedUrl: LIVE },
+ actor_id: 'u1',
+ },
+ ]);
+ });
+
+ it('completes the page’s own task too, as Mark ready does, so Publish doesn’t wait on it', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.action_tasks = [task('t0', 'create_content_draft'), task('t1', 'publish_content')];
+ expect((await publishDraft(tables.content_drafts[0], LIVE, 'u1')).taskCompleted).toBe(true);
+ expect(tables.action_tasks.map((t) => t.status)).toEqual(['completed', 'completed']);
+ // Each change names the draft: taking the page back reopens them.
+ expect(tables.action_events.map((e) => e.data)).toEqual([
+ { taskId: 't0', to: 'completed', draftId: 'dr1' },
+ { taskId: 't1', to: 'completed', draftId: 'dr1', publishedUrl: LIVE },
+ ]);
+ });
+
+ it('completes an Optimize task naming several pages once each has a ready draft', async () => {
+ const pages = ['https://www.acme.example/a', 'https://www.acme.example/b'];
+ tables.actions[0].payload.pages = pages;
+ tables.content_drafts = [
+ draft({ id: 'dr1', action_id: 'a1', method: 'optimize', source_url: pages[0] }),
+ ];
+ tables.action_tasks = [task('t0', 'optimize_content'), task('t1', 'publish_content')];
+ await publishDraft(tables.content_drafts[0], pages[0], 'u1');
+ expect(tables.action_tasks.map((t) => t.status)).toEqual(['todo', 'todo']);
+ // Page b's draft is ready, not live: the work is done, Publish waits.
+ tables.content_drafts.push(
+ draft({ id: 'dr2', action_id: 'a1', method: 'optimize', source_url: pages[1] }),
+ );
+ await publishDraft(tables.content_drafts[0], pages[0], 'u1');
+ expect(tables.action_tasks.map((t) => t.status)).toEqual(['completed', 'todo']);
+ expect((await publishDraft(tables.content_drafts[1], pages[1], 'u1')).taskCompleted).toBe(true);
+ });
+
+ it('leaves a task changed meanwhile as it is, with nothing in its History', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.action_tasks = [task('t1', 'publish_content')];
+ // Skipped in the drawer between the read and the write.
+ const realFilter = tables.action_tasks.filter.bind(tables.action_tasks);
+ let reads = 0;
+ tables.action_tasks.filter = (fn) => {
+ reads += 1;
+ if (reads === 2) tables.action_tasks[0].status = 'skipped';
+ return realFilter(fn);
+ };
+ expect((await publishDraft(tables.content_drafts[0], LIVE, 'u1')).taskCompleted).toBe(false);
+ expect(tables.action_tasks[0].status).toBe('skipped');
+ expect(tables.action_events).toEqual([]);
+ });
+
+ it('reads only the brand pages an action names, once each', async () => {
+ const page = 'https://www.acme.example/a';
+ tables.actions[0].payload.pages = [page, page, 'not a page', 42];
+ tables.content_drafts = [draft({ action_id: 'a1', method: 'optimize', source_url: page })];
+ tables.action_tasks = [task('t0', 'optimize_content'), task('t1', 'publish_content')];
+ expect((await publishDraft(tables.content_drafts[0], page, 'u1')).taskCompleted).toBe(true);
+ });
+
+ it('doesn’t wait for work someone skipped', async () => {
+ tables.content_drafts = [draft({ action_id: 'a1', method: 'optimize', source_url: LIVE })];
+ tables.action_tasks = [
+ task('t0', 'create_content_draft', 'skipped'),
+ task('t1', 'optimize_content'),
+ task('t2', 'publish_content'),
+ ];
+ expect((await publishDraft(tables.content_drafts[0], LIVE, 'u1')).taskCompleted).toBe(true);
+ expect(tables.action_tasks.map((t) => t.status)).toEqual(['skipped', 'completed', 'completed']);
+ });
+
+ it('waits for every page an Optimize task names, a draft each, before Publish is done', async () => {
+ const pages = ['https://www.acme.example/a', 'https://www.acme.example/b'];
+ tables.actions[0].payload.pages = pages;
+ tables.content_drafts = [
+ draft({ id: 'dr1', action_id: 'a1', method: 'optimize', source_url: pages[0] }),
+ ];
+ tables.action_tasks = [
+ task('t0', 'optimize_content', 'completed'),
+ task('t1', 'publish_content'),
+ ];
+ // Page b has no draft yet.
+ expect((await publishDraft(tables.content_drafts[0], pages[0], 'u1')).taskCompleted).toBe(
+ false,
+ );
+ tables.content_drafts.push(
+ draft({ id: 'dr2', action_id: 'a1', method: 'optimize', source_url: pages[1] }),
+ );
+ expect((await publishDraft(tables.content_drafts[1], pages[1], 'u1')).taskCompleted).toBe(true);
+ // An archived draft doesn't count.
+ tables.action_tasks[1].status = 'todo';
+ tables.content_drafts[0].status = 'ready';
+ tables.content_drafts[0].archived_at = '2026-10-24T10:00:00Z';
+ expect((await publishDraft(tables.content_drafts[1], pages[1], 'u1')).taskCompleted).toBe(
+ false,
+ );
+ });
+
+ it('leaves a Publish task someone skipped, and a deleted action, as they are', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.action_tasks = [task('t1', 'publish_content', 'skipped')];
+ expect((await publishDraft(tables.content_drafts[0], LIVE, 'u1')).taskCompleted).toBe(false);
+ expect(tables.action_tasks[0].status).toBe('skipped');
+ tables.actions[0].deleted_at = '2026-10-24T10:00:00Z';
+ tables.actions[0].payload = { pages: [] };
+ await publishDraft(tables.content_drafts[0], LIVE, 'u1');
+ expect(tables.actions[0].payload).toEqual({ pages: [] });
+ // Another brand's action isn't touched either.
+ tables.actions[0] = { ...tables.actions[0], deleted_at: null, brand_id: 'b2' };
+ await publishDraft(tables.content_drafts[0], LIVE, 'u1');
+ expect(tables.actions[0].payload).toEqual({ pages: [] });
+ });
+
+ it('keeps the page published when the action’s part fails, saying so in the log', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.actions[0].payload = null;
+ tables.action_tasks = null;
+ const published = await publishDraft(tables.content_drafts[0], LIVE, 'u1');
+ expect(published.taskCompleted).toBe(false);
+ expect(tables.content_drafts[0].status).toBe('published');
+ expect(events.length).toBe(1);
+ });
+});
+
+describe('markDeliveryPublished', () => {
+ it('tells the action of a page its CMS published, as a person’s publish does', async () => {
+ tables.content_drafts[0].action_id = 'a1';
+ tables.action_tasks = [task('t1', 'publish_content')];
+ tables.content_draft_deliveries = [{ id: 'x1', draft_id: 'dr1', status: 'sent' }];
+ await markDeliveryPublished(
+ { id: 'x1', draft_id: 'dr1', status: 'sent', published_url: null },
+ LIVE,
+ );
+ expect(tables.content_drafts[0]).toMatchObject({ status: 'published', published_url: LIVE });
+ expect(tables.actions[0].payload.publishedPages).toEqual({ dr1: LIVE });
+ expect(tables.action_tasks[0].status).toBe('completed');
+ expect(tables.action_events[0].actor_id).toBeNull();
+ });
+});
diff --git a/server/src/routes/content-drafts-publish.test.js b/server/src/routes/content-drafts-publish.test.js
new file mode 100644
index 000000000..28a0d5825
--- /dev/null
+++ b/server/src/routes/content-drafts-publish.test.js
@@ -0,0 +1,122 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+
+/**
+ * POST /api/content-drafts/:draftId/publish (CE-013): a member marks a page
+ * Published at its live address.
+ */
+
+const DRAFT = '77777777-7777-7777-7777-777777777777';
+
+let draftRow;
+const assertBrandAccess = vi.fn();
+const publishDraft = vi.fn();
+vi.mock('../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const chain = {
+ select: () => chain,
+ eq: () => chain,
+ maybeSingle: async () => ({ data: draftRow, error: null }),
+ single: async () => ({ data: { role: 'member' }, error: null }),
+ then: (resolve) =>
+ resolve(
+ table === 'brand_domains'
+ ? { data: [{ domain: 'acme.example' }], error: null }
+ : { data: null, error: null },
+ ),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));
+vi.mock('../lib/content-published.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ publishDraft: (...args) => publishDraft(...args),
+}));
+
+const { default: router } = await import('./content-drafts.js');
+
+let server;
+let baseUrl;
+
+beforeEach(async () => {
+ draftRow = { id: DRAFT, brand_id: 'b1', action_id: 'a1', archived_at: null };
+ assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });
+ publishDraft.mockReset().mockImplementation(async (_draft, url) => ({
+ publishedUrl: url,
+ publishedAt: '2026-10-25T10:00:00Z',
+ taskCompleted: true,
+ onBrandDomain: url.includes('acme.example'),
+ }));
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: 'u1' };
+ req.log = { error: vi.fn() };
+ next();
+ });
+ app.use('/api/content-drafts', router);
+ await new Promise((resolve) => {
+ server = app.listen(0, resolve);
+ });
+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content-drafts`;
+});
+
+afterEach(() => new Promise((resolve) => server.close(resolve)));
+
+const publish = (body, id = DRAFT) =>
+ fetch(`${baseUrl}/${id}/publish`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+describe('POST /api/content-drafts/:draftId/publish', () => {
+ it('publishes the page at its address for a member of the brand’s workspace', async () => {
+ const res = await publish({ url: ' https://www.acme.example/blog/cold-brew ' });
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ publishedUrl: 'https://www.acme.example/blog/cold-brew',
+ publishedAt: '2026-10-25T10:00:00Z',
+ taskCompleted: true,
+ onBrandDomain: true,
+ });
+ expect(assertBrandAccess).toHaveBeenCalledWith('b1', 'u1');
+ expect(publishDraft).toHaveBeenCalledWith(
+ draftRow,
+ 'https://www.acme.example/blog/cold-brew',
+ 'u1',
+ );
+ });
+
+ it('answers a failure to publish in plain words', async () => {
+ publishDraft.mockRejectedValueOnce(new Error('db down'));
+ const res = await publish({ url: 'https://medium.com/@acme/cold-brew' });
+ expect(res.status).toBe(500);
+ expect(await res.json()).toMatchObject({ code: 'failed' });
+ });
+
+ it('refuses an address that isn’t one, a page archived or gone, and another workspace’s', async () => {
+ const bad = await publish({ url: 'javascript:alert(1)' });
+ expect(bad.status).toBe(400);
+ expect(await bad.json()).toMatchObject({ code: 'invalid_url' });
+ expect((await publish({ url: 'https://user:[email protected]/x' })).status).toBe(400);
+ expect((await publish({ url: 'https://acme.example/x' }, 'not-a-draft')).status).toBe(400);
+
+ draftRow = { ...draftRow, archived_at: '2026-10-24T10:00:00Z' };
+ expect((await publish({ url: 'https://acme.example/x' })).status).toBe(404);
+ draftRow = null;
+ expect((await publish({ url: 'https://acme.example/x' })).status).toBe(404);
+
+ draftRow = { id: DRAFT, brand_id: 'b2', action_id: null, archived_at: null };
+ assertBrandAccess.mockRejectedValueOnce(
+ Object.assign(new Error('nope'), { status: 403, code: 'not_in_workspace' }),
+ );
+ const other = await publish({ url: 'https://acme.example/x' });
+ expect(other.status).toBe(403);
+ expect(await other.json()).toMatchObject({ code: 'not_in_workspace' });
+ expect(publishDraft).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index fd94b11f2..167bb7801 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -7,6 +7,7 @@ import { qualityPhase } from '../lib/content-quality.js';
import { rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';
import { DeliveryError, sendContentPages, sendInput } from '../lib/content-delivery.js';
import { checkWebflowPublished } from '../lib/cms/webflow-status.js';
+import { liveAddress, publishDraft } from '../lib/content-published.js';
import { cmsLimiter } from '../middleware/rate-limiter.js';
import { stopDraftRun } from '../lib/content-runs.js';
import { startDraftWriting, writeDraftInput } from '../lib/content-writer.js';
@@ -77,6 +78,56 @@ router.post('/send', async (req, res) => {
}
});
+const publishBody = z.object({ url: z.string().max(8192) });
+
+/**
+ * POST /api/content-drafts/:draftId/publish
+ * Body: { url }. A person marks the page Published at its live address
+ * (CE-013): any member of the brand's workspace, as they change its status.
+ * Its Live page tab then measures that address, and a linked action gets
+ * the page (its Publish task done once all its pages are live). Answers
+ * { publishedUrl, publishedAt, taskCompleted, onBrandDomain }: an address
+ * off the brand's domains is kept, but its numbers won't show.
+ */
+router.post('/:draftId/publish', async (req, res) => {
+ const id = z.guid().safeParse(req.params.draftId);
+ const parsed = publishBody.safeParse(req.body ?? {});
+ if (!id.success || !parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', code: 'invalid' });
+ }
+ const url = liveAddress(parsed.data.url);
+ if (!url) {
+ return res.status(400).json({
+ error: 'Give the http(s) address the page is live at, with no sign-in details.',
+ code: 'invalid_url',
+ });
+ }
+ try {
+ const { data: draft, error } = await supabaseAdmin
+ .from('content_drafts')
+ .select('id, brand_id, action_id, archived_at')
+ .eq('id', id.data)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ // An archived page is restored first, as its status is changed.
+ if (!draft || draft.archived_at) {
+ return res.status(404).json({ error: 'Not found', code: 'not_found' });
+ }
+ await assertBrandAccess(draft.brand_id, req.user.id);
+ return res.json(await publishDraft(draft, url, req.user.id));
+ } 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 } }, 'content draft publish error');
+ return res
+ .status(500)
+ .json({ error: 'The page could not be marked published', code: 'failed' });
+ }
+});
+
/** A brand's Webflow pages read at most this often on demand (the daily sweep reads them too). */
const WEBFLOW_STATUS_EVERY_MS = 2 * 60 * 1000;
const webflowChecked = new Map();
diff --git a/server/src/routes/webhook-content-draft-callback.js b/server/src/routes/webhook-content-draft-callback.js
index 86c09d3f1..5181d6e78 100644
--- a/server/src/routes/webhook-content-draft-callback.js
+++ b/server/src/routes/webhook-content-draft-callback.js
@@ -7,7 +7,7 @@ import {
webhookCallbackAuthFailureLimiter,
} from '../middleware/rate-limiter.js';
import { webhookSecretsMatch } from '../lib/webhook-secret.js';
-import { markDeliveryPublished } from '../lib/content-published.js';
+import { liveAddress, markDeliveryPublished } from '../lib/content-published.js';
/**
* Send to CMS's callback (#1331): the workspace's automation tells how a sent
@@ -57,21 +57,6 @@ const statusBody = z.object({
reason: mapped(z.string().trim().max(500)),
});
-/**
- * An http(s) address as the browser reads it (no stray whitespace kept),
- * without sign-in details (they'd be stored and shown as a link), or null.
- */
-function liveAddress(value) {
- try {
- const url = new URL(value);
- if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
- if (url.username || url.password) return null;
- return url.href.length <= MAX_URL ? url.href : null;
- } catch {
- return null;
- }
-}
-
/**
* POST /webhooks/content-drafts/:deliveryId/status
* Body: { status: "published", url, externalId? } or { status: "failed", reason?, externalId? }.