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(content): check the page before it's marked ready, with its JSON-LD to paste (CE-041) (#1420)
Cihan80743e98e47e
diff --git a/supabase/migrations/00260_content_draft_ready_log.sql b/supabase/migrations/00260_content_draft_ready_log.sqlnew file mode 100644index 000000000..0951691fd--- /dev/null+++ b/supabase/migrations/00260_content_draft_ready_log.sql@@ -0,0 +1,54 @@+-- ============================================================================+-- 00260: Mark ready anyway, logged (Content Editor Quality, CE-041)+-- ============================================================================+-- Before you publish (Quality spec §7) warns when a page's Trust is under 60+-- and still lets the person mark it ready: "Mark ready anyway (logged)".+-- Each time, a row keeps the Trust the page had, the check the warning named+-- (its id, e.g. claimsSourced, and how many it counted) and who marked it.+--+-- A member adds a row as themselves, only for a draft of their brand that is+-- ready, and gives only the draft, the Trust and the reason: who and when+-- are the database's. Members read them; nothing changes or deletes them,+-- and they go with the draft.++create table if not exists public.content_draft_ready_log (+ id uuid primary key default gen_random_uuid(),+ draft_id uuid not null references public.content_drafts(id) on delete cascade,+ trust smallint not null check (trust between 0 and 100),+ reason text check (reason is null or reason ~ '^[A-Za-z]{1,40}$'),+ reason_count integer check (reason_count is null or reason_count >= 0),+ created_by uuid default auth.uid() references public.profiles(id) on delete set null,+ created_at timestamptz not null default now()+);++create index if not exists content_draft_ready_log_draft_idx+ on public.content_draft_ready_log (draft_id, created_at desc);++alter table public.content_draft_ready_log enable row level security;+revoke all on table public.content_draft_ready_log from anon, authenticated;+grant select on table public.content_draft_ready_log to authenticated;+grant insert (draft_id, trust, reason, reason_count)+ on table public.content_draft_ready_log to authenticated;+grant all on table public.content_draft_ready_log to service_role;++drop policy if exists "content_draft_ready_log: member select" on public.content_draft_ready_log;+create policy "content_draft_ready_log: member select"+ on public.content_draft_ready_log+ for select+ using (public.content_draft_member(draft_id));++drop policy if exists "content_draft_ready_log: member insert" on public.content_draft_ready_log;+create policy "content_draft_ready_log: member insert"+ on public.content_draft_ready_log+ for insert+ with check (+ public.content_draft_member(draft_id)+ and created_by = auth.uid()+ and exists (+ select 1 from public.content_drafts d+ where d.id = draft_id and d.status = 'ready'+ )+ );++comment on table public.content_draft_ready_log is+ 'Content Editor Quality (CE-041): each "Mark ready anyway" past the Trust < 60 warning — the Trust the page had, the check the warning named and its count, who and when. Added by members as themselves for a ready draft; never changed.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 2c55fcef8..5afaf7374 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -37979,3 +37979,61 @@ create policy "site_trust: member select"comment on table public.site_trust is'Content Editor Quality (CE-043): a brand''s five site trust checks (About, Contact, editorial policy, Organization schema on the home page, author pages) and how many pass. Written by the server, read by members.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00260_content_draft_ready_log.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00260: Mark ready anyway, logged (Content Editor Quality, CE-041)+-- ============================================================================+-- Before you publish (Quality spec §7) warns when a page's Trust is under 60+-- and still lets the person mark it ready: "Mark ready anyway (logged)".+-- Each time, a row keeps the Trust the page had, the check the warning named+-- (its id, e.g. claimsSourced, and how many it counted) and who marked it.+--+-- A member adds a row as themselves, only for a draft of their brand that is+-- ready, and gives only the draft, the Trust and the reason: who and when+-- are the database's. Members read them; nothing changes or deletes them,+-- and they go with the draft.++create table if not exists public.content_draft_ready_log (+ id uuid primary key default gen_random_uuid(),+ draft_id uuid not null references public.content_drafts(id) on delete cascade,+ trust smallint not null check (trust between 0 and 100),+ reason text check (reason is null or reason ~ '^[A-Za-z]{1,40}$'),+ reason_count integer check (reason_count is null or reason_count >= 0),+ created_by uuid default auth.uid() references public.profiles(id) on delete set null,+ created_at timestamptz not null default now()+);++create index if not exists content_draft_ready_log_draft_idx+ on public.content_draft_ready_log (draft_id, created_at desc);++alter table public.content_draft_ready_log enable row level security;+revoke all on table public.content_draft_ready_log from anon, authenticated;+grant select on table public.content_draft_ready_log to authenticated;+grant insert (draft_id, trust, reason, reason_count)+ on table public.content_draft_ready_log to authenticated;+grant all on table public.content_draft_ready_log to service_role;++drop policy if exists "content_draft_ready_log: member select" on public.content_draft_ready_log;+create policy "content_draft_ready_log: member select"+ on public.content_draft_ready_log+ for select+ using (public.content_draft_member(draft_id));++drop policy if exists "content_draft_ready_log: member insert" on public.content_draft_ready_log;+create policy "content_draft_ready_log: member insert"+ on public.content_draft_ready_log+ for insert+ with check (+ public.content_draft_member(draft_id)+ and created_by = auth.uid()+ and exists (+ select 1 from public.content_drafts d+ where d.id = draft_id and d.status = 'ready'+ )+ );++comment on table public.content_draft_ready_log is+ 'Content Editor Quality (CE-041): each "Mark ready anyway" past the Trust < 60 warning — the Trust the page had, the check the warning named and its count, who and when. Added by members as themselves for a ready draft; never changed.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 6ff8de7c6..6c58b3855 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4149,6 +4149,45 @@},"qualityChip": "Quality {score}","qualityChipHint": "An Ansvisor estimate of this page's quality. Open Quality.",+ "beforePublish": {+ "title": "Before you publish",+ "warning": "Trust {trust}, below 60. {reason}. You can mark it ready, but {count, plural, one {fixing it} other {fixing them}} first raises Trust to about {raised}.",+ "warningNoReason": "Trust {trust}, below 60. You can mark it ready, but Quality shows what would raise it.",+ "logged": "Mark ready anyway is logged, with this Trust.",+ "author": {+ "ok": "Author for your CMS",+ "okDetail": "Set {name} as the page's author in your CMS. Its template shows the byline; nothing is added to the content.",+ "unknown": "The authors couldn't be read here, so the code below leaves the author out. Set the page's author in your CMS.",+ "none": "No author yet",+ "noneDetail": "The page goes out as {byline}, with the brand's Organization schema. A real author raises E-E-A-T."+ },+ "dates": {+ "title": "Visible published and updated dates",+ "detail": "Most CMSs (WordPress, Webflow, Shopify) add these for you. Check your page."+ },+ "schema": {+ "title": "Article schema with datePublished and dateModified",+ "detail": "Often added by your CMS. If not, paste the code below into the page.",+ "titleLive": "Article schema with dateModified",+ "detailLive": "Often added by your CMS. If not, paste the code below into the page. It gives only the updated date: your page keeps the published date it has.",+ "other": "Schema for this page type",+ "otherDetail": "Check what your CMS adds for it (Product, ItemList…). The code Ansvisor gives here is for articles."+ },+ "linksPending": "Still reading {count, plural, one {# of the page's links} other {# of the page's links}}, so Trust may change.",+ "datesNote": "The dates are today's: change them if the page goes out on another day.",+ "headlineLeftOut": "The title still has a placeholder in square brackets, so the code leaves the headline out. Fill it in, and the headline comes back here.",+ "states": {+ "check": "check it",+ "missing": "missing"+ },+ "jsonLd": "JSON-LD for this page",+ "copy": "Copy JSON-LD",+ "copied": "JSON-LD copied",+ "copyFailed": "Couldn't copy the JSON-LD. Select it and copy it yourself.",+ "fixFirst": "Fix first",+ "markReady": "Mark ready",+ "markReadyAnyway": "Mark ready anyway"+ },"quality": {"scores": "Quality scores","names": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxnew file mode 100644index 000000000..2c12f87ff--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -0,0 +1,303 @@+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 type { ContentAuthor } from '@/lib/content/authors';+import { eeat, trust, trustBlocks, type TrustRead } from '@/lib/content/quality-checks';+import { qualityTodos } from '@/lib/content/quality-todos';+import type { SiteTrust } from '@/lib/content/site-trust';++const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, ...props }: { href: string } & Record<string, unknown>) => (+ <a href={href} {...props} />+ ),+}));++const { BeforePublish } = await import('./_before-publish');+type QualityRead = import('./_quality-tab').QualityRead;++/**+ * Before you publish (Quality spec §7, CE-041): the Trust < 60 warning, what+ * the CMS does, the JSON-LD to paste, and Mark ready (anyway, logged).+ */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const ada: ContentAuthor = {+ id: 'a1',+ name: 'Ada Lovelace',+ title: 'Head of Content',+ bio: 'Writes about forecasting.',+ photoUrl: null,+ sameAs: ['https://www.linkedin.com/in/ada'],+ userId: null,+ createdBy: null,+ defaultFor: [],+ pages: null,+};+const siteTrust: SiteTrust = {+ checks: {+ about: { ok: true, url: 'https://acme.com/about' },+ contact: { ok: false, url: null },+ editorial: { ok: false, url: null },+ organizationSchema: { ok: true, url: 'https://acme.com/' },+ authorPages: { ok: true, authors: [{ name: 'Ada Lovelace', url: 'https://acme.com/ada' }] },+ },+ score: 3,+ checkedAt: '2026-10-23T12:00:00.000Z',+};+/** Three figures, one with a source: Trust 10 of 30 plus site trust 3 of 5, 37; sourced, 94. */+const lowTrust: TrustRead = trust({+ blocks: trustBlocks(+ '<p>Win rates rose 42% (<a href="https://research.example/r">report</a>).</p>' ++ '<p>Deals close $2.5 million faster.</p><p>Teams book 3x more demos.</p>',+ ),+ links: new Map(),+ brandDomains: ['acme.com'],+ siteTrust,+ now: Date.parse('2026-10-23T12:00:00Z'),+});++function quality(over: Partial<QualityRead> = {}): QualityRead {+ const author = over.author === undefined ? ada : over.author;+ const score = eeat({ author });+ return {+ readability: null,+ eeat: score,+ trust: lowTrust,+ author,+ canEdit: true,+ hasAuthors: true,+ brandName: 'Acme',+ siteTrust,+ todos: qualityTodos({ eeat: score, author, hasAuthors: true, canEdit: true }),+ ...over,+ };+}++let container: HTMLDivElement;+let root: Root;+const onMarkReady = vi.fn();+const onFixFirst = vi.fn();+const writeText = vi.fn();++async function render(+ q: QualityRead,+ {+ isNew = true,+ pageType = 'blog_post' as string | null,+ image = 'https://cdn.acme.com/pour-over.jpg' as string | null,+ linksPending = 0,+ title = 'How small teams forecast',+ } = {},+) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <BeforePublish+ onClose={() => {}}+ quality={q}+ title={title}+ isNew={isNew}+ pageType={pageType}+ image={image}+ linksPending={linksPending}+ onMarkReady={onMarkReady}+ onFixFirst={onFixFirst}+ />+ </NextIntlClientProvider>,+ );+ });+}+const dialog = () => document.querySelector('[role="dialog"]')!;+const alert = () => dialog().querySelector('[role="alert"]');+const button = (name: string) =>+ [...dialog().querySelectorAll('button')].find((b) => b.textContent === name);+const rows = () => [...dialog().querySelectorAll('li > div')].map((row) => row.textContent);+const jsonLd = () =>+ JSON.parse(+ dialog()+ .querySelector('pre')!+ .textContent!.replace(/^<script[^>]*>/, '')+ .replace(/<\/script>$/, ''),+ );+/** A Trust read as the checks would give it. */+const trustRead = (over: Partial<TrustRead>): TrustRead => ({+ score: 50,+ checks: [],+ broken: [],+ stale: [],+ dated: 0,+ unsourced: [],+ figures: 0,+ ...over,+});++beforeEach(() => {+ onMarkReady.mockReset();+ onFixFirst.mockReset();+ writeText.mockReset().mockResolvedValue(undefined);+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('BeforePublish', () => {+ it('warns under Trust 60 with the biggest reason, and logs Mark ready anyway', async () => {+ expect(lowTrust.score).toBe(37);+ await render(quality());+ expect(alert()!.textContent).toBe(+ 'Trust 37, below 60. 2 sentences with figures have no source. You can mark it ready, but fixing them first raises Trust to about 94.' ++ 'Mark ready anyway is logged, with this Trust.',+ );+ // The action has the focus, not the code (it moves there after a frame).+ await act(async () => new Promise((resolve) => setTimeout(resolve, 50)));+ expect(document.activeElement).toBe(button('Mark ready anyway'));+ await act(async () => button('Mark ready anyway')!.click());+ expect(onMarkReady).toHaveBeenCalledWith({ trust: 37, reason: 'claimsSourced', count: 2 });+ await act(async () => button('Fix first')!.click());+ expect(onFixFirst).toHaveBeenCalledWith('Deals close $2.5 million faster.');+ });++ it('names the check that raises Trust most', async () => {+ await render(+ quality({+ trust: trustRead({+ score: 51,+ checks: [+ { id: 'claimsSourced', points: 25, max: 30 },+ { id: 'freshSources', points: 0, max: 7 },+ ],+ unsourced: ['Teams book 3x more demos.'],+ figures: 6,+ stale: [{ url: 'https://old.example/', text: 'An old study.' }],+ dated: 1,+ }),+ }),+ );+ expect(alert()!.textContent).toContain('1 of 1 dated source is over 24 months old');+ await act(async () => button('Fix first')!.click());+ expect(onFixFirst).toHaveBeenCalledWith('An old study.');+ });++ it("says Trust is low with no reason when the page's own checks pass", async () => {+ await render(+ quality({+ trust: trustRead({ score: 40, checks: [{ id: 'siteTrust', points: 2, max: 5 }] }),+ }),+ );+ expect(alert()!.textContent).toContain(+ 'Trust 40, below 60. You can mark it ready, but Quality shows what would raise it.',+ );+ expect(button('Fix first')).toBeDefined();+ await act(async () => button('Mark ready anyway')!.click());+ expect(onMarkReady).toHaveBeenCalledWith({ trust: 40, reason: null, count: null });+ });++ it('marks it ready with no warning at Trust 60, or while Trust is unread', async () => {+ await render(+ quality({+ trust: trustRead({+ score: 60,+ checks: [{ id: 'claimsSourced', points: 18, max: 30 }],+ unsourced: ['A figure.'],+ figures: 2,+ }),+ }),+ );+ expect(alert()).toBeNull();+ await render(quality({ trust: null }));+ expect(alert()).toBeNull();+ expect(button('Fix first')).toBeUndefined();+ await act(async () => button('Mark ready')!.click());+ expect(onMarkReady).toHaveBeenCalledWith(null);+ });++ it('says when links are still being read, as Trust may change', async () => {+ await render(quality({ trust: null }), { linksPending: 2 });+ expect(dialog().querySelector('[role="status"]')!.textContent).toBe(+ "Still reading 2 of the page's links, so Trust may change.",+ );+ });++ it('says what the CMS does: the author, the dates and the Article schema', async () => {+ await render(quality());+ expect(rows()).toEqual([+ "Author for your CMS · check itSet Ada Lovelace as the page's author in your CMS. Its template shows the byline; nothing is added to the content.",+ 'Visible published and updated dates · check itMost CMSs (WordPress, Webflow, Shopify) add these for you. Check your page.',+ 'Article schema with datePublished and dateModified · check itOften added by your CMS. If not, paste the code below into the page.',+ ]);+ });++ it('gives the JSON-LD from the page, author and site to copy, dated today', async () => {+ await render(quality());+ expect(jsonLd()).toMatchObject({+ '@type': 'Article',+ headline: 'How small teams forecast',+ image: 'https://cdn.acme.com/pour-over.jpg',+ author: {+ '@type': 'Person',+ name: 'Ada Lovelace',+ url: 'https://acme.com/ada',+ sameAs: ['https://www.linkedin.com/in/ada'],+ },+ publisher: { '@type': 'Organization', name: 'Acme', url: 'https://acme.com/' },+ });+ expect(jsonLd().datePublished).toBe(jsonLd().dateModified);+ expect(dialog().textContent).toContain("The dates are today's");+ await act(async () => button('Copy JSON-LD')!.click());+ expect(writeText).toHaveBeenCalledWith(dialog().querySelector('pre')!.textContent);+ expect(toast.success).toHaveBeenCalledWith('JSON-LD copied');+ });++ it('leaves the headline out while the title has a placeholder, and says why', async () => {+ await render(quality(), { title: 'How [number] small teams forecast' });+ expect(jsonLd()).not.toHaveProperty('headline');+ expect(dialog().textContent).toContain(+ 'The title still has a placeholder in square brackets, so the code leaves the headline out.',+ );+ expect(button('Copy JSON-LD')).toBeDefined();+ });++ it("leaves the author out while the authors aren't read", async () => {+ await render(quality({ eeat: null, author: null }));+ expect(rows()[0]).toContain("The authors couldn't be read here");+ expect(jsonLd()).not.toHaveProperty('author');+ });++ it('names the team byline as missing, and keeps a live page its published date', async () => {+ await render(quality({ author: null }), { isNew: false, image: null });+ const [author, , schema] = rows();+ expect(author).toBe(+ "No author yet · missingThe page goes out as Acme Team, with the brand's Organization schema. A real author raises E-E-A-T.",+ );+ expect(schema).toContain('Article schema with dateModified');+ expect(schema).toContain('It gives only the updated date');+ expect(jsonLd().author).toEqual({+ '@type': 'Organization',+ name: 'Acme',+ url: 'https://acme.com/',+ });+ expect(jsonLd()).not.toHaveProperty('datePublished');+ expect(jsonLd()).not.toHaveProperty('image');+ });++ it("gives no Article for a page that isn't one", async () => {+ await render(quality(), { pageType: 'product_page' });+ expect(rows()).toEqual([+ expect.stringContaining('Author for your CMS'),+ 'Schema for this page type · check itCheck what your CMS adds for it (Product, ItemList…). The code Ansvisor gives here is for articles.',+ ]);+ expect(dialog().querySelector('pre')).toBeNull();+ expect(button('Copy JSON-LD')).toBeUndefined();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsxnew file mode 100644index 000000000..31c1548e4--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx@@ -0,0 +1,255 @@+'use client';++import { useRef } from 'react';+import { useTranslations } from 'next-intl';+import { AlertTriangle } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import {+ articleJsonLd,+ isArticlePage,+ jsonLdScript,+ localDate,+ titleHasPlaceholder,+} from '@/lib/content/page-schema';+import { cn } from '@/lib/utils';+import { copyToClipboard } from './_html-block';+import { trustSuggestions, type QualityRead } from './_quality-tab';++/** Trust under this warns before the page is marked ready (Quality spec §7). */+export const TRUST_GATE = 60;++/** The warning's facts, logged when the page is marked ready anyway. */+export interface ReadyAnyway {+ trust: number;+ /** The Trust check the warning named, and how many it counted. */+ reason: string | null;+ count: number | null;+}++type RowState = 'missing' | 'check';++/**+ * Before you publish (Content Editor Quality spec §7, CE-041), on Mark+ * ready: a warning only when Trust is under 60 (nothing else blocks), what+ * the CMS does for the page (its author, dates and schema), and for an+ * article the JSON-LD to paste when the CMS doesn't write one, from the+ * page's facts only. Mark ready anyway is logged with the Trust the page+ * had. Rendered only while open.+ */+export function BeforePublish({+ onClose,+ quality,+ title,+ isNew,+ pageType,+ image,+ linksPending,+ onMarkReady,+ onFixFirst,+}: {+ onClose: () => void;+ quality: QualityRead;+ title: string;+ /** A new page; an optimized one is already live, with its published date. */+ isNew: boolean;+ pageType: string | null;+ /** The page's own image (firstImage). */+ image: string | null;+ /** The page's links whose read may still come: Trust may change. */+ linksPending: number;+ /** Marks it ready: with the warning's facts when past it. */+ onMarkReady: (anyway: ReadyAnyway | null) => void;+ /** Goes to what would raise Trust, the passage named first. */+ onFixFirst: (show: string | null) => void;+}) {+ const t = useTranslations('contentEditor.editor.beforePublish');+ const tQuality = useTranslations('contentEditor.editor.quality');+ const tAuthor = useTranslations('contentEditor.editor.author');+ const markRef = useRef<HTMLButtonElement>(null);+ // Fix first moves on to the passage: focus isn't sent back to Mark ready.+ const fixing = useRef(false);+ const { author, brandName, siteTrust } = quality;+ // E-E-A-T is read with the authors: until then, who the page is by isn't known.+ const authorsRead = quality.eeat !== null;+ const trust = quality.trust?.score ?? null;+ const below = trust !== null && trust < TRUST_GATE;+ // The biggest of what would raise Trust: the warning's reason.+ const [fix] = below+ ? trustSuggestions(tQuality, quality.trust)+ .filter((s) => s.gain > 0)+ .sort((a, b) => b.gain - a.gain)+ : [];+ const article = isArticlePage(pageType);+ const jsonLd = article+ ? jsonLdScript(+ articleJsonLd({+ title,+ author: authorsRead ? author : undefined,+ authorUrl:+ (author &&+ siteTrust?.checks.authorPages.authors.find((a) => a.name === author.name)?.url) ||+ null,+ brandName,+ brandUrl: siteTrust?.checks.organizationSchema.url ?? null,+ image,+ isNew,+ today: localDate(new Date()),+ }),+ )+ : null;+ const rows: { state: RowState; title: string; detail: string }[] = [+ !authorsRead+ ? { state: 'check', title: t('author.ok'), detail: t('author.unknown') }+ : author+ ? {+ state: 'check',+ title: t('author.ok'),+ detail: t('author.okDetail', { name: author.name }),+ }+ : {+ state: 'missing',+ title: t('author.none'),+ detail: t('author.noneDetail', {+ byline: tAuthor('organization', { brand: brandName }),+ }),+ },+ ...(article+ ? [+ { state: 'check' as const, title: t('dates.title'), detail: t('dates.detail') },+ isNew+ ? { state: 'check' as const, title: t('schema.title'), detail: t('schema.detail') }+ : {+ state: 'check' as const,+ title: t('schema.titleLive'),+ detail: t('schema.detailLive'),+ },+ ]+ : [{ state: 'check' as const, title: t('schema.other'), detail: t('schema.otherDetail') }]),+ ];++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent+ className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-lg"+ initialFocus={markRef}+ finalFocus={() => !fixing.current}+ >+ <DialogHeader>+ <DialogTitle>{t('title')}</DialogTitle>+ </DialogHeader>+ {below && (+ <div+ role="alert"+ className="flex items-start gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-2.5 text-sm text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300"+ >+ <AlertTriangle aria-hidden className="mt-0.5 h-4 w-4 shrink-0" />+ <div className="min-w-0 space-y-1">+ <p>+ {fix+ ? t('warning', {+ trust,+ reason: fix.line,+ count: fix.count,+ raised: trust + fix.gain,+ })+ : t('warningNoReason', { trust })}+ </p>+ <p className="text-xs opacity-80">{t('logged')}</p>+ </div>+ </div>+ )}+ {linksPending > 0 && (+ <p role="status" className="text-xs text-muted-foreground">+ {t('linksPending', { count: linksPending })}+ </p>+ )}+ <ul className="divide-y rounded-xl border text-sm">+ {rows.map((row) => (+ <li key={row.title} className="flex items-start gap-2.5 px-3 py-2.5">+ <span+ aria-hidden+ className={cn(+ 'mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold',+ row.state === 'missing'+ ? 'bg-amber-100 text-amber-700 dark:bg-amber-950 dark:text-amber-300'+ : 'bg-muted text-muted-foreground',+ )}+ >+ {row.state === 'missing' ? '!' : '?'}+ </span>+ <div className="min-w-0 flex-1">+ <p className="font-medium">+ {row.title}+ <span className="sr-only">+ {' · '}+ {t(`states.${row.state}`)}+ </span>+ </p>+ <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">+ {row.detail}+ </p>+ </div>+ </li>+ ))}+ </ul>+ {jsonLd && (+ <div className="space-y-1.5">+ <pre+ aria-label={t('jsonLd')}+ tabIndex={0}+ className="max-h-48 overflow-auto rounded-xl border bg-muted/40 px-3 py-2.5 font-mono text-[11.5px] leading-relaxed whitespace-pre-wrap [overflow-wrap:anywhere]"+ >+ {jsonLd}+ </pre>+ {titleHasPlaceholder(title) && (+ <p className="text-xs text-amber-700 dark:text-amber-300">{t('headlineLeftOut')}</p>+ )}+ <p className="text-xs text-muted-foreground">{t('datesNote')}</p>+ </div>+ )}+ <DialogFooter className="gap-2 sm:justify-between">+ {jsonLd ? (+ <Button+ variant="outline"+ onClick={() => void copyToClipboard(jsonLd, t('copied'), t('copyFailed'))}+ >+ {t('copy')}+ </Button>+ ) : (+ <span />+ )}+ <div className="flex flex-wrap justify-end gap-2">+ {below && (+ <Button+ variant="outline"+ onClick={() => {+ fixing.current = true;+ onFixFirst(fix?.show ?? null);+ }}+ >+ {t('fixFirst')}+ </Button>+ )}+ <Button+ ref={markRef}+ onClick={() =>+ onMarkReady(+ below ? { trust, reason: fix?.check ?? null, count: fix?.count ?? null } : null,+ )+ }+ >+ {below ? t('markReadyAnyway') : t('markReady')}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 907ba3433..30a6385d9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -74,6 +74,7 @@ import {} from '@/lib/content/clean-html';import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/content/editor';import { JsonLd } from '@/lib/content/json-ld-node';+import { firstImage } from '@/lib/content/page-schema';import { detectPageType } from '@/lib/content/page-types';import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';import { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';@@ -86,6 +87,7 @@ import { useBrandStore } from '@/stores/use-brand-store';import { AgentCard } from './_agent-card';import { AgentDrafting, draftingKey } from './_agent-drafting';import { AuthorMenu } from './_author-menu';+import { BeforePublish, type ReadyAnyway } from './_before-publish';import { FlashBlock, findBlock, flashKey } from './_flash-block';import { useAgentRun } from './_use-agent-run';import { useLinkChecks } from './_use-link-checks';@@ -458,7 +460,12 @@ export function DraftEditor({[qualityOn, authorsRead, pageAuthor],);const pageBlocks = useMemo(() => (qualityOn ? trustBlocks(pageHtml) : []), [qualityOn, pageHtml]);- const linkChecks = useLinkChecks(draft.id, autosave.savedAt, linksToCheck(pageBlocks), qualityOn);+ const { checks: linkChecks, pending: linksPending } = useLinkChecks(+ draft.id,+ autosave.savedAt,+ linksToCheck(pageBlocks),+ qualityOn,+ );const brandDomains = reads.sources?.data?.brandDomains;// The site's trust (Site Audit, CE-043), read once: Trust's last 5 points.const [siteTrust, setSiteTrust] = useState<SiteTrust | null>(null);@@ -903,10 +910,17 @@ export function DraftEditor({* Quality's Show: the block of the page holding the passage (never a* suggestion's card), scrolled to and marked for a moment.*/- const showInPage = (text: string) => {+ const showInPage = (text: string, { focus = false } = {}) => {if (!editor) return;const at = findBlock(editor.state.doc, text);if (!at) return;+ // The caret at the passage, to fix it there (Before you publish's Fix first).+ if (focus)+ editor+ .chain()+ .setTextSelection(at.from + 1)+ .focus(undefined, { scrollIntoView: false })+ .run();(editor.view.nodeDOM(at.from) as HTMLElement | null)?.scrollIntoView({block: 'center',behavior: 'smooth',@@ -1380,9 +1394,15 @@ export function DraftEditor({: null,}: undefined;- const markReady = async () => {- // Opened with to-dos open: the nudge names the first; marking goes on.+ // Before you publish (CE-041) opens on Mark ready once Quality is live,+ // with the nudge to the first open to-do behind it.+ const [publishOpen, setPublishOpen] = useState(false);+ const openBeforePublish = () => {+ setPublishOpen(true);nudgeAt('markReady');+ };+ /** Marks it ready; past Before you publish's warning, logged with its facts. */+ const markReady = async (anyway?: ReadyAnyway) => {setMarking(true);try {// What's waiting goes out first, so the ready draft (and the version@@ -1394,7 +1414,9 @@ export function DraftEditor({toast.error(t('markReadyUnsaved'));return;}- const next = await markContentDraftReady(draft.id);+ const next = await (anyway+ ? markContentDraftReady(draft.id, anyway)+ : markContentDraftReady(draft.id));setStatus(next.status);toast.success(next.tasksDone > 0 && draft.action@@ -1508,7 +1530,7 @@ export function DraftEditor({autosave.state === 'conflict' ||autosave.state === 'too_large'}- onClick={markReady}+ onClick={() => (quality ? openBeforePublish() : void markReady())}>{marking ? <LoadingDots /> : !canMarkReady && <Check className="h-3.5 w-3.5" />}{t('markReady')}@@ -1776,6 +1798,27 @@ export function DraftEditor({)}</div>+ {quality && publishOpen && (+ <BeforePublish+ onClose={() => setPublishOpen(false)}+ quality={quality}+ title={title}+ isNew={draft.method === 'create'}+ pageType={pageType}+ image={firstImage(pageHtml)}+ linksPending={linksPending}+ onMarkReady={(anyway) => {+ setPublishOpen(false);+ void markReady(anyway ?? undefined);+ }}+ onFixFirst={(show) => {+ setPublishOpen(false);+ openPanelTab('quality');+ if (show) showInPage(show, { focus: true });+ }}+ />+ )}+<Dialog open={held !== null} onOpenChange={(open) => !open && setHeld(null)}><DialogContent className="max-w-md"><DialogHeader>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsxindex 285573047..ac5931127 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx@@ -12,6 +12,7 @@ import {trustGain,type EeatCheckId,type Score,+ type TrustCheckId,type TrustRead,} from '@/lib/content/quality-checks';import type { QualityTodo } from '@/lib/content/quality-todos';@@ -48,7 +49,7 @@ export interface QualityRead {type ScoreName = 'eeat' | 'trust' | 'readability';-interface Suggestion {+export interface Suggestion {key: string;// E-E-A-T's are the person's to-dos.score: Exclude<ScoreName, 'eeat'>;@@ -351,20 +352,25 @@ function readabilitySuggestions(t: T, readability: Readability | null): Suggesti);}+/** A Trust suggestion: its check, and how many it names (Before you publish's warning). */+export type TrustSuggestion = Suggestion & { check: TrustCheckId; count: number };+/*** Trust's: figures without a source, sources past FRESH_MONTHS, links that* don't answer, each with Show on the first one in the page. A broken link* is listed before Trust is scored too, its gain out of the Phase 1 points.*/-function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {+export function trustSuggestions(t: T, trust: TrustRead | null): TrustSuggestion[] {if (!trust) return [];- const out: Suggestion[] = [];+ const out: TrustSuggestion[] = [];if (trust.unsourced.length) {out.push({key: 'trust:claimsSourced',+ check: 'claimsSourced',score: 'trust',gain: trustGain(trust, ['claimsSourced']),line: t('checks.claimsSourced.line', { count: trust.unsourced.length }),+ count: trust.unsourced.length,detail: t('checks.claimsSourced.detail'),show: trust.unsourced[0],});@@ -372,8 +378,10 @@ function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {if (trust.stale.length) {out.push({key: 'trust:freshSources',+ check: 'freshSources',score: 'trust',gain: trustGain(trust, ['freshSources']),+ count: trust.stale.length,line: t('checks.freshSources.line', {count: trust.stale.length,total: trust.dated,@@ -386,9 +394,11 @@ function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {if (trust.broken.length) {out.push({key: 'trust:noBrokenLinks',+ check: 'noBrokenLinks',score: 'trust',gain: trustGain(trust, ['noBrokenLinks']),line: t('checks.noBrokenLinks.line', { count: trust.broken.length }),+ count: trust.broken.length,detail: t('checks.noBrokenLinks.detail', {count: trust.broken.length,url: trust.broken[0].url,diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsxindex b61cd26f1..31cfba60e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsx@@ -35,8 +35,8 @@ function Probe({savedAt: string;enabled: boolean;}) {- const checks = useLinkChecks('d1', savedAt, hrefs, enabled);- return <pre data-checks={JSON.stringify([...checks])} />;+ const { checks, pending } = useLinkChecks('d1', savedAt, hrefs, enabled);+ return <pre data-checks={JSON.stringify([...checks])} data-pending={pending} />;}/** The reads the hook holds, by link. */@@ -45,6 +45,9 @@ const seen = () =>JSON.parse(container.querySelector('pre')?.getAttribute('data-checks') ?? '[]'),);+/** How many links' reads may still come. */+const pending = () => Number(container.querySelector('pre')?.getAttribute('data-pending'));+const render = (hrefs: string[], savedAt = 's1', enabled = true) =>act(async () => root.render(<Probe hrefs={hrefs} savedAt={savedAt} enabled={enabled} />));const wait = (ms = LINK_CHECK_DELAY_MS) => act(async () => vi.advanceTimersByTimeAsync(ms));@@ -69,10 +72,12 @@ describe('useLinkChecks', () => {await render(['https://a.example/']);await wait(LINK_CHECK_DELAY_MS - 100);await render(['https://a.example/', 'https://b.example/']);+ expect(pending()).toBe(2);await wait();expect(checkDraftLinks).toHaveBeenCalledTimes(1);expect(checkDraftLinks).toHaveBeenCalledWith('d1');expect([...seen().keys()]).toEqual(['https://a.example/', 'https://b.example/']);+ expect(pending()).toBe(0);// Nothing new to read: no ask.await render(['https://a.example/', 'https://b.example/'], 's2');@@ -85,6 +90,8 @@ describe('useLinkChecks', () => {await render(['https://a.example/', 'https://new.example/']);await wait();expect(seen().has('https://new.example/')).toBe(false);+ // Its read comes after the next save.+ expect(pending()).toBe(1);// Same save: not asked again.await render(['https://a.example/', 'https://new.example/', 'https://a.example/']);@@ -102,9 +109,12 @@ describe('useLinkChecks', () => {checkDraftLinks.mockResolvedValue({ error: 'failed' });vi.spyOn(console, 'error').mockImplementation(() => {});await render(['https://a.example/']);+ expect(pending()).toBe(1);await wait(LINK_CHECK_DELAY_MS * 3);expect(checkDraftLinks).toHaveBeenCalledTimes(1);expect(seen().size).toBe(0);+ // No read is coming in this save.+ expect(pending()).toBe(0);await render(['https://d.example/'], 's1', false);await wait();@@ -118,5 +128,6 @@ describe('useLinkChecks', () => {await render(['https://a.example/unsubscribe'], 's2');await wait();expect(checkDraftLinks).toHaveBeenCalledTimes(1);+ expect(pending()).toBe(0);});});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.tsindex 969d796c5..29408af98 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.ts@@ -15,7 +15,10 @@ export const LINK_CHECK_DELAY_MS = 3_000;* link the API leaves out, one over its budget, a failed ask) is asked about* again only after the next save: until then the checks it would feed leave* it out. One the API never reads (an account link) isn't asked about again.- * The links are compared as the draft saves them (cleanHref).+ * The links are compared as the draft saves them (cleanHref). `pending`+ * counts the links whose read may still come (Before you publish says+ * Trust may change): not read, not one the API never reads, and not asked+ * about at this save without an answer.** @param hrefs the page's http(s) links now, as it has them* @param savedAt when the page was last saved@@ -25,8 +28,11 @@ export function useLinkChecks(savedAt: string,hrefs: string[],enabled: boolean,-): Map<string, LinkCheck> {+): { checks: Map<string, LinkCheck>; pending: number } {const [checks, setChecks] = useState<Map<string, LinkCheck>>(() => new Map());+ // Links the API never reads, and the save each link's ask failed at.+ const [skipped, setSkipped] = useState<ReadonlySet<string>>(() => new Set());+ const [failedAt, setFailedAt] = useState<ReadonlyMap<string, string>>(() => new Map());// The links read, and the save each other link was last asked about at.const read = useRef(new Set<string>());const askedAt = useRef(new Map<string, string>());@@ -51,9 +57,13 @@ export function useLinkChecks(void checkDraftLinks(draftId).then((result) => {if ('error' in result) {console.error('Failed to check the draft links:', result.error);+ if (open.current) {+ setFailedAt((prev) => new Map([...prev, ...fresh.map((h) => [h, savedAt] as const)]));+ }return;}if (!open.current) return;+ if (result.skipped.length) setSkipped((prev) => new Set([...prev, ...result.skipped]));// A link the API never reads is as good as read: it isn't asked about again.for (const href of [...result.links.map((l) => l.href), ...result.skipped]) {read.current.add(href);@@ -68,5 +78,10 @@ export function useLinkChecks(return () => clearTimeout(timer);}, [draftId, savedAt, key, enabled]);- return checks;+ const pending = enabled+ ? hrefs.filter(+ (href) => href && !checks.has(href) && !skipped.has(href) && failedAt.get(href) !== savedAt,+ ).length+ : 0;+ return { checks, pending };}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex 0835a5f35..5c3b175ea 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -2438,6 +2438,10 @@ describe('the side panel', () => {delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;});const nudge = () => container.querySelector('[aria-label="Your next step"]');+ const inDialog = (name: string) =>+ [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')].find(+ (b) => b.textContent === name,+ )!;it('names the first to-do once the agent has written the page, and opens the author menu', async () => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });@@ -2597,7 +2601,7 @@ describe('the side panel', () => {expect(nudge()).toBeNull();});- it('names it after Accept all, and on Mark ready while marking goes on; Later hides it', async () => {+ it('names it after Accept all, and behind Before you publish on Mark ready; Later hides it', async () => {getContentDraft.mockResolvedValue(draft({authorId: 'a1',@@ -2632,10 +2636,11 @@ describe('the side panel', () => {await act(async () => button('Later')!.click());expect(nudge()).toBeNull();- // Later holds for the session: Mark ready marks, with no nudge.+ // Later holds for the session: Mark ready opens Before you publish, with no nudge.await act(async () => button('Mark ready')!.click());- expect(markContentDraftReady).toHaveBeenCalledWith('d1');expect(nudge()).toBeNull();+ await act(async () => inDialog('Mark ready').click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');});it('names it on Mark ready with a to-do open', async () => {@@ -2643,8 +2648,106 @@ describe('the side panel', () => {markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 0 });await renderPage();await act(async () => button('Mark ready')!.click());- expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ expect(document.querySelector('[role="dialog"]')!.textContent).toContain(+ 'Before you publish',+ );expect(nudge()!.textContent).toContain("Next for you: pick the page's author");+ await act(async () => inDialog('Mark ready').click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ });+ });++ describe('Before you publish (CE-041)', () => {+ beforeEach(() => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 0 });+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'analyst' },+ });+ getDraftSources.mockResolvedValue({+ data: {+ prompts: [],+ fanouts: [],+ citedPages: [],+ gscQueries: [],+ brandDomains: ['acme.example.com'],+ competitorDomains: [],+ },+ choices: [],+ });+ });+ afterEach(() => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ });+ const dialogText = () => document.querySelector('[role="dialog"]')?.textContent ?? null;+ const inDialog = (name: string) =>+ [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] button')].find(+ (b) => b.textContent === name,+ );++ it('opens on Mark ready with what the CMS does and the JSON-LD, then marks it ready', async () => {+ getContentDraft.mockResolvedValue(draft({ authorId: null, pageType: 'blog_post' }));+ await renderPage();+ await act(async () => button('Mark ready')!.click());+ expect(markContentDraftReady).not.toHaveBeenCalled();+ expect(dialogText()).toContain('No author yet');+ expect(dialogText()).toContain('"@type": "Article"');+ expect(dialogText()).toContain('"headline": "Pipeline forecasting"');+ // No figure or link to read: Trust isn't scored, so nothing warns.+ expect(document.querySelector('[role="dialog"] [role="alert"]')).toBeNull();+ await act(async () => inDialog('Mark ready')!.click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');+ expect(dialogText()).toBeNull();+ });++ it('warns under Trust 60, and logs Mark ready anyway with the Trust and the check it named', async () => {+ getContentDraft.mockResolvedValue(+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Deals close $2.5 million faster.</p>' }),+ );+ await renderPage();+ await act(async () => button('Mark ready')!.click());+ expect(document.querySelector('[role="dialog"] [role="alert"]')!.textContent).toContain(+ 'Trust 0, below 60. 1 sentence with a figure has no source. You can mark it ready, but fixing it first raises Trust to about 100.',+ );+ await act(async () => inDialog('Mark ready anyway')!.click());+ expect(markContentDraftReady).toHaveBeenCalledWith('d1', {+ trust: 0,+ reason: 'claimsSourced',+ count: 1,+ });+ });++ it('goes to Quality on Fix first, without marking it ready', async () => {+ getContentDraft.mockResolvedValue(+ draft({ bodyHtml: '<h1>Pipeline forecasting</h1><p>Deals close $2.5 million faster.</p>' }),+ );+ window.innerWidth = 1440;+ await renderPage();+ await act(async () => button('Mark ready')!.click());+ const scrolled = vi.fn();+ const original = Element.prototype.scrollIntoView;+ Element.prototype.scrollIntoView = scrolled;+ try {+ await act(async () => inDialog('Fix first')!.click());+ } finally {+ Element.prototype.scrollIntoView = original;+ }+ expect(dialogText()).toBeNull();+ expect(markContentDraftReady).not.toHaveBeenCalled();+ expect(selectedSegment()).toMatch(/^Quality/);+ // The passage the warning names first.+ expect(scrolled).toHaveBeenCalled();+ });++ it('marks it ready at once while Quality is off', async () => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ getContentDraft.mockResolvedValue(draft());+ await renderPage();+ await act(async () => button('Mark ready')!.click());+ expect(dialogText()).toBeNull();+ expect(markContentDraftReady).toHaveBeenCalledWith('d1');});});diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex e365b9b9c..abec0a2b3 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -411,6 +411,32 @@ describe('markContentDraftReady', () => {expect(rpcCalls).toEqual([]);});+ it('logs Mark ready anyway with the Trust the page had and the check it named (CE-041)', async () => {+ updated = { status: 'ready' };+ await markContentDraftReady(DRAFT, { trust: 55, reason: 'claimsSourced', count: 3 });+ expect(calls[1]).toMatchObject({+ op: 'insert',+ value: { draft_id: DRAFT, trust: 55, reason: 'claimsSourced', reason_count: 3 },+ });++ // Not when nothing became ready, nor for a plain Mark ready.+ calls = [];+ updated = null;+ row = { id: DRAFT, brand_id: 'b1', status: 'ready', author: 'user' };+ await markContentDraftReady(DRAFT, { trust: 55, reason: null, count: null });+ updated = { status: 'ready' };+ await markContentDraftReady(DRAFT);+ expect(calls.filter((c) => c.op === 'insert')).toEqual([]);++ // Only a Trust and a check's id go in.+ await expect(+ markContentDraftReady(DRAFT, { trust: 140, reason: null, count: null }),+ ).rejects.toThrow('invalid');+ await expect(+ markContentDraftReady(DRAFT, { trust: 40, reason: '3 sentences', count: 3 }),+ ).rejects.toThrow('invalid');+ });+it('is ready even when History couldn’t keep the version', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {});updated = { status: 'ready' };diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 4f7022053..dedbc3aab 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -1283,17 +1283,32 @@ export async function deleteContentDraft(id: string): Promise<void> {if (!data?.length) throw new Error('forbidden');}+const readyAnyway = z.object({+ trust: z.number().int().min(0).max(100),+ // The check the warning named (claimsSourced…) and how many it counted.+ reason: z+ .string()+ .regex(/^[A-Za-z]{1,40}$/)+ .nullable(),+ count: z.number().int().min(0).nullable(),+});+/*** Mark ready: a draft, or an agent's draft in review, is ready to publish.* Ansvisor never publishes it; the person does (CE-013 records the URL).* Returns the status the draft has after, so a draft already ready or* published keeps its own, and how many of its action's tasks it completed- * (CE-022; completeDraftTasks).+ * (CE-022; completeDraftTasks). Marked ready past Before you publish's+ * warning (CE-041), it is logged with the Trust the page had and the check+ * the warning named (00260 content_draft_ready_log).*/export async function markContentDraftReady(id: string,+ anyway?: { trust: number; reason: string | null; count: number | null },): Promise<{ status: DraftStatus; tasksDone: number }> {if (!draftId.safeParse(id).success) throw new Error('invalid');+ const logged = anyway === undefined ? null : readyAnyway.safeParse(anyway);+ if (logged && !logged.success) throw new Error('invalid');const supabase = await createClient();const { data, error } = await supabase.from('content_drafts')@@ -1305,6 +1320,16 @@ export async function markContentDraftReady(if (error) throw new Error(error.message);if (data) {await keepVersion(supabase, id, 'ready');+ if (logged) {+ // The draft is ready either way; a log that didn't go in is reported.+ const { error: logError } = await supabase.from('content_draft_ready_log').insert({+ draft_id: id,+ trust: logged.data.trust,+ reason: logged.data.reason,+ reason_count: logged.data.count,+ });+ if (logError) console.error('Failed to log Mark ready anyway:', logError.message);+ }let tasksDone = 0;if (data.action_id) {const {diff --git a/web/src/lib/content/page-schema.test.ts b/web/src/lib/content/page-schema.test.tsnew file mode 100644index 000000000..186b52627--- /dev/null+++ b/web/src/lib/content/page-schema.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest';+import type { ContentAuthor } from './authors';+import {+ articleJsonLd,+ firstImage,+ isArticlePage,+ jsonLdScript,+ localDate,+ titleHasPlaceholder,+} from './page-schema';++/** Before you publish's JSON-LD (Quality spec §7, CE-041): from the page's facts, nothing made up. */++const ada: ContentAuthor = {+ id: 'a1',+ name: 'Ada Lovelace',+ title: 'Head of Content',+ bio: 'Writes about forecasting.',+ photoUrl: 'https://cdn.acme.com/ada.jpg',+ sameAs: ['https://www.linkedin.com/in/ada'],+ userId: null,+ createdBy: null,+ defaultFor: [],+ pages: null,+};+const base = {+ title: 'How small teams forecast pipeline',+ author: ada,+ authorUrl: 'https://acme.com/authors/ada-lovelace',+ brandName: 'Acme',+ brandUrl: 'https://acme.com/',+ image: 'https://cdn.acme.com/pour-over.jpg',+ isNew: true,+ today: '2026-10-23',+};++describe('articleJsonLd', () => {+ it('gives an Article by the person, with their profile, published and updated today', () => {+ expect(articleJsonLd(base)).toEqual({+ '@context': 'https://schema.org',+ '@type': 'Article',+ headline: 'How small teams forecast pipeline',+ image: 'https://cdn.acme.com/pour-over.jpg',+ author: {+ '@type': 'Person',+ name: 'Ada Lovelace',+ jobTitle: 'Head of Content',+ url: 'https://acme.com/authors/ada-lovelace',+ image: 'https://cdn.acme.com/ada.jpg',+ sameAs: ['https://www.linkedin.com/in/ada'],+ },+ publisher: { '@type': 'Organization', name: 'Acme', url: 'https://acme.com/' },+ datePublished: '2026-10-23',+ dateModified: '2026-10-23',+ });+ });++ it("gives the brand's Organization for the team byline, and leaves out what isn't known", () => {+ const result = articleJsonLd({+ ...base,+ author: null,+ brandUrl: null,+ image: null,+ title: ' ',+ });+ expect(result).toEqual({+ '@context': 'https://schema.org',+ '@type': 'Article',+ author: { '@type': 'Organization', name: 'Acme' },+ publisher: { '@type': 'Organization', name: 'Acme' },+ datePublished: '2026-10-23',+ dateModified: '2026-10-23',+ });+ const bare = articleJsonLd({+ ...base,+ author: { ...ada, title: null, photoUrl: null, sameAs: [] },+ authorUrl: null,+ });+ expect(bare.author).toEqual({ '@type': 'Person', name: 'Ada Lovelace' });+ });++ it("leaves the author out while the authors aren't read", () => {+ expect(articleJsonLd({ ...base, author: undefined })).not.toHaveProperty('author');+ });++ it('leaves the headline out while the title has a placeholder', () => {+ const result = articleJsonLd({ ...base, title: 'Forecasting with [figure, source] accuracy' });+ expect(result).not.toHaveProperty('headline');+ expect(result.author).toMatchObject({ name: 'Ada Lovelace' });+ // A footnote, a checkbox or "[sic]" is no placeholder.+ expect(titleHasPlaceholder('Pipeline [1] and [x] [sic]')).toBe(false);+ expect(titleHasPlaceholder('Interview with [name of a real person]')).toBe(true);+ // The match keeps no state between titles.+ expect(titleHasPlaceholder('Interview with [name of a real person]')).toBe(true);+ });++ it('keeps the published date a live page has: only the updated date', () => {+ const result = articleJsonLd({ ...base, isNew: false });+ expect(result).not.toHaveProperty('datePublished');+ expect(result.dateModified).toBe('2026-10-23');+ });+});++describe('jsonLdScript', () => {+ it("wraps it to paste, so a title can't close the tag", () => {+ const script = jsonLdScript(articleJsonLd({ ...base, title: 'Tags </script> in titles' }));+ expect(script.startsWith('<script type="application/ld+json">\n{')).toBe(true);+ expect(script.endsWith('}\n</script>')).toBe(true);+ expect(script.match(/<\/script>/g)).toHaveLength(1);+ expect(JSON.parse(script.slice(36, -10)).headline).toBe('Tags </script> in titles');+ });+});++describe('firstImage', () => {+ it("takes the page's first image with a full https address", () => {+ expect(+ firstImage(+ '<p><img src="/local.png"><img src="data:image/png;base64,AA"></p>' ++ '<img src="https://cdn.acme.com/a.jpg"><img src="https://cdn.acme.com/b.jpg">',+ ),+ ).toBe('https://cdn.acme.com/a.jpg');+ expect(firstImage('<p>No images.</p>')).toBeNull();+ });+});++describe('isArticlePage', () => {+ it('reads articles, and a page with no type yet, as one', () => {+ expect(isArticlePage('blog_post')).toBe(true);+ expect(isArticlePage(null)).toBe(true);+ expect(isArticlePage('product_page')).toBe(false);+ expect(isArticlePage('pricing')).toBe(false);+ });+});++describe('localDate', () => {+ it('gives the local day', () => {+ expect(localDate(new Date(2026, 0, 5, 23, 30))).toBe('2026-01-05');+ });+});diff --git a/web/src/lib/content/page-schema.ts b/web/src/lib/content/page-schema.tsnew file mode 100644index 000000000..9245cb44c--- /dev/null+++ b/web/src/lib/content/page-schema.ts@@ -0,0 +1,122 @@+import type { ContentAuthor } from './authors';+import type { PageType } from './drafts';++/**+ * The page's JSON-LD for Before you publish (Content Editor Quality spec §7,+ * CE-041): an Article from its title, author, brand and dates, for the+ * person to paste when their CMS doesn't write one. A person byline brings+ * their Person schema (sameAs from their profile links); the organization+ * byline, the brand's Organization. Nothing in it is made up: what isn't+ * known is left out.+ */++/**+ * The page types an Article describes. Others (a product, a pricing or a+ * category page…) take their own schema, a page-type item for later (§11).+ * A page with no type yet reads as one.+ */+export const ARTICLE_PAGE_TYPES: readonly PageType[] = [+ 'blog_post',+ 'guide',+ 'comparison',+ 'buying_guide',+ 'best_of',+ 'definition',+ 'alternatives',+ 'itinerary',+];++export const isArticlePage = (type: string | null) =>+ type === null || (ARTICLE_PAGE_TYPES as readonly string[]).includes(type);++/**+ * Words in square brackets where a real name, quote or number goes ("[figure,+ * source]"): a placeholder the Content Agent left for the person to fill, as+ * the editor's placeholder to-do reads it (CE-044). Not a footnote ("[1]"),+ * a checkbox ("[x]"), "[sic]" or a Markdown link's text.+ */+const PLACEHOLDER = /\[(?!sic\])(?=[^[\]\n]*\p{L})[^[\]\n]{2,}\](?!\()/iu;++/** Whether the title still has a placeholder: it would ship as the headline. */+export const titleHasPlaceholder = (title: string) => PLACEHOLDER.test(title);++/** The page's first image with a full https address, as JSON-LD's image. */+export function firstImage(html: string): string | null {+ const doc = new DOMParser().parseFromString(html, 'text/html');+ for (const img of doc.querySelectorAll('img[src]')) {+ const src = img.getAttribute('src') ?? '';+ if (/^https:\/\/[^\s"'<>]+$/i.test(src)) return src;+ }+ return null;+}++export interface ArticleSchemaInput {+ title: string;+ /** The page's author; undefined while the authors aren't read (it is left out). */+ author: ContentAuthor | null | undefined;+ /** The author's page on the brand's site (Site trust), if one was found. */+ authorUrl: string | null;+ brandName: string;+ /** The brand's home page as Site trust read it, if it did. */+ brandUrl: string | null;+ /** The page's own image (firstImage), if it has one. */+ image: string | null;+ /**+ * A new page is published with this version; a page already live keeps+ * the published date it has, so only the updated date is given.+ */+ isNew: boolean;+ /** The local date, YYYY-MM-DD (localDate). */+ today: string;+}++/** A date as JSON-LD gives it here: YYYY-MM-DD, in the person's time zone. */+export function localDate(now: Date): string {+ const pad = (n: number) => String(n).padStart(2, '0');+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;+}++export function articleJsonLd({+ title,+ author,+ authorUrl,+ brandName,+ brandUrl,+ image,+ isNew,+ today,+}: ArticleSchemaInput): Record<string, unknown> {+ const organization = {+ '@type': 'Organization',+ name: brandName,+ ...(brandUrl ? { url: brandUrl } : {}),+ };+ const person = author && {+ '@type': 'Person',+ name: author.name,+ ...(author.title ? { jobTitle: author.title } : {}),+ ...(authorUrl ? { url: authorUrl } : {}),+ ...(author.photoUrl ? { image: author.photoUrl } : {}),+ ...(author.sameAs.length ? { sameAs: author.sameAs } : {}),+ };+ return {+ '@context': 'https://schema.org',+ '@type': 'Article',+ // A placeholder isn't the page's headline: it is left out until filled.+ ...(title.trim() && !titleHasPlaceholder(title) ? { headline: title.trim() } : {}),+ ...(image ? { image } : {}),+ ...(author !== undefined ? { author: person ?? organization } : {}),+ publisher: organization,+ ...(isNew ? { datePublished: today } : {}),+ dateModified: today,+ };+}++/**+ * The JSON-LD as a script tag to paste into the page. A "<" in it is+ * escaped, so a title can't close the tag.+ */+export function jsonLdScript(data: Record<string, unknown>): string {+ const json = JSON.stringify(data, null, 2).replace(/</g, '\\u003c');+ return `<script type="application/ld+json">\n${json}\n</script>`;+}diff --git a/web/src/lib/content/quality-checks.ts b/web/src/lib/content/quality-checks.tsindex f45eabeda..43754b044 100644--- a/web/src/lib/content/quality-checks.ts+++ b/web/src/lib/content/quality-checks.ts@@ -113,9 +113,9 @@ export function authorProfile(author: ContentAuthor | null): { bio: boolean; lin/*** E-E-A-T from the page's author (CE-038): a real person, with a short bio* and profile links. The organization byline is no person. Author schema- * joins when Before you publish writes the page's JSON-LD (CE-041), dates- * when the live page is read (CE-042); experience, data, proof and- * who/how/why are Phase 2.+ * and dates join when the live page is read (CE-042): the JSON-LD Before you+ * publish gives counts only once the page has it. Experience, data, proof+ * and who/how/why are Phase 2.*/export function eeat({ author }: { author: ContentAuthor | null }): Score<EeatCheckId> {const { bio, links } = authorProfile(author);diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 7f4fbdfd9..2561d21a9 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1226,6 +1226,51 @@ export type Database = {},]}+ content_draft_ready_log: {+ Row: {+ created_at: string+ created_by: string | null+ draft_id: string+ id: string+ reason: string | null+ reason_count: number | null+ trust: number+ }+ Insert: {+ created_at?: string+ created_by?: string | null+ draft_id: string+ id?: string+ reason?: string | null+ reason_count?: number | null+ trust: number+ }+ Update: {+ created_at?: string+ created_by?: string | null+ draft_id?: string+ id?: string+ reason?: string | null+ reason_count?: number | null+ trust?: number+ }+ Relationships: [+ {+ foreignKeyName: "content_draft_ready_log_created_by_fkey"+ columns: ["created_by"]+ isOneToOne: false+ referencedRelation: "profiles"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "content_draft_ready_log_draft_id_fkey"+ columns: ["draft_id"]+ isOneToOne: false+ referencedRelation: "content_drafts"+ referencedColumns: ["id"]+ },+ ]+ }content_draft_sources: {Row: {added: boolean