Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(content): tell a Fix run or hand-off how far past its Length the page is when it isn't asked to shorten it, so what it adds stays short (#1552)
Cihan307670bfc3d3
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.jsindex 19a761ff5..c8be00fd1 100644--- a/server/src/lib/content-agent.js+++ b/server/src/lib/content-agent.js@@ -125,6 +125,17 @@ export const fixRulesInput = z.object({locked: z.array(z.string().max(5000)).max(500).default([]),/** The sources the Sources tab keeps (v1.1 CE-033); none from an older editor. */sources: rebuildSources.optional(),+ /**+ * The page past its Length when Length isn't among the rules (held for the+ * person, or not picked: editor test 2026-10-26): its characters and the+ * most it may have, so what the agent adds for the other rules stays short.+ */+ overLength: z+ .object({+ count: z.number().int().min(0).max(10_000_000),+ max: z.number().int().min(1).max(10_000_000),+ })+ .optional(),});export const suggestionsSchema = z.object({@@ -946,6 +957,17 @@ export function dropsPlaceholder(passage, before, after, tag = 'p') {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 of a page already over its Length that it isn't+ * asked to shorten: fixing the other rules, it adds no more than they need+ * (editor test 2026-10-26: fan-out sections, FAQ answers and H2 answers took a+ * page 26% over its Length further over).+ */+export function overLengthLine(over) {+ if (!over || over.count <= over.max) return '';+ return `The page is already ${over.count.toLocaleString('en-US')} characters, past the most its Length allows (${over.max.toLocaleString('en-US')}). The Length isn't among the rules here, so don't cut the page for it. Fix each rule with as few words as it needs: an answer in one or two sentences, no section, list, table or example a rule doesn't ask for, and a replace no longer than the words it replaces unless the rule needs words added (a keyword, a figure, a name).`;+}+/** What the model is told: the brand, the page's passages, and the rules to fix. */export function buildFixPrompt({brand,@@ -965,6 +987,7 @@ export function buildFixPrompt({if (more) lines.push('(The page goes on; suggest changes only to the passages above.)');const rules = input.rules.map((r) => `- ${r.key}: ${r.name}${r.detail ? ` — ${r.detail}` : ''}`);const own = input.textRules.map((text) => `- ${text}`);+ const over = overLengthLine(input.overLength);return `Brand: ${brand?.name || 'Unknown'}Industry: ${brand?.industry || 'Not specified'}${siteTypeLine(brand)}Description: ${brand?.description || 'N/A'}@@ -974,7 +997,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')}-${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` : ''}+${over ? `${over}\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')}diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.jsindex dae9e8824..7efb206a7 100644--- a/server/src/lib/content-agent.test.js+++ b/server/src/lib/content-agent.test.js@@ -84,6 +84,7 @@ const {dropsPlaceholder,emptyWhy,fixDraftRules,+ fixRulesInput,keepSuggestions,growsPastLimit,htmlLines,@@ -209,6 +210,34 @@ describe('the page as the agent reads it', () => {});});+ it('tells it of a page over its Length it isn’t asked to shorten (editor test 2026-10-26)', () => {+ const prompt = (overLength) =>+ buildFixPrompt({+ brand: { name: 'Acme Coffee', language: 'en' },+ draft: rows.content_drafts,+ passages: draftPassages(BODY),+ lockedKeys: new Set(),+ input: { ...input(), overLength },+ });+ expect(prompt({ count: 17_683, max: 16_798 })).toContain(+ "- faq: FAQ with 5 questions — missing\nThe page is already 17,683 characters, past the most its Length allows (16,798). The Length isn't among the rules here, so don't cut the page for it.",+ );+ // Within its Length, or none sent: nothing said.+ expect(prompt({ count: 9_000, max: 16_798 })).not.toContain('its Length allows');+ expect(prompt(undefined)).not.toContain('its Length allows');+ expect(+ fixRulesInput.parse({ ...input(), overLength: { count: 17_683, max: 16_798 } }),+ ).toMatchObject({+ overLength: { count: 17_683, max: 16_798 },+ });+ expect(() =>+ fixRulesInput.parse({ ...input(), overLength: { count: -1, max: 16_798 } }),+ ).toThrow();+ expect(() =>+ fixRulesInput.parse({ ...input(), overLength: { count: 17_683, max: 0 } }),+ ).toThrow();+ });+it('sends a long page only up to its cap, and no passage too long to change', () => {const long = { tag: 'p', text: 'x'.repeat(5_001) };const passage = { tag: 'p', text: 'y'.repeat(4_000) };diff --git a/server/src/lib/content-handoff.js b/server/src/lib/content-handoff.jsindex 042f33bb4..d963a9b12 100644--- a/server/src/lib/content-handoff.js+++ b/server/src/lib/content-handoff.js@@ -81,6 +81,8 @@ export async function handOffDraft({ draftId, brandId, input }) {textRules: input.textRules,locked: input.locked,...(input.sources ? { sources: input.sources } : {}),+ // Its checks add text too (an FAQ, a specs table, headings).+ ...(input.overLength ? { overLength: input.overLength } : {}),},handoff: { origin: input.origin },});diff --git a/server/src/lib/content-handoff.test.js b/server/src/lib/content-handoff.test.jsindex a288169b1..a06878517 100644--- a/server/src/lib/content-handoff.test.js+++ b/server/src/lib/content-handoff.test.js@@ -80,4 +80,16 @@ describe('handOffDraft', () => {handoff: { origin: 'auto' },});});++ it('passes on a page over its Length, so its checks add as little as they need', async () => {+ const input = handOffInput.parse({+ items: [{ key: 'readability:longSentences', detail: '' }],+ overLength: { count: 17_683, max: 16_798 },+ });+ await handOffDraft({ draftId: 'd1', brandId: 'b1', input });+ expect(fixDraftRules.mock.calls.at(-1)[0].input.overLength).toEqual({+ count: 17_683,+ max: 16_798,+ });+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 866adeb60..66b789c8d 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@@ -171,6 +171,7 @@ import {lengthWarns,notForAgentMessage,openRulesForAgent,+ overLengthFor,lengthBand,rewriteAdvice,NO_RULE_CONTEXT,@@ -2366,8 +2367,11 @@ export function DraftEditor({}),...agentContext(editor),};+ // A page over a Length it isn't sent: what it adds stays short.+ const overLength = overLengthFor(rules.rules, open);await runAgentFix(- () => fixDraftRules(draft.id, draft.brandId, request),+ () =>+ fixDraftRules(draft.id, draft.brandId, overLength ? { ...request, overLength } : request),undefined,false,beginThirdTry(),@@ -2566,6 +2570,8 @@ export function DraftEditor({const cases = casesOn? proofAsks.filter((ask) => ask.kind === 'customer_case').map((ask) => ask.block): [];+ // Its checks add text too: on a page over its Length, kept short.+ const overLength = overLengthFor(rules.rules, []);setHandingOff(true);try {await runAgentFix(@@ -2575,6 +2581,7 @@ export function DraftEditor({origin,...context,locked: [...context.locked, ...cases],+ ...(overLength ? { overLength } : {}),}),handedOff,origin === 'auto',diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 9e4f4ae0a..bc8202402 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -104,6 +104,7 @@ vi.mock('@/lib/supabase/server', () => ({const {createContentDraft,fixDraftRules,+ handOffDraft,decideDraftSuggestions,getDraftSuggestions,getLastRestoreAt,@@ -1105,6 +1106,32 @@ describe('fixDraftRules', () => {vi.unstubAllGlobals();});+ it('sends a hand-off how far over its Length the page is too', async () => {+ const fetchMock = vi.fn(async () => Response.json({ count: 1 }));+ vi.stubGlobal('fetch', fetchMock);+ const overLength = { count: 17_683, max: 16_798 };+ await handOffDraft(DRAFT, BRAND, {+ items: [{ key: 'readability:longSentences', detail: '' }],+ textRules: [],+ locked: [],+ origin: 'person',+ overLength,+ });+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(JSON.parse(init.body as string).overLength).toEqual(overLength);+ vi.unstubAllGlobals();+ });++ it('sends how far over its Length the page is, when the Length rule isn’t sent', async () => {+ const fetchMock = vi.fn(async () => Response.json({ count: 1 }));+ vi.stubGlobal('fetch', fetchMock);+ const overLength = { count: 17_683, max: 16_798 };+ await fixDraftRules(DRAFT, BRAND, { ...request, overLength });+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(JSON.parse(init.body as string)).toEqual({ brandId: BRAND, ...request, overLength });+ vi.unstubAllGlobals();+ });+it('names the budget and the empty page, and anything else as failed', async () => {for (const [body, error] of [[{ code: 'ai_budget' }, 'ai_budget'],diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 4c0f2cf35..3c6200406 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -2321,6 +2321,8 @@ export interface AgentFixRequest {locked: string[];/** The sources the Sources tab keeps, which the agent writes from (v1.1 CE-033). */sources?: RebuildSources;+ /** The page over a Length it isn't sent (rules.ts overLengthFor). */+ overLength?: { count: number; max: number };}/** Why a run left nothing to review (content-agent.js emptyWhy). */@@ -2366,6 +2368,7 @@ export async function fixDraftRules(locked: request.locked.slice(0, 500).map((key) => key.slice(0, 5000)),// Already within the server's limits (rebuildSources)....(request.sources ? { sources: request.sources } : {}),+ ...(request.overLength ? { overLength: request.overLength } : {}),}),});const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;@@ -2437,6 +2440,7 @@ export async function handOffDraft(textRules: request.textRules.slice(0, 50).map((text) => text.slice(0, 300)),locked: request.locked.slice(0, 500).map((key) => key.slice(0, 5000)),...(request.sources ? { sources: request.sources } : {}),+ ...(request.overLength ? { overLength: request.overLength } : {}),origin: request.origin,}),});diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex 9cfc7f01b..575786b2b 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -5,6 +5,7 @@ import {notForAgentMessage,fanoutsToUse,openRulesForAgent,+ overLengthFor,activeRules,effectiveRules,splitRules,@@ -253,6 +254,36 @@ describe('length and structure', () => {expect(heldMessage([{ rule: { key: 'sentence' } }])).toBe('heldAll');});+ it('tells a Fix run of a page over its Length it doesn’t send (editor test 2026-10-26)', () => {+ const rules = activeRules(ruleSet('blog_post'), {+ overrides: { length: { value: '1000' } },+ });+ const statuses = (characters: number) =>+ rules.map((r) => ({+ rule: r,+ status: checkRule(r, page('<h1>T</h1><p>x</p>', characters), ctx),+ }));+ const over = statuses(1_500);+ const { forAgent, held } = openRulesForAgent(over, undefined, new Set(['length']));+ expect(held.map(({ rule }) => rule.key)).toEqual(['length']);+ expect(overLengthFor(over, forAgent)).toEqual({ count: 1_500, max: 1_200 });+ // Sent as a rule, it says so itself; within its Length, or short: nothing.+ expect(overLengthFor(over, openRulesForAgent(over).forAgent)).toBeUndefined();+ // Asked for some rules only, Length not among them; a hand-off, which sends none.+ expect(overLengthFor(over, openRulesForAgent(over, ['faq']).forAgent)).toEqual({+ count: 1_500,+ max: 1_200,+ });+ expect(overLengthFor(over, [])).toEqual({ count: 1_500, max: 1_200 });+ expect(overLengthFor(statuses(1_150), forAgent)).toBeUndefined();+ expect(overLengthFor(statuses(200), forAgent)).toBeUndefined();+ // Length off.+ const off = activeRules(ruleSet('blog_post'), { overrides: { length: { on: false } } }).map(+ (r) => ({ rule: r, status: checkRule(r, page('<h1>T</h1><p>x</p>', 1_500), ctx) }),+ );+ expect(overLengthFor(off, [])).toBeUndefined();+ });+it('reads a rule met without the locked passages as held by them', () => {const sentence = activeRules(ruleSet('blog_post'), {overrides: { sentence: { value: '20' } },diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex 0e5baa029..057652330 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -815,6 +815,25 @@ export function openRulesForAgent<T extends { rule: ActiveRule; status: RuleStat/** No rule held by what the page keeps. */export const NO_HELD: ReadonlySet<string> = new Set();+/**+ * A page past its Length when a Fix run doesn't send the Length rule (held+ * for the person, or not picked; a hand-off sends none: editor test+ * 2026-10-26): its characters and the most it may have, so what the agent+ * adds for the other rules stays short. Undefined with Length off, within+ * it, or sent.+ */+export function overLengthFor<T extends { rule: ActiveRule; status: RuleStatus }>(+ rules: T[],+ sent: readonly { rule: ActiveRule }[],+): { count: number; max: number } | undefined {+ const length = rules.find(({ rule }) => rule.key === 'length' && rule.on);+ if (!length || sent.some(({ rule }) => rule.key === 'length')) return undefined;+ const { status } = length;+ return status.state === 'bad' && 'code' in status && status.code === 'long'+ ? { count: status.count, max: status.max }+ : undefined;+}+/*** What to say when only held rules are left for the agent: the quoted* passages' (a sentence in one), else the Length's, out of a rewrite's reach.