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.

fix(content): keep agent answers out of headings (#1369)

Cihan4a3b0e3312db
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.js
index 688a5477f..c7dce7d6c 100644
--- a/server/src/lib/content-agent.js
+++ b/server/src/lib/content-agent.js
@@ -28,6 +28,23 @@ const CALL_TIMEOUT_MS = 60_000;
/** The longest passage the agent may change: keepSuggestions skips longer ones. */
const MAX_PASSAGE_CHARS = 5_000;
+/**
+ * How long an agent may make a heading, by level: an H1 around 50–60
+ * characters, an H2 8–15 words, as 2026's SEO/AEO guides advise. Longer, it
+ * has taken in an answer. The same as HEADING_LIMITS in
+ * web/src/lib/content/suggestions.ts; a person's own headings are never held.
+ */
+export const HEADING_LIMITS = { h1: 70, other: 90 };
+
+/** The longest an agent may make a heading of this tag. */
+export const headingLimit = (tag) => (tag === 'h1' ? HEADING_LIMITS.h1 : HEADING_LIMITS.other);
+
+/** The headings rule both agent prompts give the model (fix rules, Start Agent). */
+export const HEADING_RULE = `- A heading stays a heading: one short line, an H1 up to ${HEADING_LIMITS.h1} characters and other headings up to ${HEADING_LIMITS.other}. Never write an answer, a sentence or a FAQ into a heading's replace; to answer under a heading, insert a paragraph after it.`;
+
+/** The shortest answer a heading's replace may carry for it to go under the heading. */
+const MIN_ANSWER_CHARS = 40;
+
/**
* How much of the page the model reads, in characters: a very long page is
* sent up to here, so one run can't spend far past the AI usage budget.
@@ -73,7 +90,7 @@ export const suggestionsSchema = z.object({
after: z
.string()
.describe(
- 'replace: the new words, as plain text; insert: the blocks to add, as simple HTML (h2, h3, p, ul, ol, li, strong, em).',
+ `replace: the new words, as plain text (a heading stays one line: an H1 up to ${HEADING_LIMITS.h1} characters, others up to ${HEADING_LIMITS.other}); insert: the blocks to add, as simple HTML (h2, h3, p, ul, ol, li, strong, em).`,
),
reason: z.string().describe('What the change does, in a few words.'),
rules: z.array(z.string()).describe('The keys of the rules it fixes.'),
@@ -88,6 +105,7 @@ Rules for your suggestions:
- Fix only the rules listed. Each suggestion fixes one or more of them; put their keys in "rules".
- A replace changes words inside one passage: copy "before" exactly as that passage has it (a phrase or a sentence), and write "after" as plain text that fits in its place.
- An insert adds new blocks after a passage, as simple HTML (h2, h3, p, ul, ol, li, strong, em).
+${HEADING_RULE}
- Never change a passage marked LOCKED: AI assistants quote its wording today. You may insert after it.
- Use only facts from the page and the brand. Never invent numbers, prices, dates, names, sources or quotes. When a rule needs a fact you don't have, write a placeholder in square brackets, e.g. [figure, source, year].
- Keep the page's voice and change as little as each rule needs. At most ${MAX_AGENT_SUGGESTIONS} suggestions.
@@ -158,11 +176,85 @@ const textOf = (html) =>
.root()
.text();
+const isHeading = (tag) => /^h[1-6]$/.test(tag);
+
+/** A question, then what follows it: "?" before a space, or a full-width "?". */
+const QUESTION_AND_ANSWER = /^([\s\S]+?(?:\?(?=\s)|?))\s*(\S[\s\S]*)$/;
+/** How an answer ends: a sentence. */
+const ANSWER_END = /[.!。!]$/;
+
+/** Where the first block of a cleaned HTML starts. */
+const BLOCK_START = /<(?:h[2-4]|p|ul|ol|li)>/;
+
+/** Whether a replace grows a heading past its limit: one already longer may still be shortened. */
+export function growsPastLimit(passage, before, words) {
+ if (!isHeading(passage.tag)) return false;
+ const now = passage.text.trim().length;
+ const then = passage.text.replace(before, () => words).trim().length;
+ return then > headingLimit(passage.tag) && then > now;
+}
+
+/** A paragraph holding `text`, escaped. */
+function paragraph(text) {
+ const $ = cheerio.load('<p></p>', null, false);
+ $('p').text(text);
+ return $.html();
+}
+
+/**
+ * A replace's "after" split into the words that go in its passage and the
+ * blocks that go after it. Asked to answer under a heading, models write the
+ * heading and its answer (or a whole FAQ) as the replace, which would glue
+ * them onto the heading's line. The words are its leading text, or its first
+ * block when that is of the passage's kind; the rest is an insert. On a
+ * heading, words that answer its question ("What is X? X is …", the answer
+ * a sentence of MIN_ANSWER_CHARS or more) keep the question, and the answer
+ * becomes the first paragraph under it.
+ */
+export function splitReplace(after, tag) {
+ const html = cleanInsertHtml(after);
+ const start = html.search(BLOCK_START);
+ let words = start === -1 ? html : html.slice(0, start);
+ let blocks = start === -1 ? '' : html.slice(start);
+ if (!textOf(words).trim()) {
+ const own = blocks.match(
+ isHeading(tag) ? /^<(h[2-4])>([\s\S]*?)<\/\1>/ : /^<(p)>([\s\S]*?)<\/p>/,
+ );
+ if (own) {
+ words = own[2];
+ blocks = blocks.slice(own[0].length);
+ }
+ }
+ // Line breaks and runs of spaces, not a non-breaking space the passage may keep.
+ words = textOf(words)
+ .replace(/[ \t\r\n\f]+/g, ' ')
+ .trim();
+ if (isHeading(tag)) {
+ // A question and its answer ("What is X? X is …"): the answer goes under
+ // the heading first, before any blocks that came with it. A subtitle that
+ // fits ("What is AEO? The Complete Guide") isn't one: an answer ends a
+ // sentence. Past the heading's limit, the rest is never the heading's.
+ const answered = words.match(QUESTION_AND_ANSWER);
+ if (
+ answered &&
+ (words.length > headingLimit(tag) ||
+ (ANSWER_END.test(answered[2]) && answered[2].length >= MIN_ANSWER_CHARS))
+ ) {
+ words = answered[1];
+ blocks = paragraph(answered[2]) + blocks;
+ }
+ }
+ return { words, blocks: blocks.trim() };
+}
+
/**
* The model's suggestions the editor can apply: on a passage that exists,
* a replace's words found in it and never on a locked passage, an insert's
* HTML cleaned and not empty; the rules named kept to the ones sent, and
- * each change once.
+ * each change once. A replace that carries blocks, or an answer on a
+ * heading, is split into a replace and an insert after it (splitReplace);
+ * one that would still grow a heading past its headingLimit is dropped (a
+ * long heading may still be shortened).
*/
export function keepSuggestions(raw, passages, lockedKeys, ruleKeys) {
const kept = [];
@@ -173,37 +265,53 @@ export function keepSuggestions(raw, passages, lockedKeys, ruleKeys) {
const reason = s.reason.trim().slice(0, 300);
if (!passage || !reason || passage.text.length > MAX_PASSAGE_CHARS) continue;
const rules = [...new Set(s.rules.filter((key) => ruleKeys.has(key)))];
- if (s.kind === 'replace') {
+ const insertOf = (html) =>
+ textOf(html).trim() && html.length <= 20_000
+ ? {
+ id: `insert:${passage.text}:${html}`,
+ row: {
+ kind: 'insert',
+ block_text: passage.text,
+ before_text: '',
+ after_text: html,
+ reason,
+ rule_keys: rules,
+ },
+ }
+ : null;
+ // One suggestion's changes are kept together, or not at all: a split
+ // replace never leaves a question without its answer.
+ let changes;
+ if (s.kind !== 'replace') {
+ changes = [insertOf(cleanInsertHtml(s.after))];
+ } else {
if (lockedKeys.has(passageKey(passage.text))) continue;
const before = s.before.trim();
- const after = textOf(s.after).trim();
- if (!before || !after || before === after || after.length > 2000) continue;
- if (!passage.text.includes(before)) continue;
- const id = `replace:${passage.text}:${before}`;
- if (seen.has(id)) continue;
- seen.add(id);
- kept.push({
- kind: 'replace',
- block_text: passage.text,
- before_text: before,
- after_text: after,
- reason,
- rule_keys: rules,
- });
- } else {
- const html = cleanInsertHtml(s.after);
- if (!textOf(html).trim() || html.length > 20_000) continue;
- const id = `insert:${passage.text}:${html}`;
- if (seen.has(id)) continue;
- seen.add(id);
- kept.push({
- kind: 'insert',
- block_text: passage.text,
- before_text: '',
- after_text: html,
- reason,
- rule_keys: rules,
- });
+ if (!before || !passage.text.includes(before)) continue;
+ const { words, blocks } = splitReplace(s.after, passage.tag);
+ const changed = words && words !== before;
+ if (changed && (words.length > 2000 || growsPastLimit(passage, before, words))) continue;
+ changes = [
+ changed && {
+ id: `replace:${passage.text}:${before}`,
+ row: {
+ kind: 'replace',
+ block_text: passage.text,
+ before_text: before,
+ after_text: words,
+ reason,
+ rule_keys: rules,
+ },
+ },
+ blocks && insertOf(blocks),
+ ];
+ }
+ changes = changes.filter(Boolean);
+ if (!changes.length || changes.some((c) => seen.has(c.id))) continue;
+ if (kept.length + changes.length > MAX_AGENT_SUGGESTIONS) continue;
+ for (const c of changes) {
+ seen.add(c.id);
+ kept.push(c.row);
}
}
return kept;
diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.js
index 95c94299f..9715b4767 100644
--- a/server/src/lib/content-agent.test.js
+++ b/server/src/lib/content-agent.test.js
@@ -45,9 +45,12 @@ const {
draftPassages,
fixDraftRules,
keepSuggestions,
+ growsPastLimit,
+ HEADING_LIMITS,
MAX_PROMPT_PASSAGE_CHARS,
passageKey,
promptPassages,
+ splitReplace,
} = await import('./content-agent.js');
const { PlanLimitError } = await import('./plan-guard.js');
@@ -215,6 +218,179 @@ describe('keepSuggestions', () => {
});
});
+/**
+ * An answer written into a heading's replace was glued onto the heading's
+ * line ("What is LLM SEO? LLM SEO optimizes…", "Frequently Asked
+ * QuestionsWhat is an AEO tracker?…"): it now goes after the heading.
+ */
+describe('a replace on a heading', () => {
+ const page = draftPassages(
+ '<h2>What is LLM SEO</h2><p>It is new.</p><h2>FAQ</h2><p>Ask us.</p><p>Use good coffee.</p>',
+ );
+ const keep = (over) =>
+ keepSuggestions(
+ [suggestion({ passage: 1, before: 'What is LLM SEO', rules: ['faq'], ...over })],
+ page,
+ new Set(),
+ new Set(['faq']),
+ );
+
+ it('keeps the question in the heading and inserts its answer after it', () => {
+ expect(
+ keep({ after: 'What is LLM SEO? LLM SEO optimizes pages for large language models.' }),
+ ).toEqual([
+ expect.objectContaining({
+ kind: 'replace',
+ block_text: 'What is LLM SEO',
+ before_text: 'What is LLM SEO',
+ after_text: 'What is LLM SEO?',
+ }),
+ expect.objectContaining({
+ kind: 'insert',
+ block_text: 'What is LLM SEO',
+ after_text: '<p>LLM SEO optimizes pages for large language models.</p>',
+ rule_keys: ['faq'],
+ }),
+ ]);
+ });
+
+ it('turns a heading sent with its blocks into the heading and an insert', () => {
+ const kept = keepSuggestions(
+ [
+ suggestion({
+ passage: 3,
+ before: 'FAQ',
+ after:
+ '<h2>Frequently Asked Questions</h2><h3>What is an AEO tracker?</h3><p>An AEO tracker monitors AI answers.</p>',
+ }),
+ ],
+ page,
+ new Set(),
+ new Set(),
+ );
+ expect(kept.map((k) => [k.kind, k.after_text])).toEqual([
+ ['replace', 'Frequently Asked Questions'],
+ ['insert', '<h3>What is an AEO tracker?</h3><p>An AEO tracker monitors AI answers.</p>'],
+ ]);
+ });
+
+ it('leaves only the insert when the heading keeps its words', () => {
+ expect(
+ keep({ after: '<h2>What is LLM SEO</h2><p>LLM SEO optimizes pages.</p>' }).map((k) => k.kind),
+ ).toEqual(['insert']);
+ });
+
+ it('keeps a split suggestion whole, or not at all, at the cap', () => {
+ const many = Array.from({ length: 7 }, (_, i) =>
+ suggestion({ kind: 'insert', passage: 2, before: '', after: `<p>Note ${i}.</p>` }),
+ );
+ const answer = suggestion({
+ after: 'What is LLM SEO? LLM SEO optimizes pages for large language models.',
+ });
+ const kept = keepSuggestions(
+ [...many, { ...answer, passage: 1, before: 'What is LLM SEO' }],
+ page,
+ new Set(),
+ new Set(),
+ );
+ expect(kept).toHaveLength(7);
+ expect(kept.every((k) => k.kind === 'insert')).toBe(true);
+ });
+
+ it('drops one that would still make the heading over its length', () => {
+ expect(keep({ after: 'What is LLM SEO '.repeat(10) })).toEqual([]);
+ });
+
+ it('holds an H1 to 70 characters and other headings to 90, unless they get shorter', () => {
+ expect(HEADING_LIMITS).toEqual({ h1: 70, other: 90 });
+ const h1 = { tag: 'h1', text: 'Guide' };
+ const h2 = { tag: 'h2', text: 'Guide' };
+ expect(growsPastLimit(h1, 'Guide', 'x'.repeat(70))).toBe(false);
+ expect(growsPastLimit(h1, 'Guide', 'x'.repeat(71))).toBe(true);
+ expect(growsPastLimit(h2, 'Guide', 'x'.repeat(90))).toBe(false);
+ expect(growsPastLimit(h2, 'Guide', 'x'.repeat(91))).toBe(true);
+ // An imported heading already over its limit may still be shortened.
+ const long = { tag: 'h2', text: 'y'.repeat(120) };
+ expect(growsPastLimit(long, 'y'.repeat(20), 'z'.repeat(10))).toBe(false);
+ expect(growsPastLimit(long, 'y'.repeat(20), 'z'.repeat(30))).toBe(true);
+ // A paragraph has no limit here.
+ expect(growsPastLimit({ tag: 'p', text: 'a' }, 'a', 'b'.repeat(500))).toBe(false);
+ });
+
+ it('keeps a heading with a second clause, and a paragraph replace as it was', () => {
+ expect(splitReplace('AEO or SEO? Which matters more in 2026', 'h2')).toEqual({
+ words: 'AEO or SEO? Which matters more in 2026',
+ blocks: '',
+ });
+ // A short second part is the heading's, not an answer.
+ expect(splitReplace("Is AEO worth it? Here's what the data says.", 'h2').blocks).toBe('');
+ expect(splitReplace('What is AEO? The complete guide.', 'h1').blocks).toBe('');
+ expect(
+ splitReplace(
+ 'AEO とは? AEO は AI アシスタントの回答に引用されるための最適化の方法です。説明します。',
+ 'h2',
+ ),
+ ).toEqual({
+ words: 'AEO とは?',
+ blocks: '<p>AEO は AI アシスタントの回答に引用されるための最適化の方法です。説明します。</p>',
+ });
+ // A non-breaking space stays one, as the passage keeps it.
+ expect(splitReplace('Pour\u00a0slowly', 'p').words).toBe('Pour\u00a0slowly');
+ expect(splitReplace('Use 15 g of coffee. Then pour.', 'p')).toEqual({
+ words: 'Use 15 g of coffee. Then pour.',
+ blocks: '',
+ });
+ });
+
+ it('puts the answer first under the heading when blocks come with it', () => {
+ expect(
+ splitReplace(
+ 'What is LLM SEO? LLM SEO optimizes pages for large language models.<ul><li>a</li></ul>',
+ 'h2',
+ ),
+ ).toEqual({
+ words: 'What is LLM SEO?',
+ blocks: '<p>LLM SEO optimizes pages for large language models.</p><ul><li>a</li></ul>',
+ });
+ expect(
+ splitReplace(
+ '<h2>What is LLM SEO? LLM SEO optimizes pages for large language models.</h2><p>More.</p>',
+ 'h2',
+ ),
+ ).toEqual({
+ words: 'What is LLM SEO?',
+ blocks: '<p>LLM SEO optimizes pages for large language models.</p><p>More.</p>',
+ });
+ });
+
+ it('keeps a subtitle that fits, and splits after a full-width ? with no space', () => {
+ const subtitle = 'What is AEO? The Complete Guide to Answer Engine Optimization';
+ expect(splitReplace(subtitle, 'h1')).toEqual({ words: subtitle, blocks: '' });
+ expect(
+ splitReplace(
+ 'AEOとは?AEOはAIアシスタントの回答に引用されるための最適化の方法です。詳しく順番に説明します。',
+ 'h2',
+ ),
+ ).toEqual({
+ words: 'AEOとは?',
+ blocks:
+ '<p>AEOはAIアシスタントの回答に引用されるための最適化の方法です。詳しく順番に説明します。</p>',
+ });
+ // "?" inside a word is no question's end.
+ expect(splitReplace('What?No. A long enough sentence that ends here.', 'h2').blocks).toBe('');
+ // Past the heading's limit the rest goes under it, a full stop or not.
+ const long = `What is LLM SEO? ${'LLM SEO optimizes pages for large language models '.repeat(2)}`;
+ expect(splitReplace(long, 'h2').words).toBe('What is LLM SEO?');
+ });
+
+ it('moves blocks sent with a paragraph replace after it', () => {
+ expect(splitReplace('<p>Use 15 g.</p><ul><li>a scale</li></ul>', 'p')).toEqual({
+ words: 'Use 15 g.',
+ blocks: '<ul><li>a scale</li></ul>',
+ });
+ });
+});
+
describe('cleanInsertHtml', () => {
it('keeps simple blocks without attributes and unwraps the rest', () => {
expect(
@@ -239,7 +415,13 @@ describe('fixDraftRules', () => {
expect(enforceImproveQuota).toHaveBeenCalledWith('org-1', expect.any(String));
expect(generateObject).toHaveBeenCalledWith(
- expect.objectContaining({ model: expect.stringMatching(/^model:/) }),
+ expect.objectContaining({
+ model: expect.stringMatching(/^model:/),
+ // An answer goes after a heading, never into it.
+ system: expect.stringContaining(
+ 'Never write an answer, a sentence or a FAQ into a heading',
+ ),
+ }),
);
expect(result).toEqual({ count: 1, batchId: expect.any(String) });
const usage = writes.find((w) => w.table === 'prompt_improve_usage');
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.js
index 36208b125..ba05fff41 100644
--- a/server/src/lib/content-writer.js
+++ b/server/src/lib/content-writer.js
@@ -4,6 +4,7 @@ import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
import { resolveModel } from './ai-provider.js';
import {
+ HEADING_RULE,
MAX_AGENT_SUGGESTIONS,
draftPassages,
hasOpenSuggestions,
@@ -104,6 +105,7 @@ Rules for your suggestions:
- Make the page answer the questions and AI searches listed, follow the brief when there is one, and meet the rules listed.
- A replace changes words inside one passage: copy "before" exactly as that passage has it (a phrase or a sentence), and write "after" as plain text that fits in its place.
- An insert adds new blocks after a passage, as simple HTML (h2, h3, p, ul, ol, li, strong, em): a missing section, a direct answer, an FAQ.
+${HEADING_RULE}
- Never change a passage marked LOCKED: AI assistants quote its wording today. You may insert after it.
- Put the keys of the rules a change meets in "rules" (none when it meets none).
- Use only facts from the page and the brand. Never invent numbers, prices, dates, names, sources or quotes; write a placeholder in square brackets instead, e.g. [figure, source, year].
diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.js
index 9502650c3..be262d94d 100644
--- a/server/src/lib/content-writer.test.js
+++ b/server/src/lib/content-writer.test.js
@@ -391,6 +391,10 @@ describe('runDraftWriting on an existing page', () => {
}),
]);
expect(generateObject.mock.calls[0][0].prompt).toContain(`[2] (p, LOCKED) ${QUOTED}`);
+ // An answer goes after a heading, never into it.
+ expect(generateObject.mock.calls[0][0].system).toContain(
+ 'Never write an answer, a sentence or a FAQ into a heading',
+ );
expect(draftUpdates()).toEqual([
{ status: 'in_review', agent_state: null, agent_state_at: expect.any(String) },
]);
diff --git a/web/messages/en.json b/web/messages/en.json
index 97aabb439..66a41c082 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3609,10 +3609,11 @@
"restore": "Restore",
"locked": "AI quotes this passage, so agents don't change it.",
"stale": "The page changed here since the agent read it.",
+ "heading": "This would put more than a heading into the heading. Reject it, and add the text below the heading yourself.",
"acceptedToast": "{count, plural, one {Accepted} other {# changes accepted}} · undo any time",
"rejectedToast": "{count, plural, one {Rejected} other {# changes rejected}} · restore any time",
"undoneToast": "{count, plural, one {Undone · back to the suggestion} other {# undone · the suggestions are back}}",
- "notApplied": "{count, plural, one {# suggestion couldn't be applied} other {# suggestions couldn't be applied}}: the page changed there, or AI quotes the passage.",
+ "notApplied": "{count, plural, one {# suggestion couldn't be applied} other {# suggestions couldn't be applied}}: the page changed there, AI quotes the passage, or a heading would get too long.",
"saveFailed": "Couldn't keep the decision. Try again.",
"htmlBlocked": "Accept or reject the {count, plural, one {# agent suggestion} other {# agent suggestions}} first, then edit as HTML.",
"fixRules": "Apply rules with Agent",
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.tsx
index 113581436..5cc02ca81 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
@@ -432,6 +432,7 @@ export function DraftEditor({
restore: t('suggestions.restore'),
locked: t('suggestions.locked'),
stale: t('suggestions.stale'),
+ heading: t('suggestions.heading'),
}),
[t],
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
index ea2ce44ce..bd95af4ff 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts
@@ -9,7 +9,7 @@ import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/p
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { cleanHtml } from '@/lib/content/clean-html';
import { passageKey } from '@/lib/content/cited-passages';
-import type { DraftSuggestion } from '@/lib/content/suggestions';
+import { growsPastLimit, type DraftSuggestion } from '@/lib/content/suggestions';
import { blockKey, citedLocks, citedPassagesKey, type CitedLocks } from './_cited-passages';
/**
@@ -34,6 +34,7 @@ export interface SuggestionLabels {
restore: string;
locked: string;
stale: string;
+ heading: string;
}
interface SuggestionView {
@@ -212,10 +213,16 @@ export function blockedReason(
all: DraftSuggestion[],
doc: PmNode = state.doc,
locks: CitedLocks = citedLocks(state),
-): 'stale' | 'locked' | null {
+): 'stale' | 'locked' | 'heading' | null {
const placed = placeSuggestion(state, { ...s, status: 'open' }, all, doc);
if (!placed) return 'stale';
if (placed.at === 'words' && lockedBlock(placed.block, locks)) return 'locked';
+ if (placed.at === 'words' && placed.block.node.type.name === 'heading') {
+ // A heading that would grow past its limit has taken in an answer.
+ const now = placed.block.node.textContent.length;
+ const then = now - s.beforeText.length + s.afterText.length;
+ if (growsPastLimit(placed.block.node.attrs.level, now, then)) return 'heading';
+ }
return null;
}
@@ -350,7 +357,7 @@ function badge(text: string, tone: 'ok' | 'no'): HTMLElement {
function card(
s: DraftSuggestion,
labels: SuggestionLabels,
- blocked: 'stale' | 'locked' | null,
+ blocked: 'stale' | 'locked' | 'heading' | null,
decide: (id: string, decision: SuggestionDecision) => void,
): HTMLElement {
if (s.status === 'rejected') {
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.tsx
index a6942bc11..7c65cebf2 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
@@ -1078,10 +1078,39 @@ describe('the content editor', () => {
expect(pageText()).toContain(VAGUE);
expect(decideDraftSuggestions).not.toHaveBeenCalled();
expect(toast).toHaveBeenCalledWith(
- "2 suggestions couldn't be applied: the page changed there, or AI quotes the passage.",
+ "2 suggestions couldn't be applied: the page changed there, AI quotes the passage, or a heading would get too long.",
);
});
+ it('never glues an answer into a heading, and takes a short change to one', async () => {
+ const ANSWER =
+ 'Pipeline forecasting? It predicts which deals close this quarter from the activity on each one, team by team, against the revenue that closed.';
+ getContentDraft.mockResolvedValue(page);
+ getDraftSuggestions.mockResolvedValue([
+ suggestion({
+ blockText: 'Pipeline forecasting',
+ beforeText: 'Pipeline forecasting',
+ afterText: ANSWER,
+ }),
+ suggestion({
+ id: 's4',
+ blockText: 'Pipeline forecasting',
+ beforeText: 'forecasting',
+ afterText: 'forecasting, explained',
+ }),
+ ]);
+ await renderPage();
+
+ const glued = cardOf('s1')!;
+ expect(glued.textContent).toContain('This would put more than a heading into the heading.');
+ expect(
+ [...glued.querySelectorAll('button')].find((b) => b.textContent === 'Accept')!.disabled,
+ ).toBe(true);
+ await press('s4', 'Accept');
+ expect(pageText()).toContain('Pipeline forecasting, explained');
+ expect(pageText()).not.toContain('It predicts which deals');
+ });
+
it('leaves the page and the card as they were when the decision can’t be saved', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
getContentDraft.mockResolvedValue(page);
diff --git a/web/src/lib/content/agent-suggestions.test.ts b/web/src/lib/content/agent-suggestions.test.ts
index 8126a80f0..67c6991a5 100644
--- a/web/src/lib/content/agent-suggestions.test.ts
+++ b/web/src/lib/content/agent-suggestions.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from 'vitest';
import { passageKey } from './cited-passages';
-import { cleanInsertHtml, draftPassages, keepAgentSuggestions } from './agent-suggestions';
+import {
+ cleanInsertHtml,
+ draftPassages,
+ keepAgentSuggestions,
+ splitReplace,
+} from './agent-suggestions';
const HTML =
'<h1>How to brew pour-over</h1><p>Use good coffee &amp; hot water.</p>' +
@@ -104,3 +109,151 @@ describe('keepAgentSuggestions', () => {
]);
});
});
+
+/**
+ * An answer written into a heading's replace was glued onto the heading's
+ * line ("What is LLM SEO? LLM SEO optimizes…"): it now goes after it.
+ */
+describe('a replace on a heading', () => {
+ const page = draftPassages('<h2>What is LLM SEO</h2><p>It is new.</p><h2>FAQ</h2>');
+ const heading = (after: string, over = {}) => ({
+ kind: 'replace' as const,
+ passage: 1,
+ before: 'What is LLM SEO',
+ after,
+ reason: 'answer under the H2',
+ ...over,
+ });
+
+ it('keeps the question in the heading and inserts its answer after it', () => {
+ const { kept, dropped } = keepAgentSuggestions(
+ [heading('What is LLM SEO? LLM SEO optimizes pages for large language models & AI.')],
+ page,
+ new Set(),
+ );
+ expect(dropped).toEqual([]);
+ expect(kept.map((k) => [k.kind, k.block_text, k.after_text])).toEqual([
+ ['replace', 'What is LLM SEO', 'What is LLM SEO?'],
+ [
+ 'insert',
+ 'What is LLM SEO',
+ '<p>LLM SEO optimizes pages for large language models &amp; AI.</p>',
+ ],
+ ]);
+ });
+
+ it('turns a FAQ sent as a heading replace into the heading and an insert', () => {
+ const { kept } = keepAgentSuggestions(
+ [
+ heading(
+ '<h2>Frequently Asked Questions</h2><h3>What is an AEO tracker?</h3><p>It monitors AI answers.</p>',
+ { passage: 3, before: 'FAQ' },
+ ),
+ ],
+ page,
+ new Set(),
+ );
+ expect(kept.map((k) => [k.kind, k.after_text])).toEqual([
+ ['replace', 'Frequently Asked Questions'],
+ ['insert', '<h3>What is an AEO tracker?</h3><p>It monitors AI answers.</p>'],
+ ]);
+ });
+
+ it('says when a heading would still run over its length', () => {
+ const { kept, dropped } = keepAgentSuggestions(
+ [heading('What is LLM SEO '.repeat(10))],
+ page,
+ new Set(),
+ );
+ expect(kept).toEqual([]);
+ expect(dropped).toEqual([{ index: 0, reason: 'heading_too_long' }]);
+ });
+
+ it('holds an H1 to 70 characters and other headings to 90, unless they get shorter', () => {
+ const run = (html: string, before: string, after: string) =>
+ keepAgentSuggestions(
+ [{ kind: 'replace', passage: 1, before, after, reason: 'tighten' }],
+ draftPassages(html),
+ new Set(),
+ ).dropped;
+ expect(run('<h1>Guide</h1>', 'Guide', 'x'.repeat(70))).toEqual([]);
+ expect(run('<h1>Guide</h1>', 'Guide', 'x'.repeat(71))).toEqual([
+ { index: 0, reason: 'heading_too_long' },
+ ]);
+ expect(run('<h2>Guide</h2>', 'Guide', 'x'.repeat(90))).toEqual([]);
+ expect(run('<h3>Guide</h3>', 'Guide', 'x'.repeat(91))).toEqual([
+ { index: 0, reason: 'heading_too_long' },
+ ]);
+ // An imported heading already over its limit may still be shortened.
+ expect(run(`<h2>${'y'.repeat(120)}</h2>`, 'y'.repeat(20), 'z'.repeat(10))).toEqual([]);
+ });
+
+ it('keeps a split suggestion whole, or not at all, at the cap', () => {
+ const many = Array.from({ length: 19 }, (_, i) => ({
+ kind: 'insert' as const,
+ passage: 2,
+ after: `<p>Note ${i}.</p>`,
+ reason: 'note',
+ }));
+ const { kept, dropped } = keepAgentSuggestions(
+ [...many, heading('What is LLM SEO? LLM SEO optimizes pages for large language models.')],
+ page,
+ new Set(),
+ );
+ expect(kept).toHaveLength(19);
+ expect(dropped).toEqual([{ index: 19, reason: 'too_many' }]);
+ });
+
+ it('puts the answer first under the heading when blocks come with it', () => {
+ expect(
+ splitReplace(
+ 'What is LLM SEO? LLM SEO optimizes pages for large language models.<ul><li>a</li></ul>',
+ 'h2',
+ ),
+ ).toEqual({
+ words: 'What is LLM SEO?',
+ blocks: '<p>LLM SEO optimizes pages for large language models.</p><ul><li>a</li></ul>',
+ });
+ expect(
+ splitReplace(
+ '<h2>What is LLM SEO? LLM SEO optimizes pages for large language models.</h2><p>More.</p>',
+ 'h2',
+ ).blocks,
+ ).toBe('<p>LLM SEO optimizes pages for large language models.</p><p>More.</p>');
+ });
+
+ it('keeps a subtitle that fits, and splits after a full-width ? with no space', () => {
+ const subtitle = 'What is AEO? The Complete Guide to Answer Engine Optimization';
+ expect(splitReplace(subtitle, 'h1')).toEqual({ words: subtitle, blocks: '' });
+ expect(
+ splitReplace(
+ 'AEOとは?AEOはAIアシスタントの回答に引用されるための最適化の方法です。詳しく順番に説明します。',
+ 'h2',
+ ).words,
+ ).toBe('AEOとは?');
+ // "?" inside a word is no question's end.
+ expect(splitReplace('What?No. A long enough sentence that ends here.', 'h2').blocks).toBe('');
+ // Past the heading's limit the rest goes under it, a full stop or not.
+ const long = `What is LLM SEO? ${'LLM SEO optimizes pages for large language models '.repeat(2)}`;
+ expect(splitReplace(long, 'h2').words).toBe('What is LLM SEO?');
+ });
+
+ it('keeps a heading with a second clause, and moves blocks off a paragraph', () => {
+ // A short second part is the heading's, not an answer.
+ expect(splitReplace("Is AEO worth it? Here's what the data says.", 'h2').blocks).toBe('');
+ expect(
+ splitReplace(
+ 'AEO とは? AEO は AI アシスタントの回答に引用されるための最適化の方法です。説明します。',
+ 'h2',
+ ).words,
+ ).toBe('AEO とは?');
+ expect(splitReplace('AEO or SEO? Which matters more in 2026', 'h2')).toEqual({
+ words: 'AEO or SEO? Which matters more in 2026',
+ blocks: '',
+ });
+ expect(splitReplace('<p>Use 15 g.</p><ul><li>a scale</li></ul>', 'p')).toEqual({
+ words: 'Use 15 g.',
+ blocks: '<ul><li>a scale</li></ul>',
+ });
+ });
+});
diff --git a/web/src/lib/content/agent-suggestions.ts b/web/src/lib/content/agent-suggestions.ts
index 126c1228d..a157f9b4e 100644
--- a/web/src/lib/content/agent-suggestions.ts
+++ b/web/src/lib/content/agent-suggestions.ts
@@ -1,5 +1,6 @@
import sanitizeHtml from 'sanitize-html';
import { passageKey } from './cited-passages';
+import { growsPastLimit, headingLimit } from './suggestions';
/**
* An agent's suggestions through the editor API (CE-022): the same contract
@@ -67,6 +68,72 @@ export function cleanInsertHtml(html: string): string {
const textOf = (html: string) =>
decodeEntities(sanitizeHtml(html ?? '', { allowedTags: [], allowedAttributes: {} }));
+const isHeading = (tag: string) => /^h[1-6]$/.test(tag);
+
+/** A heading tag's level: h2 → 2. */
+const levelOf = (tag: string) => Number(tag.slice(1));
+
+/** The shortest answer a heading's replace may carry for it to go under the heading. */
+const MIN_ANSWER_CHARS = 40;
+
+/** A question, then what follows it: "?" before a space, or a full-width "?". */
+const QUESTION_AND_ANSWER = /^([\s\S]+?(?:\?(?=\s)|?))\s*(\S[\s\S]*)$/;
+/** How an answer ends: a sentence. */
+const ANSWER_END = /[.!。!]$/;
+
+/** Where the first block of a cleaned HTML starts. */
+const BLOCK_START = /<(?:h[2-4]|p|ul|ol|li)>/;
+
+const escapeHtml = (text: string) =>
+ text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+
+/**
+ * A replace's "after" split into the words that go in its passage and the
+ * blocks that go after it, as the Content Agent splits it on the server
+ * (splitReplace in server/src/lib/content-agent.js). Agents asked to answer
+ * under a heading write the heading and its answer (or a whole FAQ) as the
+ * replace, which would glue them onto the heading's line. The words are its
+ * leading text, or its first block when that is of the passage's kind; the
+ * rest is an insert. On a heading, words that answer its question ("What
+ * is X? X is …", the answer a sentence of MIN_ANSWER_CHARS or more) keep the
+ * question, and the answer becomes the first paragraph under it.
+ */
+export function splitReplace(after: string, tag: string): { words: string; blocks: string } {
+ const html = cleanInsertHtml(after);
+ const start = html.search(BLOCK_START);
+ let words = start === -1 ? html : html.slice(0, start);
+ let blocks = start === -1 ? '' : html.slice(start);
+ if (!textOf(words).trim()) {
+ const own = blocks.match(
+ isHeading(tag) ? /^<(h[2-4])>([\s\S]*?)<\/\1>/ : /^<(p)>([\s\S]*?)<\/p>/,
+ );
+ if (own) {
+ words = own[2];
+ blocks = blocks.slice(own[0].length);
+ }
+ }
+ // Line breaks and runs of spaces, not a non-breaking space the passage may keep.
+ words = textOf(words)
+ .replace(/[ \t\r\n\f]+/g, ' ')
+ .trim();
+ if (isHeading(tag)) {
+ // A question and its answer ("What is X? X is …"): the answer goes under
+ // the heading first, before any blocks that came with it. A subtitle that
+ // fits ("What is AEO? The Complete Guide") isn't one: an answer ends a
+ // sentence. Past the heading's limit, the rest is never the heading's.
+ const answered = words.match(QUESTION_AND_ANSWER);
+ if (
+ answered &&
+ (words.length > headingLimit(levelOf(tag)) ||
+ (ANSWER_END.test(answered[2]) && answered[2].length >= MIN_ANSWER_CHARS))
+ ) {
+ words = answered[1];
+ blocks = `<p>${escapeHtml(answered[2])}</p>${blocks}`;
+ }
+ }
+ return { words, blocks: blocks.trim() };
+}
+
/** What an agent sends: passage numbers are 1-based, as get_content_draft lists them. */
export interface AgentSuggestionInput {
kind: 'replace' | 'insert';
@@ -94,12 +161,16 @@ export type DroppedReason =
| 'no_change'
| 'empty'
| 'duplicate'
- | 'too_many';
+ | 'too_many'
+ | 'heading_too_long';
/**
* The suggestions the editor can apply: a passage that exists; a replace's
* words found in it as written, changed, and never on a locked passage; an
- * insert's HTML cleaned and not empty; each change once.
+ * insert's HTML cleaned and not empty; each change once. A replace that
+ * carries blocks, or an answer on a heading, is split into a replace and an
+ * insert after it (splitReplace); one that would still grow a heading past
+ * its limit (growsPastLimit) is dropped.
*/
export function keepAgentSuggestions(
raw: AgentSuggestionInput[],
@@ -117,39 +188,70 @@ export function keepAgentSuggestions(
const reason = s.reason.trim().slice(0, 300);
if (!reason) return drop('empty');
const rules = [...new Set((s.rules ?? []).map((r) => r.trim()).filter(Boolean))].slice(0, 20);
- if (s.kind === 'replace') {
+ const insertOf = (html: string): { id: string; row: KeptSuggestion } | null =>
+ textOf(html).trim() && html.length <= 20_000
+ ? {
+ id: `insert:${passage.text}:${html}`,
+ row: {
+ kind: 'insert',
+ block_text: passage.text,
+ before_text: '',
+ after_text: html,
+ reason,
+ rule_keys: rules,
+ },
+ }
+ : null;
+ // One suggestion's changes are kept together, or not at all: a split
+ // replace never leaves a question without its answer.
+ const changes: { id: string; row: KeptSuggestion }[] = [];
+ if (s.kind !== 'replace') {
+ const insert = insertOf(cleanInsertHtml(s.after));
+ if (!insert) return drop('empty');
+ changes.push(insert);
+ } else {
if (lockedKeys.has(passageKey(passage.text))) return drop('locked');
const before = (s.before ?? '').trim();
- const after = textOf(s.after).trim();
- if (!before || !after) return drop('empty');
- if (before === after || after.length > 2000) return drop('no_change');
+ const { words, blocks } = splitReplace(s.after, passage.tag);
+ if (!before || (!words && !blocks)) return drop('empty');
+ const changed = !!words && words !== before;
+ if (!changed && !blocks) return drop('no_change');
+ if (changed && words.length > 2000) return drop('no_change');
if (!passage.text.includes(before)) return drop('not_in_passage');
- const id = `replace:${passage.text}:${before}`;
- if (seen.has(id)) return drop('duplicate');
- seen.add(id);
- kept.push({
- kind: 'replace',
- block_text: passage.text,
- before_text: before,
- after_text: after,
- reason,
- rule_keys: rules,
- });
- return;
+ if (
+ changed &&
+ isHeading(passage.tag) &&
+ growsPastLimit(
+ levelOf(passage.tag),
+ passage.text.trim().length,
+ passage.text.replace(before, () => words).trim().length,
+ )
+ ) {
+ return drop('heading_too_long');
+ }
+ if (changed) {
+ changes.push({
+ id: `replace:${passage.text}:${before}`,
+ row: {
+ kind: 'replace',
+ block_text: passage.text,
+ before_text: before,
+ after_text: words,
+ reason,
+ rule_keys: rules,
+ },
+ });
+ }
+ const insert = blocks ? insertOf(blocks) : null;
+ if (insert) changes.push(insert);
+ if (!changes.length) return drop('empty');
+ }
+ if (changes.some((c) => seen.has(c.id))) return drop('duplicate');
+ if (kept.length + changes.length > MAX_API_SUGGESTIONS) return drop('too_many');
+ for (const c of changes) {
+ seen.add(c.id);
+ kept.push(c.row);
}
- const html = cleanInsertHtml(s.after);
- if (!textOf(html).trim() || html.length > 20_000) return drop('empty');
- const id = `insert:${passage.text}:${html}`;
- if (seen.has(id)) return drop('duplicate');
- seen.add(id);
- kept.push({
- kind: 'insert',
- block_text: passage.text,
- before_text: '',
- after_text: html,
- reason,
- rule_keys: rules,
- });
});
return { kept, dropped };
}
diff --git a/web/src/lib/content/suggestions.test.ts b/web/src/lib/content/suggestions.test.ts
new file mode 100644
index 000000000..c0ba8b278
--- /dev/null
+++ b/web/src/lib/content/suggestions.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { growsPastLimit, headingLimit } from './suggestions';
+
+/**
+ * How long an agent's change may make a heading: an H1 up to 70 characters,
+ * other headings up to 90, as 2026's SEO/AEO guides advise. Longer, it has
+ * taken in an answer.
+ */
+describe('growsPastLimit', () => {
+ it('holds an H1 to 70 characters and other headings to 90', () => {
+ expect([1, 2, 3, 6].map(headingLimit)).toEqual([70, 90, 90, 90]);
+ expect(growsPastLimit(1, 20, 70)).toBe(false);
+ expect(growsPastLimit(1, 20, 71)).toBe(true);
+ expect(growsPastLimit(2, 20, 90)).toBe(false);
+ expect(growsPastLimit(2, 20, 91)).toBe(true);
+ });
+
+ it('lets a heading already over its limit be shortened, never grown', () => {
+ expect(growsPastLimit(2, 120, 110)).toBe(false);
+ expect(growsPastLimit(2, 120, 120)).toBe(false);
+ expect(growsPastLimit(2, 120, 121)).toBe(true);
+ });
+});
diff --git a/web/src/lib/content/suggestions.ts b/web/src/lib/content/suggestions.ts
index 8118719a1..e083c5ffc 100644
--- a/web/src/lib/content/suggestions.ts
+++ b/web/src/lib/content/suggestions.ts
@@ -31,6 +31,28 @@ export interface DraftSuggestion {
status: SuggestionStatus;
}
+/**
+ * How long an agent's change may make a heading, by level: an H1 around 50–60
+ * characters, an H2 8–15 words, as 2026's SEO/AEO guides advise. Longer, it
+ * has taken in an answer (the agent glued "What is X? X is …" into H2s). The
+ * same as HEADING_LIMITS in server/src/lib/content-agent.js; a person's own
+ * headings are never held.
+ */
+export const HEADING_LIMITS = { h1: 70, other: 90 } as const;
+
+/** The longest an agent may make a heading of this level (1–6). */
+export function headingLimit(level: number): number {
+ return level === 1 ? HEADING_LIMITS.h1 : HEADING_LIMITS.other;
+}
+
+/**
+ * Whether changing a heading from `now` to `then` characters grows it past
+ * its limit: one already longer may still be shortened.
+ */
+export function growsPastLimit(level: number, now: number, then: number): boolean {
+ return then > headingLimit(level) && then > now;
+}
+
/** The most suggestions decided at once (00217). */
export const MAX_DECIDE = 200;
diff --git a/web/src/lib/mcp/content-schemas.ts b/web/src/lib/mcp/content-schemas.ts
index 5cf05910e..ab516c44a 100644
--- a/web/src/lib/mcp/content-schemas.ts
+++ b/web/src/lib/mcp/content-schemas.ts
@@ -81,7 +81,11 @@ export const suggestionsShape = {
kind: z.enum(['replace', 'insert']),
passage: z.number().int().min(1).describe('The passage number, from get_content_draft.'),
before: z.string().max(5000).optional().describe('replace: the exact words to change.'),
- after: z.string().min(1).max(20_000).describe('replace: the new words; insert: the HTML.'),
+ after: z
+ .string()
+ .min(1)
+ .max(20_000)
+ .describe('replace: the new words (a heading stays one short line); insert: the HTML.'),
reason: z
.string()
.min(1)
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 5cdeddb0e..9f7662c32 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -56,6 +56,7 @@ import {
suggestContentChangesFor,
} from './content';
import { MAX_API_SUGGESTIONS } from '@/lib/content/agent-suggestions';
+import { HEADING_LIMITS } from '@/lib/content/suggestions';
import {
addSourceShape,
createDraftShape,
@@ -1687,7 +1688,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
server.registerTool(
'suggest_content_changes',
{
- description: `Leave changes on a draft for a person to accept or reject in the editor — never applied by the agent. Read the draft with get_content_draft first: each suggestion names a passage by its number. A replace changes words in that passage ("before" copied exactly as the passage has it, "after" as plain text); an insert adds blocks after it ("after" as simple HTML: h2, h3, p, ul, ol, li, strong, em). Never change a locked passage. While a person still has the draft's open suggestions to decide, no new ones are taken: wait until get_content_draft lists none. At most ${MAX_API_SUGGESTIONS}; ones the editor can't apply come back in "dropped" with the reason (no_passage, locked, not_in_passage, no_change, empty, duplicate, too_many).`,
+ description: `Leave changes on a draft for a person to accept or reject in the editor — never applied by the agent. Read the draft with get_content_draft first: each suggestion names a passage by its number. A replace changes words in that passage ("before" copied exactly as the passage has it, "after" as plain text); an insert adds blocks after it ("after" as simple HTML: h2, h3, p, ul, ol, li, strong, em). A heading stays one line (an H1 up to ${HEADING_LIMITS.h1} characters, others up to ${HEADING_LIMITS.other}): to answer under it, insert a paragraph after it (an answer or blocks sent in a heading's replace are moved into an insert after it). Never change a locked passage. While a person still has the draft's open suggestions to decide, no new ones are taken: wait until get_content_draft lists none. At most ${MAX_API_SUGGESTIONS}; ones the editor can't apply come back in "dropped" with the reason (no_passage, locked, not_in_passage, no_change, empty, duplicate, too_many, heading_too_long).`,
inputSchema: {
draft_id: relaxedUuid.describe('Draft UUID.'),
...suggestionsShape,