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): hand a draft's open Quality checks to the Content Agent in one run (00275, CE-051, part 1) (#1481)

Cihan86140d819cb9
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.js
index dee15c888..f604bb668 100644
--- a/server/src/lib/content-agent.js
+++ b/server/src/lib/content-agent.js
@@ -12,7 +12,9 @@ import { authorWords, guardPeopleInHtml, knownPeople } from './content-people.js
import {
RunStoppedError,
advanceRun,
+ dropRun,
finishRun,
+ fixUnderWay,
isStop,
runCall,
startRun,
@@ -33,7 +35,7 @@ import {
todayText,
} from './content-sources.js';
import { getLanguageName } from './languages.js';
-import { reserveAiBudget } from './plan-guard.js';
+import { PlanLimitError, reserveAiBudget } from './plan-guard.js';
/**
* Fix open rules with agent (Content Editor CE-018, spec §8): the Content
@@ -381,6 +383,8 @@ export function splitReplace(after, tag, links = null) {
*/
export function keepSuggestions(raw, passages, lockedKeys, ruleKeys, links = null, sourcing = {}) {
const numbered = sourcing.numbered ?? [];
+ // Quality's hand-off (CE-051): a placeholder is the person's to fill.
+ const keepsPlaceholders = sourcing.keepPlaceholders === true;
const known = sourcing.known ?? knownNumbers(...passages.map((p) => p.text));
const people = sourcing.people ?? knownPeople(...passages.map((p) => p.text));
const kept = [];
@@ -427,6 +431,14 @@ export function keepSuggestions(raw, passages, lockedKeys, ruleKeys, links = nul
const wordLinks = split.links.slice(0, MAX_LINKS);
// Linking words the passage already has is a change too.
const changed = words && (words !== before || wordLinks.length > 0);
+ // Read in what is kept: the passage's new words, and the blocks after it.
+ if (
+ keepsPlaceholders &&
+ changed &&
+ dropsPlaceholder(passage.text, before, `${words} ${textOf(blocks)}`, passage.tag)
+ ) {
+ continue;
+ }
if (
changed &&
(words.length > 2000 ||
@@ -507,6 +519,51 @@ export function promptPassages(passages) {
return { passages: sent, more: false };
}
+/**
+ * Words in square brackets with a letter and more than one character in
+ * them: a placeholder (CE-044), as the editor reads one (placeholders.ts).
+ */
+const PLACEHOLDER = /\[(?!sic\])(?=[^[\]\n]*\p{L})[^[\]\n]{2,}\](?!\()/giu;
+
+/**
+ * The forms the server's guards write (the number guard's "[figure,
+ * source]", content-people.js's name and quote): in a heading only these
+ * are placeholders, as the editor reads them (placeholders.ts placeholderIn);
+ * brackets a person writes in a title ("[2026 Update]") are part of it.
+ */
+const AGENT_PLACEHOLDER =
+ /\[(?:figure, source[^[\]\n]*|name of a real person|quote from a real person[^[\]\n]*)\](?!\()/giu;
+
+/** Each placeholder in the text, by how many times it is there. */
+function placeholderCounts(text, heading) {
+ const counts = new Map();
+ for (const found of text.match(heading ? AGENT_PLACEHOLDER : PLACEHOLDER) ?? []) {
+ counts.set(found, (counts.get(found) ?? 0) + 1);
+ }
+ return counts;
+}
+
+/**
+ * Whether a replace takes a placeholder out of its passage, filled or
+ * dropped: each placeholder counted before and after the change, so one of
+ * two alike ("[figure, source]" twice) counts too (a "before" may cut into
+ * one: "product name" in "[product name]").
+ */
+export function dropsPlaceholder(passage, before, after, tag = 'p') {
+ const heading = isHeading(tag);
+ const had = placeholderCounts(passage, heading);
+ if (!had.size) return false;
+ const now = placeholderCounts(
+ passage.replace(before, () => String(after ?? '')),
+ heading,
+ );
+ return [...had].some(([placeholder, count]) => (now.get(placeholder) ?? 0) < count);
+}
+
+/** Quality's hand-off (CE-051): the guard drops a fill, so the model isn't asked to make one. */
+const KEEP_PLACEHOLDERS =
+ "Leave every [placeholder] exactly as it is: the person fills it; don't change or remove one.";
+
/** What the model is told: the brand, the page's passages, and the rules to fix. */
export function buildFixPrompt({
brand,
@@ -517,6 +574,7 @@ export function buildFixPrompt({
input,
linkTargets = '',
sources = '',
+ handoff = false,
}) {
const lines = passages.map((p, i) => {
const locked = lockedKeys.has(passageKey(p.text)) ? ', LOCKED' : '';
@@ -534,7 +592,7 @@ Page type: ${pageTypeFormat(draft.page_type)}
Rules the page doesn't meet yet (key: rule — what it asks and how the page reads now):
${rules.join('\n')}
-${own.length ? `\nThe writer's own rules, to follow in every change:\n${own.join('\n')}\n` : ''}${sources ? `\n${sources}\n` : ''}${linkTargets ? `\n${linkTargets}\n` : ''}
+${handoff ? `${KEEP_PLACEHOLDERS}\n` : ''}${own.length ? `\nThe writer's own rules, to follow in every change:\n${own.join('\n')}\n` : ''}${sources ? `\n${sources}\n` : ''}${linkTargets ? `\n${linkTargets}\n` : ''}
The page, passage by passage:
${lines.join('\n')}
@@ -590,14 +648,24 @@ export function agentWriting(draft, now = Date.now()) {
* budget, asks the model, and keeps the suggestions the editor can apply as
* one new batch, linked to the draft's Action Center action if it has one.
* Throws with `.status` 404 for a draft outside the brand, 409 for a
- * published draft or one whose suggestions are still open, 422 for an empty
- * page, PlanLimitError once the budget is spent — all before charging.
+ * published draft, one whose suggestions are still open or one the agent is
+ * fixing already (`running`), 422 for an empty page, PlanLimitError once
+ * the budget is spent — all before charging.
+ *
+ * `handoff` runs it as Quality's hand-off (CE-051): a run of its own kind,
+ * by a person or the editor on its own (`origin`). The rules are the page's
+ * checks in the server's words, and what the editor sent of them (their
+ * detail) is no fact the agent may write; a placeholder stays the person's.
+ * An automatic one runs only on a draft made while its brand handed off
+ * (quality_handoff, 00275) and while it still does (409 `not_due`), once
+ * (409 `already`); one the AI budget stops
+ * before it begins is taken back, to run once the budget renews.
*/
-export async function fixDraftRules({ draftId, brandId, input }) {
+export async function fixDraftRules({ draftId, brandId, input, handoff = null }) {
const { data: draft, error: draftError } = await supabaseAdmin
.from('content_drafts')
.select(
- 'id, brand_id, title, body_html, page_type, action_id, status, source_url, agent_state, agent_state_at',
+ `id, brand_id, title, body_html, page_type, action_id, status, source_url, agent_state, agent_state_at${handoff ? ', quality_handoff' : ''}`,
)
.eq('id', draftId)
.maybeSingle();
@@ -605,6 +673,13 @@ export async function fixDraftRules({ draftId, brandId, input }) {
if (!draft || draft.brand_id !== brandId) {
throw Object.assign(new Error('Draft not found'), { status: 404 });
}
+ // An automatic hand-off on a draft its brand doesn't hand off never will be due.
+ if (handoff?.origin === 'auto' && draft.quality_handoff !== true) {
+ throw Object.assign(new Error('The brand hands off no quality fixes'), {
+ status: 409,
+ code: 'not_due',
+ });
+ }
if (draft.status === 'published') {
throw Object.assign(new Error('The draft is published'), { status: 409, code: 'published' });
}
@@ -626,23 +701,39 @@ export async function fixDraftRules({ draftId, brandId, input }) {
code: 'writing',
});
}
+ // One fix at a time on a draft (a second tab, a person's beside the auto one).
+ if (await fixUnderWay(draftId)) {
+ throw Object.assign(new Error('The agent is already fixing it'), {
+ status: 409,
+ code: 'running',
+ });
+ }
const { data: brand, error: brandError } = await supabaseAdmin
.from('brands')
.select(
- 'name, industry, description, organization_id, language, site_type, shopping_mode_enabled',
+ `name, industry, description, organization_id, language, site_type, shopping_mode_enabled${handoff ? ', content_quality_handoff' : ''}`,
)
.eq('id', brandId)
.single();
if (brandError) throw brandError;
+ // Turned off since the draft was made: its automatic hand-off doesn't run.
+ if (handoff?.origin === 'auto' && brand.content_quality_handoff !== true) {
+ throw Object.assign(new Error('The brand hands off no quality fixes'), {
+ status: 409,
+ code: 'not_due',
+ });
+ }
// Its steps, named by the work it does (CE-027/035); Stop aborts the call.
const sources = input.sources;
const run = await startRun({
draftId,
- kind: 'fix',
+ kind: handoff ? 'handoff' : 'fix',
+ origin: handoff?.origin ?? 'person',
+ strict: handoff?.origin === 'auto',
counts: {
- rules: input.rules.length,
+ [handoff ? 'checks' : 'rules']: input.rules.length,
sources: sources
? sources.promptIds.length +
sources.fanouts.length +
@@ -652,7 +743,17 @@ export async function fixDraftRules({ draftId, brandId, input }) {
},
});
try {
- const result = await fixWithRun({ draft, brand, brandId, draftId, input, passages, more, run });
+ const result = await fixWithRun({
+ draft,
+ brand,
+ brandId,
+ draftId,
+ input,
+ passages,
+ more,
+ run,
+ handoff: !!handoff,
+ });
await finishRun(run, 'done', { 2: result.count });
return result;
} catch (err) {
@@ -660,13 +761,46 @@ export async function fixDraftRules({ draftId, brandId, input }) {
await finishRun(run, 'stopped');
throw new RunStoppedError();
}
- await finishRun(run, 'failed');
+ // An automatic hand-off the budget stopped before it began: its claim goes.
+ if (handoff?.origin === 'auto' && err instanceof PlanLimitError) await dropRun(run);
+ else await finishRun(run, 'failed');
throw err;
}
}
+/** Quality's checks a hand-off fixes with a source: they link the draft's sources (CE-051). */
+const SOURCE_CHECKS = new Set([
+ 'trust:claimsSourced',
+ 'trust:freshSources',
+ 'trust:noWeakSources',
+ 'trust:primarySources',
+ 'trust:noBrokenLinks',
+]);
+
+/** The brand's approved facts still on its site (CE-047), as their words. */
+async function approvedFacts(brandId) {
+ const { data, error } = await supabaseAdmin
+ .from('brand_facts')
+ .select('quote')
+ .eq('brand_id', brandId)
+ .eq('status', 'approved')
+ .is('gone_at', null);
+ if (error) throw error;
+ return (data ?? []).map((f) => f.quote).filter(Boolean);
+}
+
/** Fix open rules' run itself, step by step: nothing is kept once it is stopped. */
-async function fixWithRun({ draft, brand, brandId, draftId, input, passages, more, run }) {
+async function fixWithRun({
+ draft,
+ brand,
+ brandId,
+ draftId,
+ input,
+ passages,
+ more,
+ run,
+ handoff = false,
+}) {
const modelId = contentBriefModelId();
const lockedKeys = new Set(input.locked.map(passageKey));
const ruleKeys = new Set(input.rules.map((r) => r.key));
@@ -684,14 +818,20 @@ async function fixWithRun({ draft, brand, brandId, draftId, input, passages, mor
queries: input.sources?.queries,
inputs: inputSources(inputRow, brand.name),
});
+ // A hand-off's details and the person's own rules are the editor's words:
+ // no fact the agent may write. The brand's approved facts are, read here.
+ const ruleWords = handoff
+ ? input.rules.map((r) => r.name)
+ : [...input.rules.flatMap((r) => [r.name, r.detail]), ...input.textRules];
+ const facts = handoff && ruleKeys.has('trust:brandFacts') ? await approvedFacts(brandId) : [];
const known = knownNumbers(
htmlText(draft.body_html),
draft.title,
brand.name,
brand.industry,
brand.description,
- ...input.rules.flatMap((r) => [r.name, r.detail]),
- ...input.textRules,
+ ...ruleWords,
+ ...facts,
todayText(),
);
// The people and quotes it may name: the same words, its data's and the authors' (CE-044).
@@ -701,17 +841,21 @@ async function fixWithRun({ draft, brand, brandId, draftId, input, passages, mor
brand.name,
brand.industry,
brand.description,
- ...input.rules.flatMap((r) => [r.name, r.detail]),
- ...input.textRules,
+ ...ruleWords,
...numbered.map(sourceWords),
...(await authorWords(supabaseAdmin, brand.organization_id)),
);
- // Where it may link: the brand's pages and the draft's sources (A).
+ // Where it may link: the brand's pages and the draft's sources (A); a
+ // hand-off's source checks link the draft's sources.
+ const linkKeys =
+ handoff && [...ruleKeys].some((key) => SOURCE_CHECKS.has(key))
+ ? new Set([...ruleKeys, 'outboundLinks', 'citeInline'])
+ : ruleKeys;
const targets = await readLinkTargets({
brandId,
draftId,
sourceUrl: draft.source_url,
- ruleKeys,
+ ruleKeys: linkKeys,
});
// Held on the budget before the call, so calls at once can't pass it.
const budget = await reserveAiBudget(brand.organization_id, {
@@ -734,8 +878,9 @@ async function fixWithRun({ draft, brand, brandId, draftId, input, passages, mor
more,
lockedKeys,
input,
- linkTargets: linkTargetsPrompt(targets, ruleKeys),
+ linkTargets: linkTargetsPrompt(targets, linkKeys),
sources: sourcesPrompt(numbered),
+ handoff,
}),
abortSignal,
}),
@@ -759,7 +904,7 @@ async function fixWithRun({ draft, brand, brandId, draftId, input, passages, mor
lockedKeys,
ruleKeys,
linkAllowList(targets),
- { numbered, known, people },
+ { numbered, known, people, keepPlaceholders: handoff },
);
// Stopped meanwhile: nothing it wrote is kept.
await stopIfStopped(run);
diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.js
index 0b3483797..38b667525 100644
--- a/server/src/lib/content-agent.test.js
+++ b/server/src/lib/content-agent.test.js
@@ -21,7 +21,9 @@ vi.mock('../config/supabase.js', () => ({
const chain = {
select: () => chain,
eq: () => chain,
+ is: () => chain,
in: () => chain,
+ gt: () => chain,
order: () => chain,
then: (resolve) => resolve(result()),
limit: async () => result(),
@@ -49,10 +51,18 @@ vi.mock('./plan-guard.js', async (importOriginal) => ({
}));
vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } }));
const stopIfStopped = vi.fn();
-vi.mock('./content-runs.js', async (importOriginal) => ({
- ...(await importOriginal()),
- stopIfStopped: (...args) => stopIfStopped(...args),
-}));
+/** A run's start, take-back and finish, when a test stands in for them. */
+const runs = vi.hoisted(() => ({ startRun: null, dropRun: null, finishRun: null }));
+vi.mock('./content-runs.js', async (importOriginal) => {
+ const real = await importOriginal();
+ return {
+ ...real,
+ stopIfStopped: (...args) => stopIfStopped(...args),
+ startRun: (...args) => (runs.startRun ?? real.startRun)(...args),
+ dropRun: (...args) => (runs.dropRun ?? real.dropRun)(...args),
+ finishRun: (...args) => (runs.finishRun ?? real.finishRun)(...args),
+ };
+});
const readLinkTargets = vi.fn();
vi.mock('./content-links.js', async (importOriginal) => ({
...(await importOriginal()),
@@ -64,6 +74,7 @@ const {
buildFixPrompt,
cleanInsertHtml,
draftPassages,
+ dropsPlaceholder,
fixDraftRules,
keepSuggestions,
growsPastLimit,
@@ -1028,6 +1039,15 @@ describe('fixDraftRules', () => {
expect(generateObject).not.toHaveBeenCalled();
});
+ it('runs one fix at a time on a draft: another under way is 409 running', async () => {
+ rows.content_agent_runs = [{ id: 'run-1' }];
+ await expect(
+ fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input() }),
+ ).rejects.toMatchObject({ status: 409, code: 'running' });
+ expect(reserveAiBudget).not.toHaveBeenCalled();
+ expect(generateObject).not.toHaveBeenCalled();
+ });
+
it('waits while Start or a rewrite holds the draft, which a stopped server no longer does', async () => {
rows.content_drafts.agent_state = 'writing';
rows.content_drafts.agent_state_at = new Date().toISOString();
@@ -1112,3 +1132,249 @@ describe('fixDraftRules', () => {
expect(held.release).toHaveBeenCalled();
});
});
+
+describe('Quality’s hand-off (CE-051)', () => {
+ const handoff = (over = {}) =>
+ input({
+ rules: [
+ {
+ key: 'trust:claimsSourced',
+ name: 'Every figure or claim has a source in its paragraph',
+ // The editor's words: no fact the agent may write.
+ detail: 'Brew at 94 degrees for 4 minutes.',
+ },
+ ],
+ locked: [],
+ ...over,
+ });
+
+ it('runs as a hand-off, and keeps the editor’s details from the facts it may write', async () => {
+ generateObject.mockResolvedValue({
+ object: {
+ suggestions: [
+ suggestion({
+ before: 'good coffee and hot water',
+ after: 'good coffee and water at 94 degrees',
+ rules: ['trust:claimsSourced'],
+ sources: [],
+ marks: [],
+ }),
+ ],
+ },
+ usage: { inputTokens: 900, outputTokens: 200 },
+ });
+ await fixDraftRules({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: handoff(),
+ handoff: { origin: 'person' },
+ });
+ // 94 was only in the editor's detail: a number with no source, so not kept.
+ expect(writes.find((w) => w.table === 'content_draft_suggestions')).toBeUndefined();
+ // A Fix open rules run takes the details as given.
+ writes = [];
+ await fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: handoff() });
+ expect(writes.find((w) => w.table === 'content_draft_suggestions').value[0].after_text).toBe(
+ 'good coffee and water at 94 degrees',
+ );
+ });
+
+ it('runs an automatic one only on a draft its brand hands off', async () => {
+ await expect(
+ fixDraftRules({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: handoff(),
+ handoff: { origin: 'auto' },
+ }),
+ ).rejects.toMatchObject({ status: 409, code: 'not_due' });
+ expect(generateObject).not.toHaveBeenCalled();
+ });
+
+ describe('an automatic one', () => {
+ beforeEach(() => {
+ rows.content_drafts = { ...rows.content_drafts, quality_handoff: true };
+ rows.brands = { ...rows.brands, content_quality_handoff: true };
+ runs.startRun = vi.fn(async () => ({
+ id: 'run-9',
+ steps: [],
+ signal: new AbortController().signal,
+ }));
+ runs.dropRun = vi.fn(async () => {});
+ runs.finishRun = vi.fn(async () => {});
+ });
+ afterEach(() => {
+ runs.startRun = runs.dropRun = runs.finishRun = null;
+ });
+
+ it('doesn’t run once the brand turned it off, though the draft was made while it was on', async () => {
+ rows.brands = { ...rows.brands, content_quality_handoff: false };
+ await expect(
+ fixDraftRules({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: handoff(),
+ handoff: { origin: 'auto' },
+ }),
+ ).rejects.toMatchObject({ status: 409, code: 'not_due' });
+ expect(runs.startRun).not.toHaveBeenCalled();
+ });
+
+ it('claims its one run, and gives it back when the AI budget stops it before it begins', async () => {
+ reserveAiBudget.mockRejectedValue(new PlanLimitError('used up', 429));
+ await expect(
+ fixDraftRules({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: handoff(),
+ handoff: { origin: 'auto' },
+ }),
+ ).rejects.toBeInstanceOf(PlanLimitError);
+ expect(runs.startRun).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'handoff', origin: 'auto', strict: true }),
+ );
+ expect(runs.dropRun).toHaveBeenCalled();
+ expect(runs.finishRun).not.toHaveBeenCalled();
+ });
+
+ it('keeps a person’s run, the budget spent, as failed', async () => {
+ reserveAiBudget.mockRejectedValue(new PlanLimitError('used up', 429));
+ await expect(
+ fixDraftRules({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: handoff(),
+ handoff: { origin: 'person' },
+ }),
+ ).rejects.toBeInstanceOf(PlanLimitError);
+ expect(runs.startRun).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'handoff', origin: 'person', strict: false }),
+ );
+ expect(runs.dropRun).not.toHaveBeenCalled();
+ expect(runs.finishRun).toHaveBeenCalledWith(expect.anything(), 'failed');
+ });
+ });
+
+ it('links the draft’s sources for its source checks, and writes the brand’s approved facts', async () => {
+ rows.brand_facts = [{ quote: 'Pro costs $49 per month' }];
+ generateObject.mockResolvedValue({
+ object: {
+ suggestions: [
+ suggestion({
+ before: 'good coffee and hot water',
+ after: 'good coffee and hot water, from $49 per month',
+ rules: ['trust:brandFacts'],
+ sources: [],
+ marks: [],
+ }),
+ ],
+ },
+ usage: { inputTokens: 900, outputTokens: 200 },
+ });
+ await fixDraftRules({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: handoff({
+ rules: [
+ { key: 'trust:brandFacts', name: 'Match the brand’s approved facts', detail: '' },
+ { key: 'trust:claimsSourced', name: 'Every figure has a source', detail: '' },
+ ],
+ }),
+ handoff: { origin: 'person' },
+ });
+ expect(readLinkTargets.mock.calls[0][0].ruleKeys).toEqual(
+ new Set(['trust:brandFacts', 'trust:claimsSourced', 'outboundLinks', 'citeInline']),
+ );
+ expect(writes.find((w) => w.table === 'content_draft_suggestions').value[0].after_text).toBe(
+ 'good coffee and hot water, from $49 per month',
+ );
+ });
+
+ it('leaves a placeholder to the person: a change that fills or drops one isn’t kept', () => {
+ const page = 'Brew it for [time, source] at home.';
+ expect(dropsPlaceholder(page, 'for [time, source] at home', 'for 4 minutes at home')).toBe(
+ true,
+ );
+ expect(dropsPlaceholder(page, 'Brew it', 'Steep it')).toBe(false);
+ // A "before" that cuts into the brackets fills it all the same.
+ expect(dropsPlaceholder('Buy [product name] today.', 'product name', 'Ansvisor Pro')).toBe(
+ true,
+ );
+ expect(dropsPlaceholder('See note [1].', 'See note', 'See the note')).toBe(false);
+ const passages = draftPassages('<p>Brew it for [time, source] at home, then pour.</p>');
+ const fill = suggestion({
+ passage: 1,
+ before: 'Brew it for [time, source] at home',
+ after: 'Brew it for a while at home',
+ rules: ['readability:longSentences'],
+ sources: [],
+ marks: [],
+ });
+ const rules = new Set(['readability:longSentences']);
+ expect(
+ keepSuggestions([fill], passages, new Set(), rules, null, { keepPlaceholders: true }),
+ ).toEqual([]);
+ expect(keepSuggestions([fill], passages, new Set(), rules)).toHaveLength(1);
+ });
+
+ it('counts each placeholder, so filling one of two alike isn’t kept either', () => {
+ const page = 'Teams save [figure, source] and cut costs by [figure, source].';
+ expect(dropsPlaceholder(page, 'Teams save [figure, source]', 'Teams save 30%')).toBe(true);
+ expect(dropsPlaceholder(page, 'Teams save', 'Most teams save')).toBe(false);
+ // In a heading only the agent's forms are placeholders: a title's own brackets aren't.
+ expect(
+ dropsPlaceholder(
+ 'Best CRM tools [2026 Update]',
+ 'Best CRM tools [2026 Update]',
+ 'Best CRM tools in 2026',
+ 'h1',
+ ),
+ ).toBe(false);
+ expect(
+ dropsPlaceholder('Save [figure, source] a week', 'Save [figure, source]', 'Save hours', 'h2'),
+ ).toBe(true);
+
+ // Read in what is kept: a placeholder moved into the blocks after the passage stays.
+ const passages = draftPassages(
+ '<p>Teams save [figure, source] and cut costs by [figure, source], every month.</p>',
+ );
+ const rules = new Set(['trust:claimsSourced']);
+ const filled = suggestion({
+ passage: 1,
+ before: 'Teams save [figure, source] and cut costs',
+ after: 'Teams save 30% and cut costs',
+ rules: ['trust:claimsSourced'],
+ sources: [],
+ marks: [],
+ });
+ expect(
+ keepSuggestions([filled], passages, new Set(), rules, null, { keepPlaceholders: true }),
+ ).toEqual([]);
+ const moved = suggestion({
+ passage: 1,
+ before: 'Teams save [figure, source] and cut costs by [figure, source], every month.',
+ after:
+ 'Teams save [figure, source] every month.<p>They cut costs by [figure, source] too.</p>',
+ rules: ['trust:claimsSourced'],
+ sources: [],
+ marks: [],
+ });
+ expect(
+ keepSuggestions([moved], passages, new Set(), rules, null, { keepPlaceholders: true }),
+ ).toHaveLength(2);
+ });
+
+ it('tells the model to leave the placeholders on a hand-off only', () => {
+ const args = {
+ brand: { name: 'Acme' },
+ draft: { title: 'T', page_type: null },
+ passages: draftPassages('<p>Brew it for [time, source].</p>'),
+ lockedKeys: new Set(),
+ input: { rules: [], textRules: [] },
+ };
+ expect(buildFixPrompt({ ...args, handoff: true })).toContain(
+ 'Leave every [placeholder] exactly as it is',
+ );
+ expect(buildFixPrompt(args)).not.toContain('Leave every [placeholder]');
+ });
+});
diff --git a/server/src/lib/content-handoff.js b/server/src/lib/content-handoff.js
new file mode 100644
index 000000000..009712239
--- /dev/null
+++ b/server/src/lib/content-handoff.js
@@ -0,0 +1,85 @@
+import { z } from 'zod';
+import { fixDraftRules, fixRulesInput } from './content-agent.js';
+
+/**
+ * Quality's hand-off (Content Editor Quality spec §5, CE-051): the Content
+ * Agent fixes every fixable Quality suggestion in one run, as suggestions
+ * the person reviews; what only the person can give stays a to-do. The
+ * editor reads the checks (they're computed in the browser) and sends each
+ * fixable one by its key, with what it names on the page (its sentences,
+ * links, the disclosure line); the server says what each asks, in its own
+ * words. One run, on the workspace's AI budget, as Fix open rules is.
+ */
+
+/** Each fixable check, by the editor's suggestion key: what the agent is asked. */
+export const HANDOFF_CHECKS = {
+ 'readability:avgSentence':
+ 'Average sentence 15–20 words: split the longest sentences, saying the same thing',
+ 'readability:longSentences': 'No sentence over 35 words: split each into two or three',
+ 'readability:readingLevel':
+ 'Easier to read: shorter sentences and words, plain words for jargon, the meaning kept',
+ 'readability:answerFirst':
+ 'Answer first: the first paragraph under the H1 answers what the H1 asks, in 60 words or fewer',
+ 'readability:shortParagraphs': 'Short paragraphs: 4 sentences at most; split longer ones',
+ 'readability:headingSpacing':
+ 'A heading every 200–300 words: add an H2 or H3 where a section runs long, named for what it covers',
+ 'readability:passiveJargon': 'Active voice and plain words: rewrite passive sentences and jargon',
+ 'trust:claimsSourced':
+ 'Every figure or claim has a source in its paragraph: link one from your data; where you have none, write the figure as a placeholder or soften the claim, never make one up',
+ 'trust:brandFacts':
+ "Match the brand's approved facts named here (prices, trial length, founding year) where the page differs",
+ 'trust:freshSources':
+ 'Sources from the last 24 months: where your data has a newer source for the same point, link it instead',
+ 'trust:noWeakSources':
+ "No forum, social post or competitor's page as a source: link a study, an official page or data from your data instead, where you have one",
+ 'trust:primarySources':
+ 'At least one primary source (an official page, research, a standard) from your data, linked where it supports the page',
+ 'trust:disclosure':
+ "The page recommends the brand's own product: add the disclosure line given here, as it is, under the page's opening paragraph",
+ 'trust:balanced':
+ "Balance: say where the brand's own product falls short, or where another option is the better pick, from the page and your data only; where you don't know, write a placeholder",
+ 'trust:noBrokenLinks':
+ "Links that don't answer: link a working source from your data for the same point instead, or soften the claim",
+};
+
+export const HANDOFF_KEYS = Object.keys(HANDOFF_CHECKS);
+
+export const handOffInput = fixRulesInput.omit({ rules: true }).extend({
+ /** The fixable checks open on the page, each with what it names there. */
+ items: z
+ .array(
+ z.object({
+ key: z.enum(HANDOFF_KEYS),
+ detail: z.string().trim().max(500).default(''),
+ }),
+ )
+ .min(1)
+ .max(HANDOFF_KEYS.length),
+ /** A person's Hand off, or the editor's on its own (Settings › Content). */
+ origin: z.enum(['person', 'auto']).default('person'),
+});
+
+/**
+ * Hands the draft's open Quality checks to the Content Agent: one run of
+ * Fix open rules' kind 'handoff', the checks as its rules in the server's
+ * words (each key once), and the same answers and errors (fixDraftRules).
+ */
+export async function handOffDraft({ draftId, brandId, input }) {
+ const seen = new Set();
+ const rules = input.items.flatMap(({ key, detail }) => {
+ if (seen.has(key)) return [];
+ seen.add(key);
+ return [{ key, name: HANDOFF_CHECKS[key], detail }];
+ });
+ return fixDraftRules({
+ draftId,
+ brandId,
+ input: {
+ rules,
+ textRules: input.textRules,
+ locked: input.locked,
+ ...(input.sources ? { sources: input.sources } : {}),
+ },
+ handoff: { origin: input.origin },
+ });
+}
diff --git a/server/src/lib/content-handoff.test.js b/server/src/lib/content-handoff.test.js
new file mode 100644
index 000000000..890245072
--- /dev/null
+++ b/server/src/lib/content-handoff.test.js
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** Quality's hand-off (CE-051): the page's fixable checks, in the server's words, as one run. */
+
+const fixDraftRules = vi.fn();
+vi.mock('./content-agent.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ fixDraftRules: (...args) => fixDraftRules(...args),
+}));
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+const { HANDOFF_CHECKS, handOffDraft, handOffInput } = await import('./content-handoff.js');
+
+beforeEach(() => {
+ fixDraftRules.mockReset().mockResolvedValue({ count: 3, batchId: 'b1' });
+});
+
+describe('handOffInput', () => {
+ it('takes the fixable checks by key, each with what it names, and who started it', () => {
+ const parsed = handOffInput.parse({
+ items: [{ key: 'trust:disclosure', detail: 'Disclosure: the product … is offered by Acme.' }],
+ locked: [],
+ });
+ expect(parsed).toMatchObject({ origin: 'person', textRules: [] });
+ // A to-do (the person's), or a key it doesn't know: refused.
+ expect(handOffInput.safeParse({ items: [{ key: 'eeat:experience' }] }).success).toBe(false);
+ expect(handOffInput.safeParse({ items: [] }).success).toBe(false);
+ expect(
+ handOffInput.safeParse({ items: [{ key: 'readability:longSentences' }], origin: 'cron' })
+ .success,
+ ).toBe(false);
+ });
+});
+
+describe('handOffDraft', () => {
+ it('runs Fix open rules as a hand-off, the checks in its own words, each once', async () => {
+ const input = handOffInput.parse({
+ items: [
+ { key: 'readability:longSentences', detail: '2 sentences over 35 words' },
+ { key: 'trust:claimsSourced', detail: 'Teams save 40% of their time.' },
+ { key: 'readability:longSentences', detail: 'again' },
+ ],
+ textRules: ['Say “we” for the brand'],
+ locked: ['a locked passage'],
+ origin: 'auto',
+ });
+ await expect(handOffDraft({ draftId: 'd1', brandId: 'b1', input })).resolves.toEqual({
+ count: 3,
+ batchId: 'b1',
+ });
+ expect(fixDraftRules).toHaveBeenCalledWith({
+ draftId: 'd1',
+ brandId: 'b1',
+ input: {
+ rules: [
+ {
+ key: 'readability:longSentences',
+ name: HANDOFF_CHECKS['readability:longSentences'],
+ detail: '2 sentences over 35 words',
+ },
+ {
+ key: 'trust:claimsSourced',
+ name: HANDOFF_CHECKS['trust:claimsSourced'],
+ detail: 'Teams save 40% of their time.',
+ },
+ ],
+ textRules: ['Say “we” for the brand'],
+ locked: ['a locked passage'],
+ },
+ handoff: { origin: 'auto' },
+ });
+ });
+});
diff --git a/server/src/lib/content-runs.js b/server/src/lib/content-runs.js
index a36cf94c5..badeb33b9 100644
--- a/server/src/lib/content-runs.js
+++ b/server/src/lib/content-runs.js
@@ -44,6 +44,25 @@ async function shown(what, runId, write) {
}
}
+/**
+ * Whether one of the agent's fixes (Fix open rules, Quality's hand-off) is
+ * under way on the draft, and not one a stopped server left: a second would
+ * make a model call of its own, charged, and its batch would hide the
+ * first's (another tab, or a person's beside the editor's own hand-off).
+ */
+export async function fixUnderWay(draftId) {
+ const { data, error } = await supabaseAdmin
+ .from('content_agent_runs')
+ .select('id')
+ .eq('draft_id', draftId)
+ .in('kind', ['fix', 'handoff'])
+ .is('finished_at', null)
+ .gt('started_at', new Date(Date.now() - RUN_STALE_MS).toISOString())
+ .limit(1);
+ if (error) throw error;
+ return (data?.length ?? 0) > 0;
+}
+
/**
* A run's steps by kind, each a short name for the work the server does
* then, with the counts the run gives (CE-027/035): the rules it writes to,
@@ -68,6 +87,14 @@ export function runSteps(kind, counts = {}) {
{ key: 'rewrite_page', count: null },
{ key: 'check_sources', count: null },
];
+ case 'handoff':
+ // Quality's hand-off (CE-051): the page's checks instead of its rules.
+ return [
+ { key: 'read_checks', count: n(counts.checks) },
+ { key: 'gather_sources', count: n(counts.sources) },
+ { key: 'write_changes', count: null },
+ { key: 'check_sources', count: null },
+ ];
case 'brief':
return [
{ key: 'gather_sources', count: n(counts.sources) },
@@ -91,8 +118,20 @@ export function runSteps(kind, counts = {}) {
* steps shown and Stop by its signal only. `claimedAt` is the claim a Start
* or Rewrite holds on the draft (its agent_state_at): a Stop lets go of that
* claim only, never another run's.
+ *
+ * `origin` says who started it: a person, or the editor on its own (auto,
+ * Quality's hand-off, CE-051). A run that must be written (`strict`) throws
+ * instead of running unshown: an automatic hand-off is one a draft, and its
+ * row is the claim (a second one is 409 `already`).
*/
-export async function startRun({ draftId, kind, counts, claimedAt = null }) {
+export async function startRun({
+ draftId,
+ kind,
+ counts,
+ claimedAt = null,
+ origin = 'person',
+ strict = false,
+}) {
const steps = runSteps(kind, counts);
const controller = new AbortController();
// Runs a stopped server left on the draft are closed: only those older
@@ -106,13 +145,34 @@ export async function startRun({ draftId, kind, counts, claimedAt = null }) {
.is('finished_at', null)
.lt('started_at', new Date(Date.now() - RUN_STALE_MS).toISOString()),
);
- const data = await shown('run', null, () =>
- supabaseAdmin
+ // A person's is the column's default: a database before 00275 takes it.
+ const row = {
+ draft_id: draftId,
+ kind,
+ steps,
+ claimed_at: claimedAt,
+ ...(origin === 'person' ? {} : { origin }),
+ };
+ let data;
+ if (strict) {
+ const { data: written, error } = await supabaseAdmin
.from('content_agent_runs')
- .insert({ draft_id: draftId, kind, steps, claimed_at: claimedAt })
+ .insert(row)
.select('id')
- .single(),
- );
+ .single();
+ if (error?.code === '23505') {
+ throw Object.assign(new Error('The draft was handed off already'), {
+ status: 409,
+ code: 'already',
+ });
+ }
+ if (error) throw error;
+ data = written;
+ } else {
+ data = await shown('run', null, () =>
+ supabaseAdmin.from('content_agent_runs').insert(row).select('id').single(),
+ );
+ }
const id = data?.id ?? null;
if (id) live.set(id, controller);
return { id, steps, signal: controller.signal };
@@ -232,3 +292,19 @@ export function isStop(err, run) {
(Boolean(run?.id) && live.get(run.id)?.signal.aborted === true)
);
}
+
+/**
+ * Takes a run's row back, as if it never started: an automatic hand-off the
+ * AI budget stopped before it began is tried again once the budget renews
+ * (its row is the one-a-draft claim). Logged, never thrown.
+ */
+export async function dropRun(run) {
+ if (!run?.id) return;
+ live.delete(run.id);
+ const dropped = await shown('dropped run', run.id, async () => {
+ const { error } = await supabaseAdmin.from('content_agent_runs').delete().eq('id', run.id);
+ return { data: !error, error };
+ });
+ // Not taken back: at least not left under way.
+ if (!dropped) await finishRun(run, 'failed');
+}
diff --git a/server/src/lib/content-runs.test.js b/server/src/lib/content-runs.test.js
index ed1e1085c..c463d9087 100644
--- a/server/src/lib/content-runs.test.js
+++ b/server/src/lib/content-runs.test.js
@@ -8,6 +8,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
let rows;
let writes;
let failInsert;
+/** The error an insert answers, when it isn't `failInsert`'s. */
+let insertError;
+let failDelete = false;
+/** The reads made, each with its filters. */
+let reads;
vi.mock('../config/supabase.js', () => ({
default: {
@@ -19,16 +24,30 @@ vi.mock('../config/supabase.js', () => ({
return {
select: () => ({
single: async () =>
- failInsert
- ? { data: null, error: new Error('down') }
- : { data: { id: 'run-1' }, error: null },
+ insertError
+ ? { data: null, error: insertError }
+ : failInsert
+ ? { data: null, error: new Error('down') }
+ : { data: { id: 'run-1' }, error: null },
}),
};
},
update: (value) => (writes.push({ table, op: 'update', value, call }), chain),
- select: (columns) => ((call.columns = columns), chain),
+ delete: () => {
+ writes.push({ table, op: 'delete', call });
+ return failDelete
+ ? { eq: async () => ({ error: new Error('down') }) }
+ : {
+ eq: (col, v) => (
+ call.filters.push(['eq', col, v]),
+ Promise.resolve({ error: null })
+ ),
+ };
+ },
+ select: (columns) => ((call.columns = columns), reads.push(call), chain),
eq: (col, v) => (call.filters.push(['eq', col, v]), chain),
is: (col, v) => (call.filters.push(['is', col, v]), chain),
+ in: (col, v) => (call.filters.push(['in', col, v]), chain),
gt: (col, v) => (call.filters.push(['gt', col, v]), chain),
lt: (col, v) => (call.filters.push(['lt', col, v]), chain),
gte: () => chain,
@@ -48,7 +67,9 @@ const {
RunStoppedError,
advanceRun,
callSignal,
+ dropRun,
finishRun,
+ fixUnderWay,
isStop,
runCall,
runSteps,
@@ -61,7 +82,28 @@ const {
beforeEach(() => {
rows = {};
writes = [];
+ reads = [];
failInsert = false;
+ insertError = null;
+});
+
+describe('fixUnderWay', () => {
+ it('finds a fix or a hand-off still going on the draft, not one a stopped server left', async () => {
+ rows.updated = [{ id: 'run-1' }];
+ await expect(fixUnderWay('d1')).resolves.toBe(true);
+ const [read] = reads;
+ expect(read.table).toBe('content_agent_runs');
+ expect(read.filters).toEqual([
+ ['eq', 'draft_id', 'd1'],
+ ['in', 'kind', ['fix', 'handoff']],
+ ['is', 'finished_at', null],
+ ['gt', 'started_at', expect.any(String)],
+ ]);
+ // Within RUN_STALE_MS: an older one is a stopped server's.
+ expect(Date.now() - Date.parse(read.filters[3][2])).toBeGreaterThanOrEqual(10 * 60_000);
+ rows.updated = [];
+ await expect(fixUnderWay('d1')).resolves.toBe(false);
+ });
});
describe('runSteps', () => {
@@ -268,3 +310,65 @@ describe('a run', () => {
await finishRun(run, 'failed');
});
});
+
+describe('Quality’s hand-off runs (CE-051)', () => {
+ it('reads the page’s checks first, and writes who started it', async () => {
+ expect(runSteps('handoff', { checks: 6, sources: 12 }).map((s) => [s.key, s.count])).toEqual([
+ ['read_checks', 6],
+ ['gather_sources', 12],
+ ['write_changes', null],
+ ['check_sources', null],
+ ]);
+ await startRun({ draftId: 'd1', kind: 'handoff', counts: {}, origin: 'auto', strict: true });
+ expect(writes.find((w) => w.op === 'insert').value).toMatchObject({
+ kind: 'handoff',
+ origin: 'auto',
+ });
+ // A person's is the column's default: a database before 00275 takes the row.
+ writes = [];
+ await startRun({ draftId: 'd1', kind: 'fix', counts: {} });
+ expect(writes.find((w) => w.op === 'insert').value).not.toHaveProperty('origin');
+ });
+
+ it('claims an automatic one once: a second is 409 already, and a run that must be written throws', async () => {
+ insertError = { code: '23505', message: 'duplicate key' };
+ await expect(
+ startRun({ draftId: 'd1', kind: 'handoff', counts: {}, origin: 'auto', strict: true }),
+ ).rejects.toMatchObject({ status: 409, code: 'already' });
+ insertError = null;
+ failInsert = true;
+ await expect(
+ startRun({ draftId: 'd1', kind: 'handoff', counts: {}, origin: 'auto', strict: true }),
+ ).rejects.toThrow('down');
+ // Not strict: it runs unshown, as before.
+ await expect(startRun({ draftId: 'd1', kind: 'fix', counts: {} })).resolves.toMatchObject({
+ id: null,
+ });
+ });
+
+ it('takes a run’s row back, so its claim goes', async () => {
+ const run = await startRun({
+ draftId: 'd1',
+ kind: 'handoff',
+ counts: {},
+ origin: 'auto',
+ strict: true,
+ });
+ await dropRun(run);
+ expect(writes.find((w) => w.op === 'delete')).toMatchObject({
+ table: 'content_agent_runs',
+ call: { filters: [['eq', 'id', 'run-1']] },
+ });
+ // Not taken back (the delete failed): at least not left under way.
+ writes = [];
+ failDelete = true;
+ await dropRun(run);
+ expect(writes.map((w) => w.op)).toEqual(['delete', 'update']);
+ expect(writes[1].value).toMatchObject({ outcome: 'failed' });
+ failDelete = false;
+ // No row written: nothing to take back.
+ writes = [];
+ await dropRun({ id: null });
+ expect(writes).toEqual([]);
+ });
+});
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index 6f8658725..64c42c135 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -2,6 +2,8 @@ import { Router } from 'express';
import { z } from 'zod';
import { assertBrandAccess } from '../lib/access.js';
import { fixDraftRules, fixRulesInput } from '../lib/content-agent.js';
+import { handOffDraft, handOffInput } from '../lib/content-handoff.js';
+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 { stopDraftRun } from '../lib/content-runs.js';
@@ -13,7 +15,8 @@ import { PlanLimitError } from '../lib/plan-guard.js';
* Content Editor drafts: Rebuild outline in the editor's Brief tab writes
* the draft's brief from the sources the person kept (CE-007); Fix open
* rules with agent leaves the Content Agent's suggestions for review
- * (CE-018); Start's Agent has the Content Agent do the page (CE-015);
+ * (CE-018); Hand off has it fix the page's open Quality checks (CE-051);
+ * Start's Agent has the Content Agent do the page (CE-015);
* Stop ends the agent's run under way, changing nothing (v1.1 CE-027); and
* Send to CMS sends pages to the brand's webhook (#1331).
*/
@@ -116,7 +119,8 @@ const fixBody = fixRulesInput.extend({ brandId: z.guid() });
* Body: { brandId, rules: [{ key, name, detail }], textRules, locked }
* Answers { count, batchId }: the suggestions left for review (none when the
* agent found nothing it could change); 409 `open_suggestions` while the
- * latest batch is undecided, 409 `published` for a published draft.
+ * latest batch is undecided, 409 `published` for a published draft, 409
+ * `running` while a fix or a hand-off on it is under way.
*/
router.post('/:draftId/suggestions', async (req, res) => {
const draftId = z.guid().safeParse(req.params.draftId);
@@ -145,6 +149,44 @@ router.post('/:draftId/suggestions', async (req, res) => {
}
});
+const handOffBody = handOffInput.extend({ brandId: z.guid() });
+
+/**
+ * POST /api/content-drafts/:draftId/handoff
+ * Body: { brandId, items: [{ key, detail }], textRules, locked, sources?, origin }
+ * Quality's hand-off (CE-051): answers { count, batchId } as /suggestions
+ * does, with its errors; 404 `off` before Quality's phase 2, 409 `not_due`
+ * for an automatic one the brand doesn't hand off, 409 `already` when the
+ * draft had its automatic one.
+ */
+router.post('/:draftId/handoff', async (req, res) => {
+ if (qualityPhase() < 2) return res.status(404).json({ error: 'Not available', code: 'off' });
+ const draftId = z.guid().safeParse(req.params.draftId);
+ const parsed = handOffBody.safeParse(req.body ?? {});
+ if (!draftId.success || !parsed.success) {
+ return res.status(400).json({ error: 'Invalid request', code: 'invalid' });
+ }
+ const { brandId, ...input } = parsed.data;
+ try {
+ await assertBrandAccess(brandId, req.user.id);
+ const result = await handOffDraft({ draftId: draftId.data, brandId, input });
+ return res.json(result);
+ } catch (err) {
+ if (err instanceof PlanLimitError) {
+ // 402: no active subscription, not a spent budget.
+ const code = err.statusCode === 402 ? 'no_subscription' : 'ai_budget';
+ return res.status(err.statusCode).json({ error: err.message, code });
+ }
+ 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 }, 'content draft hand-off error');
+ return res.status(502).json({ error: 'The agent could not run', code: 'failed' });
+ }
+});
+
const writeBody = writeDraftInput.extend({ brandId: z.guid() });
/**
diff --git a/server/src/routes/content-drafts.test.js b/server/src/routes/content-drafts.test.js
index 7981e5ec3..63f11aa6f 100644
--- a/server/src/routes/content-drafts.test.js
+++ b/server/src/routes/content-drafts.test.js
@@ -271,6 +271,58 @@ describe('POST /api/content-drafts/:draftId/suggestions', () => {
});
});
+describe('POST /api/content-drafts/:draftId/handoff (CE-051)', () => {
+ const handOff = (body) =>
+ fetch(`${baseUrl}/${DRAFT}/handoff`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const items = [{ key: 'readability:longSentences', detail: '2 sentences over 35 words' }];
+ beforeEach(() => {
+ process.env.CONTENT_QUALITY_PHASE = '2';
+ });
+ afterEach(() => {
+ delete process.env.CONTENT_QUALITY_PHASE;
+ });
+
+ it('hands the page’s checks to the agent for a member of the brand', async () => {
+ const res = await handOff({ brandId: BRAND, items, origin: 'auto' });
+ expect(res.status).toBe(200);
+ await expect(res.json()).resolves.toEqual({ count: 2, batchId: 'b1' });
+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');
+ expect(fixDraftRules).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftId: DRAFT,
+ brandId: BRAND,
+ input: expect.objectContaining({
+ rules: [expect.objectContaining({ key: 'readability:longSentences' })],
+ }),
+ handoff: { origin: 'auto' },
+ }),
+ );
+ });
+
+ it('is off before phase 2, refuses a check it doesn’t fix, and says why it didn’t run', async () => {
+ let res = await handOff({ brandId: BRAND, items: [{ key: 'eeat:experience' }] });
+ expect(res.status).toBe(400);
+ for (const code of ['not_due', 'already', 'open_suggestions']) {
+ fixDraftRules.mockRejectedValueOnce(Object.assign(new Error(code), { status: 409, code }));
+ res = await handOff({ brandId: BRAND, items });
+ expect(res.status).toBe(409);
+ await expect(res.json()).resolves.toMatchObject({ code });
+ }
+ fixDraftRules.mockRejectedValueOnce(new PlanLimitError('used up', 429));
+ res = await handOff({ brandId: BRAND, items });
+ expect(res.status).toBe(429);
+ await expect(res.json()).resolves.toMatchObject({ code: 'ai_budget' });
+ process.env.CONTENT_QUALITY_PHASE = '1';
+ res = await handOff({ brandId: BRAND, items });
+ expect(res.status).toBe(404);
+ await expect(res.json()).resolves.toMatchObject({ code: 'off' });
+ });
+});
+
describe('POST /api/content-drafts/:draftId/stop', () => {
const stop = (body = { brandId: BRAND }, draftId = DRAFT) =>
fetch(`${baseUrl}/${draftId}/stop`, {
diff --git a/supabase/migrations/00275_content_quality_handoff.sql b/supabase/migrations/00275_content_quality_handoff.sql
new file mode 100644
index 000000000..1490f8df5
--- /dev/null
+++ b/supabase/migrations/00275_content_quality_handoff.sql
@@ -0,0 +1,72 @@
+-- ============================================================================
+-- 00275: Quality phase 2, CE-051 — hand it off to the Content Agent
+-- ============================================================================
+-- Hand off has the Content Agent fix every fixable Quality suggestion in one
+-- run, as suggestions the person reviews: a run of its own kind. A brand may
+-- hand off its new and optimized pages on their own (Settings › Content,
+-- off by default); each such draft gets its automatic run once.
+--
+-- * content_agent_runs.kind gains 'handoff'; origin says who started a
+-- run: a person, or the editor on its own ('auto'), one a draft;
+-- * brands.content_quality_handoff: the brand's setting;
+-- * content_drafts.quality_handoff: the setting as it was when the draft
+-- was made (a trigger copies it; a member can't change it), so turning
+-- it on reaches new drafts only.
+
+alter table public.content_agent_runs drop constraint if exists content_agent_runs_kind_check;
+alter table public.content_agent_runs
+ add constraint content_agent_runs_kind_check
+ check (kind in ('fix', 'rewrite', 'write', 'brief', 'handoff'));
+
+alter table public.content_agent_runs
+ add column if not exists origin text not null default 'person'
+ check (origin in ('person', 'auto'));
+
+-- An automatic hand-off is once a draft: its row is the claim.
+create unique index if not exists content_agent_runs_auto_handoff
+ on public.content_agent_runs (draft_id)
+ where kind = 'handoff' and origin = 'auto';
+
+comment on column public.content_agent_runs.origin is
+ 'Content Agent run (00275): who started it — a person, or the editor on its own (auto: Quality''s hand-off, once a draft).';
+
+alter table public.brands
+ add column if not exists content_quality_handoff boolean not null default false;
+
+comment on column public.brands.content_quality_handoff is
+ 'Quality CE-051 (00275): hand off quality fixes automatically — new and optimized pages get the Content Agent''s hand-off run, its changes left for review. Off by default.';
+
+alter table public.content_drafts
+ add column if not exists quality_handoff boolean not null default false;
+
+comment on column public.content_drafts.quality_handoff is
+ 'Quality CE-051 (00275): the brand''s hand-off setting when the draft was made (a trigger copies it); its automatic hand-off runs once.';
+
+-- As the member who makes the draft (RLS reads their brand); the server
+-- bypasses RLS. A change by a member is undone: only the server sets it.
+create or replace function public.content_draft_quality_handoff()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if tg_op = 'INSERT' then
+ select b.content_quality_handoff into new.quality_handoff
+ from public.brands b
+ where b.id = new.brand_id;
+ new.quality_handoff := coalesce(new.quality_handoff, false);
+ elsif new.quality_handoff is distinct from old.quality_handoff
+ and not (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)
+ then
+ new.quality_handoff := old.quality_handoff;
+ end if;
+ return new;
+end;
+$$;
+
+drop trigger if exists content_drafts_quality_handoff on public.content_drafts;
+create trigger content_drafts_quality_handoff
+ before insert or update of quality_handoff on public.content_drafts
+ for each row execute function public.content_draft_quality_handoff();
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 52789b792..de296cf66 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -39325,6 +39325,82 @@ comment on column public.content_quality_pages.checks is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00275_content_quality_handoff.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00275: Quality phase 2, CE-051 — hand it off to the Content Agent
+-- ============================================================================
+-- Hand off has the Content Agent fix every fixable Quality suggestion in one
+-- run, as suggestions the person reviews: a run of its own kind. A brand may
+-- hand off its new and optimized pages on their own (Settings › Content,
+-- off by default); each such draft gets its automatic run once.
+--
+-- * content_agent_runs.kind gains 'handoff'; origin says who started a
+-- run: a person, or the editor on its own ('auto'), one a draft;
+-- * brands.content_quality_handoff: the brand's setting;
+-- * content_drafts.quality_handoff: the setting as it was when the draft
+-- was made (a trigger copies it; a member can't change it), so turning
+-- it on reaches new drafts only.
+
+alter table public.content_agent_runs drop constraint if exists content_agent_runs_kind_check;
+alter table public.content_agent_runs
+ add constraint content_agent_runs_kind_check
+ check (kind in ('fix', 'rewrite', 'write', 'brief', 'handoff'));
+
+alter table public.content_agent_runs
+ add column if not exists origin text not null default 'person'
+ check (origin in ('person', 'auto'));
+
+-- An automatic hand-off is once a draft: its row is the claim.
+create unique index if not exists content_agent_runs_auto_handoff
+ on public.content_agent_runs (draft_id)
+ where kind = 'handoff' and origin = 'auto';
+
+comment on column public.content_agent_runs.origin is
+ 'Content Agent run (00275): who started it — a person, or the editor on its own (auto: Quality''s hand-off, once a draft).';
+
+alter table public.brands
+ add column if not exists content_quality_handoff boolean not null default false;
+
+comment on column public.brands.content_quality_handoff is
+ 'Quality CE-051 (00275): hand off quality fixes automatically — new and optimized pages get the Content Agent''s hand-off run, its changes left for review. Off by default.';
+
+alter table public.content_drafts
+ add column if not exists quality_handoff boolean not null default false;
+
+comment on column public.content_drafts.quality_handoff is
+ 'Quality CE-051 (00275): the brand''s hand-off setting when the draft was made (a trigger copies it); its automatic hand-off runs once.';
+
+-- As the member who makes the draft (RLS reads their brand); the server
+-- bypasses RLS. A change by a member is undone: only the server sets it.
+create or replace function public.content_draft_quality_handoff()
+returns trigger
+language plpgsql
+set search_path = ''
+as $$
+begin
+ if tg_op = 'INSERT' then
+ select b.content_quality_handoff into new.quality_handoff
+ from public.brands b
+ where b.id = new.brand_id;
+ new.quality_handoff := coalesce(new.quality_handoff, false);
+ elsif new.quality_handoff is distinct from old.quality_handoff
+ and not (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user)
+ then
+ new.quality_handoff := old.quality_handoff;
+ end if;
+ return new;
+end;
+$$;
+
+drop trigger if exists content_drafts_quality_handoff on public.content_drafts;
+create trigger content_drafts_quality_handoff
+ before insert or update of quality_handoff on public.content_drafts
+ for each row execute function public.content_draft_quality_handoff();
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00276_organization_insert_columns.sql
-- ─────────────────────────────────────────────────────────────────────────