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): stop recommending a page rewrite for a Length it can't reach, and offer one it can (#1514)

Cihan9f5bb0e01e90
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.js
index b0d417a6a..432e3e3c6 100644
--- a/server/src/lib/content-writer.js
+++ b/server/src/lib/content-writer.js
@@ -616,6 +616,11 @@ async function rewritePage({
after_text: html,
reason: clean(stripSourceIds(object.reason)).slice(0, 300) || 'Rewrote the page to the rules',
rule_keys: [...ruleKeys],
+ // What it was asked for and came to (00285): a Length it missed isn't
+ // offered again. With Length off, it was asked for none.
+ length_target: ruleKeys.has('length') ? length : null,
+ kept_chars: page.keptChars,
+ after_chars: textLength(html),
...(sources.length ? { sources } : {}),
});
if (insertError) throw insertError;
diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.js
index c9cb546dd..796c3aa5c 100644
--- a/server/src/lib/content-writer.test.js
+++ b/server/src/lib/content-writer.test.js
@@ -740,6 +740,10 @@ describe('Rewrite the page to these rules', () => {
before_html: existing.body_html,
reason: 'cut to about 3,000 characters',
rule_keys: ['length', 'faq'],
+ // What it was asked for and came to (00285): the kept passage and table count.
+ length_target: 3000,
+ kept_chars: textLength(`${QUOTED} Ratio 1:16`),
+ after_chars: textLength(row.after_text),
});
expect(row.after_text).toBe(
`<h1>Pour-over coffee</h1><p>${QUOTED}</p><p>Use good coffee, freshly ground.</p>` +
@@ -766,6 +770,8 @@ describe('Rewrite the page to these rules', () => {
});
await expect(run()).resolves.toEqual({ rewritten: true });
const row = writes.find((w) => w.table === 'content_draft_suggestions').value;
+ // Length off: it was asked for none (00285).
+ expect(row.length_target).toBeNull();
// The fan-out it named; S7 isn't on the list.
expect(row.sources).toEqual([
{ kind: 'fanout', ref: 'pour over ratio', label: 'pour over ratio' },
diff --git a/supabase/migrations/00285_content_page_rewrite_reach.sql b/supabase/migrations/00285_content_page_rewrite_reach.sql
new file mode 100644
index 000000000..112c067ec
--- /dev/null
+++ b/supabase/migrations/00285_content_page_rewrite_reach.sql
@@ -0,0 +1,34 @@
+-- ============================================================================
+-- 00285: what a page rewrite was asked for and came to (Length's reach)
+-- ============================================================================
+-- In the live editor test of 2026-10-25, a page kept 78% of its Length in
+-- passages AI answers quote and tables, and the editor kept recommending
+-- Rewrite page: three rewrites came to 5,468, 6,843 and 7,335 characters for
+-- a Length of 4,000. A rewrite that missed isn't offered again for the same
+-- Length, so a page rewrite (kind 'page', 00247) now says:
+--
+-- * `length_target`: the Length it was written to; null with Length off
+-- (the page kept its own length, which says nothing about a Length).
+-- * `kept_chars`: the characters it kept word for word (quoted passages,
+-- tables…): a passage unlocked since lets a rewrite go shorter.
+-- * `after_chars`: the characters it came to, counted once here, so the
+-- editor reads a number, not the rewritten page.
+--
+-- All three are written by the API (content-writer.js) and are null on other
+-- suggestions and on page rewrites made before this. Adding nullable columns
+-- with no default rewrites nothing.
+
+alter table public.content_draft_suggestions
+ add column if not exists length_target integer
+ check (length_target is null or length_target > 0),
+ add column if not exists kept_chars integer
+ check (kept_chars is null or kept_chars >= 0),
+ add column if not exists after_chars integer
+ check (after_chars is null or after_chars >= 0);
+
+comment on column public.content_draft_suggestions.length_target is
+ 'A page rewrite''s Length target (00285); null with Length off and on other suggestions.';
+comment on column public.content_draft_suggestions.kept_chars is
+ 'The characters a page rewrite kept word for word (00285).';
+comment on column public.content_draft_suggestions.after_chars is
+ 'The characters a page rewrite came to (00285).';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 9111682ca..476fe39d7 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -40178,3 +40178,41 @@ grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uu
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00285_content_page_rewrite_reach.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00285: what a page rewrite was asked for and came to (Length's reach)
+-- ============================================================================
+-- In the live editor test of 2026-10-25, a page kept 78% of its Length in
+-- passages AI answers quote and tables, and the editor kept recommending
+-- Rewrite page: three rewrites came to 5,468, 6,843 and 7,335 characters for
+-- a Length of 4,000. A rewrite that missed isn't offered again for the same
+-- Length, so a page rewrite (kind 'page', 00247) now says:
+--
+-- * `length_target`: the Length it was written to; null with Length off
+-- (the page kept its own length, which says nothing about a Length).
+-- * `kept_chars`: the characters it kept word for word (quoted passages,
+-- tables…): a passage unlocked since lets a rewrite go shorter.
+-- * `after_chars`: the characters it came to, counted once here, so the
+-- editor reads a number, not the rewritten page.
+--
+-- All three are written by the API (content-writer.js) and are null on other
+-- suggestions and on page rewrites made before this. Adding nullable columns
+-- with no default rewrites nothing.
+
+alter table public.content_draft_suggestions
+ add column if not exists length_target integer
+ check (length_target is null or length_target > 0),
+ add column if not exists kept_chars integer
+ check (kept_chars is null or kept_chars >= 0),
+ add column if not exists after_chars integer
+ check (after_chars is null or after_chars >= 0);
+
+comment on column public.content_draft_suggestions.length_target is
+ 'A page rewrite''s Length target (00285); null with Length off and on other suggestions.';
+comment on column public.content_draft_suggestions.kept_chars is
+ 'The characters a page rewrite kept word for word (00285).';
+comment on column public.content_draft_suggestions.after_chars is
+ 'The characters a page rewrite came to (00285).';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 664c68155..6bdfbf1b9 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -5265,7 +5265,10 @@
"length": "Recommended: the page is {count, number} characters for a Length of {target, number} ({percent, number}% off). A rewrite gets there in one go.",
"open": "Recommended: {count, number} rules are open. A rewrite meets them together."
},
- "lengthOutOfReach": "The page is {count, number} characters for a Length of {target, number}, but {kept, number} of them are passages AI answers quote, tables and other blocks a rewrite keeps as they are. Raise the Length to about {suggested, number}, or unlock passages you're fine to have reworded.",
+ "lengthOutOfReach": "The page is {count, number} characters for a Length of {target, number}, but a rewrite can't go much under {least, number}: {kept, number} are passages AI answers quote, tables and other blocks it keeps as they are, and each heading needs its answer. Raise the Length to about {suggested, number}, or unlock passages you're fine to have reworded.",
+ "lengthOutOfReachRun": "The page is {count, number} characters for a Length of {target, number}. The last rewrite came to {least, number}, so another won't get there. Raise the Length to about {suggested, number}, or unlock passages you're fine to have reworded.",
+ "lengthOutOfReachHeadings": "The page is {count, number} characters for a Length of {target, number}, but its headings and an answer under each come to about {least, number}. Raise the Length to about {suggested, number}, or use fewer sections.",
+ "raiseLength": "Raise Length to {suggested, number}",
"lengthConflict": "The fan-out H2s, FAQ questions and summary these rules still ask for take about {need, number} characters, more than Length allows (up to {max, number}). Raise Length, or ask for fewer.",
"fixTrace": "Fix",
"fixTraceHint": "Content Agent rewrites only these phrases, for you to review",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
index 9bf6364a9..a9f5ed8bf 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.test.tsx
@@ -237,12 +237,18 @@ describe('AgentCard', () => {
afterText: '<h1>New</h1><p>Shorter.</p>',
reason: 'shortened the content to about 4 characters',
});
- // 12 characters for a Length of 4 (3–5): missed, most of it kept.
- await render([page], false, { length: { target: 4, min: 3, max: 5, kept: 4 } });
+ // 12 characters for a Length of 4 (3–5): missed, and what it keeps puts it out of reach.
+ await render([page], false, {
+ length: { target: 4, min: 3, max: 5, kept: 4, outOfReach: true },
+ });
expect(container.textContent).toContain(
'37 → 12 characters · Length 4 not reached (4 characters are passages AI answers quote, tables and other blocks a rewrite keeps as they are)',
);
expect(container.textContent).not.toContain('shortened the content');
+ // Something kept, but not why it missed: not named as the reason.
+ await render([page], false, { length: { target: 4, min: 3, max: 5, kept: 4 } });
+ expect(container.textContent).toContain('37 → 12 characters · Length 4 not reached');
+ expect(container.textContent).not.toContain('characters are passages AI answers quote');
// Within the Length: the agent's own words.
await render([page], false, { length: { target: 12, min: 10, max: 14, kept: 0 } });
expect(container.textContent).toContain(
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
index e128ce429..1de361c22 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-card.tsx
@@ -12,7 +12,6 @@ import {
type SuggestionStatus,
} from '@/lib/content/suggestions';
import { shownSteps, stepMessage, type AgentRun } from '@/lib/content/agent-runs';
-import { KEPT_LENGTH_SHARE } from '@/lib/content/rules';
import { cn } from '@/lib/utils';
import { PageCompareDialog, pageCharacters } from './_page-rewrite';
import { WorkingDots } from './_working-dots';
@@ -264,7 +263,14 @@ export function AgentCard({
* The page's Length rule (its target and band) and what a rewrite keeps
* as it is: a rewrite's result is read against it, never the agent's say.
*/
- length?: { target: number; min: number; max: number; kept: number } | null;
+ length?: {
+ target: number;
+ min: number;
+ max: number;
+ kept: number;
+ /** What the rewrite keeps puts the Length out of its reach (rules.ts lengthOutOfReach). */
+ outOfReach?: boolean;
+ } | null;
}) {
const t = useTranslations('contentEditor.editor.agentCard');
const locale = useLocale();
@@ -375,7 +381,8 @@ export function AgentCard({
<span className="text-amber-700 dark:text-amber-400">
{tRewrite('lengthMissed', { target: missed.target })}
{afterChars > missed.max &&
- missed.kept >= missed.target * KEPT_LENGTH_SHARE &&
+ missed.outOfReach &&
+ missed.kept > 0 &&
` ${tRewrite('lengthKept', { kept: missed.kept })}`}
</span>
) : (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts
index fa963f237..648738aad 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.test.ts
@@ -8,6 +8,7 @@ import {
citedPassagesKey,
keptCharacters,
lockedPassageCount,
+ rewriteFloor,
type HeldEdit,
} from './_cited-passages';
@@ -85,6 +86,75 @@ describe('keptCharacters', () => {
});
});
+describe('rewriteFloor', () => {
+ it('adds the headings and the least answer where nothing kept stands to what a rewrite keeps', () => {
+ const quote = 'A customer said it saved them a week.';
+ const small = new Editor({
+ extensions: [StarterKit, CitedPassages.configure({ onHeld: () => {} })],
+ content:
+ '<h1>Title</h1><p>Summary to rewrite.</p>' +
+ `<h2>Tool A</h2><p>${QUOTED}</p>` +
+ `<h2>Tool B</h2><p>Plain answer.</p><blockquote><p>${quote}</p></blockquote>` +
+ '<h3>Questions?</h3><p>Plain too.</p>',
+ });
+ try {
+ const lock = (unlocked: string[] = []) =>
+ small.view.dispatch(
+ small.state.tr.setMeta(citedPassagesKey, {
+ labels: new Map([[passageKey(QUOTED), 'Cited by ChatGPT 3×']]),
+ unlocked: new Set(unlocked),
+ }),
+ );
+ lock();
+ const kept = QUOTED.length + quote.length;
+ const headings = 'Title'.length + 'Tool A'.length + 'Tool B'.length + 'Questions?'.length;
+ // The quoted passage answers Tool A; a quote doesn't answer Tool B; the
+ // summary and the question need theirs.
+ expect(rewriteFloor(small.state, { summary: true })).toEqual({
+ kept,
+ floor: kept + headings + 100 * 3,
+ });
+ // No summary asked for: none counted.
+ expect(rewriteFloor(small.state, { summary: false }).floor).toBe(kept + headings + 100 * 2);
+ // Unlocked: Tool A's answer is the rewrite's to write.
+ lock([passageKey(QUOTED)]);
+ expect(rewriteFloor(small.state, { summary: true })).toEqual({
+ kept: quote.length,
+ floor: quote.length + headings + 100 * 4,
+ });
+ } finally {
+ small.destroy();
+ }
+ });
+
+ it('takes a quoted passage in a quote as the answer, and asks none of a heading over deeper ones', () => {
+ const small = new Editor({
+ extensions: [StarterKit, CitedPassages.configure({ onHeld: () => {} })],
+ content:
+ '<h1>Title</h1>' +
+ // An empty paragraph under Tools still leaves it a heading that groups.
+ `<h2>Tools</h2><p></p><h3>Tool A</h3><blockquote><p>${QUOTED}</p></blockquote>` +
+ '<h3>Tool B</h3><p>Plain.</p>',
+ });
+ try {
+ small.view.dispatch(
+ small.state.tr.setMeta(citedPassagesKey, {
+ labels: new Map([[passageKey(QUOTED), 'Cited by ChatGPT 3×']]),
+ unlocked: new Set(),
+ }),
+ );
+ const headings = 'Title'.length + 'Tools'.length + 'Tool A'.length + 'Tool B'.length;
+ // Tools groups; Tool A's answer is the quoted passage; only Tool B needs one.
+ expect(rewriteFloor(small.state, { summary: false })).toEqual({
+ kept: QUOTED.length,
+ floor: QUOTED.length + headings + 100,
+ });
+ } finally {
+ small.destroy();
+ }
+ });
+});
+
describe('locked passages', () => {
it('marks the quoted passage and counts it', () => {
expect(lockedPassageCount(editor.state)).toBe(1);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
index 39e4ff990..103715c60 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_cited-passages.ts
@@ -4,6 +4,7 @@ import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/p
import { Mapping } from '@tiptap/pm/transform';
import { Decoration, DecorationSet } from '@tiptap/pm/view';
import { passageKey } from '@/lib/content/cited-passages';
+import { LEAST_ANSWER, LEAST_SUMMARY } from '@/lib/content/rules';
/**
* Locked passages in the editor (CE-018): a passage AI answers quote today
@@ -189,6 +190,63 @@ export function keptCharacters(state: EditorState): number {
return kept;
}
+/**
+ * The least a page rewrite comes to, for Length's reach (rules.ts
+ * RewriteReach): what it keeps (keptCharacters), each heading (a rewrite
+ * keeps the sections, content-rewrite.js), and, at their least, an answer
+ * under each heading (it answers each first) and a summary under the H1
+ * (when the rules ask for one) where no kept passage stands there already.
+ * Low on purpose, so a Length called out of reach really is.
+ */
+export function rewriteFloor(
+ state: EditorState,
+ { summary }: { summary: boolean },
+): { kept: number; floor: number } {
+ const locks = citedLocks(state);
+ let kept = 0;
+ let floor = 0;
+ // The section open now: under a heading (its level), or the H1's summary;
+ // null before the H1. `empty` until a block stands under it.
+ let section: { level: number; least: number; answered: boolean; empty: boolean } | null = null;
+ const close = (next: number) => {
+ // A heading that only groups the deeper ones under it (an H2 over H3s)
+ // needs no answer of its own.
+ const grouping = section && section.empty && section.level > 1 && next > section.level;
+ if (section && !section.answered && !grouping) floor += section.least;
+ };
+ state.doc.forEach((block) => {
+ const text = () => block.textBetween(0, block.content.size, undefined, ' ').length;
+ const locked = block.isTextblock && isLocked(blockKey(block), locks);
+ if (block.type.name === 'heading') {
+ const level = Number(block.attrs.level);
+ close(level);
+ if (locked) kept += text();
+ else floor += text();
+ section =
+ level === 1
+ ? { level, least: summary ? LEAST_SUMMARY : 0, answered: !summary, empty: true }
+ : { level, least: LEAST_ANSWER, answered: false, empty: true };
+ return;
+ }
+ // An empty paragraph between an H2 and its H3s doesn't make it a section of its own.
+ if (section && (!block.isTextblock || block.textContent.trim())) section.empty = false;
+ let keep = KEPT_NODES.has(block.type.name) || locked;
+ // A quoted passage stands as the answer, in a list or a quote too; a
+ // table or an image alone doesn't.
+ let answers = locked;
+ block.descendants((node) => {
+ if (node.type.name === 'image' || node.type.name === 'table') keep = true;
+ else if (node.isTextblock && isLocked(blockKey(node), locks)) keep = answers = true;
+ return !answers;
+ });
+ if (!keep) return;
+ kept += text();
+ if (answers && section) section.answered = true;
+ });
+ close(0);
+ return { kept, floor: kept + floor };
+}
+
/** How many quoted passages the page has now (the marks the plugin keeps). */
export function lockedPassageCount(state: EditorState): number {
return citedPassagesKey.getState(state)?.marks.find().length ?? 0;
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 9766dadf1..4fdc78112 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
@@ -40,6 +40,7 @@ import {
type HandOffError,
getCitedPassages,
getDraftSuggestions,
+ getLastPageRewrite,
keepAgentBeforeVersion,
markContentDraftReady,
unmarkContentDraftReady,
@@ -167,7 +168,10 @@ import {
openRulesForAgent,
lengthBand,
rewriteAdvice,
+ keptOutOfReach,
type ActiveRule,
+ type LastRewrite,
+ type RewriteReach,
type RuleStatus,
} from '@/lib/content/rules';
import { aiUsageTone } from '@/lib/billing/ai-usage';
@@ -191,8 +195,8 @@ import {
CitedPassages,
citedLocks,
citedPassagesKey,
- keptCharacters,
lockedPassageCount,
+ rewriteFloor,
type HeldEdit,
} from './_cited-passages';
import { ExportDialog, type ExportDestination } from './_export-dialog';
@@ -606,8 +610,13 @@ export function DraftEditor({
catalog: feedOn ? (catalog === undefined ? 'reading' : catalog) : null,
});
// What a page rewrite keeps as it is (the passages AI answers quote, tables,
- // images…), read as the characters are: a Length under it is out of reach.
- const keptChars = editor && citedRead ? keptCharacters(editor.state) : 0;
+ // images…), read as the characters are, and the least it comes to with the
+ // headings and their answers: a Length under that is out of reach.
+ const summaryAsked = rules.rules.some(({ rule }) => rule.key === 'summary' && rule.on);
+ const { kept: keptChars, floor: floorChars } =
+ editor && citedRead
+ ? rewriteFloor(editor.state, { summary: summaryAsked })
+ : { kept: 0, floor: 0 };
// The Length the page is written to, for what the agent's rewrite reached.
const lengthRule = rules.rules.find(({ rule }) => rule.key === 'length' && rule.on)?.rule;
const lengthTarget = Number(lengthRule?.current);
@@ -1807,6 +1816,23 @@ export function DraftEditor({
};
const openSuggestions = suggestions.filter((s) => s.status === 'open').length;
const pageSuggestion = suggestions.find((s) => s.kind === 'page') ?? null;
+ // The page's last rewrite, from any run (00285), read on opening and again
+ // once a new one is shown: a Length it missed isn't a rewrite's to reach
+ // (rules.ts RewriteReach). A later Fix run's batch doesn't hide it.
+ const [lastRewrite, setLastRewrite] = useState<LastRewrite | null>(null);
+ const shownRewriteId = pageSuggestion?.id ?? null;
+ useEffect(() => {
+ let cancelled = false;
+ getLastPageRewrite(draft.id)
+ .then((last) => {
+ if (!cancelled) setLastRewrite(last);
+ })
+ .catch((err) => console.error("Failed to read the page's last rewrite:", err));
+ return () => {
+ cancelled = true;
+ };
+ }, [draft.id, shownRewriteId]);
+ const reach: RewriteReach = { kept: keptChars, floor: floorChars, last: lastRewrite };
// The rules as the agent card counts its gain: met now, and the ones still open.
const cardRules = useMemo(
() => ({
@@ -2664,7 +2690,7 @@ export function DraftEditor({
? {
run: () => void rewritePage(),
running: rewriting,
- kept: keptChars,
+ reach,
blocked:
aiUsedUp && !rewriting
? aiUsedUp
@@ -2815,7 +2841,7 @@ export function DraftEditor({
published: status === 'published',
hasBrief: reads.brief.status === 'ready' ? reads.brief.brief !== null : null,
empty: !pageHasWords,
- rewrite: rewriteAdvice(rules.rules, keptChars),
+ rewrite: rewriteAdvice(rules.rules, reach),
openRules: rulesForNext(rules.rules),
quality: quality
? { trust: trustNow, trustLow: trustNow !== null && trustNow < TRUST_GATE, todos }
@@ -3510,7 +3536,8 @@ export function DraftEditor({
}
: null
}
- length={length}
+ // The kept blocks are named only when they put the Length out of reach.
+ length={length && { ...length, outOfReach: keptOutOfReach(rules.rules, reach) }}
onAllSteps={() => {
setNextFocus(true);
setNextOpen(true);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
index b37dfb31d..369f8c892 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
@@ -165,13 +165,56 @@ describe('the Rules tab', () => {
expect(main().textContent).toBe('Run Agent');
});
- it('says when the Length is out of a rewrite’s reach for what it keeps, recommending none for it', async () => {
- // 15,921 characters for 3,000, 2,900 of them passages AI answers quote and tables.
- await show({ agentFix: fix(), pageRewrite: { ...fix(), kept: 2_900 } });
+ it('says when the Length is out of a rewrite’s reach, recommending none for it, with a Length it can reach', async () => {
+ // 15,921 characters for 3,000 (up to 3,600): a rewrite keeping 2,900 can't go under 3,900.
+ await show({
+ agentFix: fix(),
+ pageRewrite: { ...fix(), reach: { kept: 2_900, floor: 3_900, last: null } },
+ });
+ const notes = () =>
+ [...container.querySelectorAll('[role="note"]')].map((n) => n.textContent ?? '');
+ expect(notes().some((n) => n.startsWith('Recommended: the page is'))).toBe(false);
+ expect(notes()).toContainEqual(
+ expect.stringContaining(
+ "The page is 15,921 characters for a Length of 3,000, but a rewrite can't go much under 3,900: 2,900 are passages AI answers quote, tables and other blocks it keeps as they are, and each heading needs its answer. Raise the Length to about 4,000, or unlock passages you're fine to have reworded.",
+ ),
+ );
+ change.mockClear();
+ await act(async () =>
+ buttons()
+ .find((b) => b.textContent === 'Raise Length to 4,000')!
+ .click(),
+ );
+ expect(change).toHaveBeenCalledWith('length', { value: '4000' });
+ });
+
+ it('doesn’t offer a rewrite again for a Length the last one missed', async () => {
+ await show({
+ agentFix: fix(),
+ pageRewrite: {
+ ...fix(),
+ reach: { kept: 900, floor: 1_500, last: { chars: 9_800, target: 3_000, kept: 900 } },
+ },
+ });
const notes = [...container.querySelectorAll('[role="note"]')].map((n) => n.textContent);
expect(notes.some((n) => n?.startsWith('Recommended: the page is'))).toBe(false);
expect(notes).toContainEqual(
- "The page is 15,921 characters for a Length of 3,000, but 2,900 of them are passages AI answers quote, tables and other blocks a rewrite keeps as they are. Raise the Length to about 4,500, or unlock passages you're fine to have reworded.",
+ expect.stringContaining(
+ "The page is 15,921 characters for a Length of 3,000. The last rewrite came to 9,800, so another won't get there. Raise the Length to about 10,000",
+ ),
+ );
+ });
+
+ it('says so of the headings alone, when nothing is kept', async () => {
+ await show({
+ agentFix: fix(),
+ pageRewrite: { ...fix(), reach: { kept: 0, floor: 3_700, last: null } },
+ });
+ const notes = [...container.querySelectorAll('[role="note"]')].map((n) => n.textContent);
+ expect(notes).toContainEqual(
+ expect.stringContaining(
+ 'but its headings and an answer under each come to about 3,700. Raise the Length to about 4,000, or use fewer sections.',
+ ),
);
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
index 709a81fea..c373872c2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
@@ -31,6 +31,7 @@ import { isPageType, type PageType } from '@/lib/content/drafts';
import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';
import {
MAX_TEXT_RULE_LENGTH,
+ NO_REACH,
RULE_GROUPS,
notForAgentMessage,
openRulesForAgent,
@@ -38,6 +39,7 @@ import {
rewriteAdvice,
splitRules,
type ActiveRule,
+ type RewriteReach,
type RuleStatus,
type TextRule,
} from '@/lib/content/rules';
@@ -87,8 +89,8 @@ export interface PageRewrite {
running: boolean;
/** Why it can't run now (suggestions still open), or null. */
blocked: string | null;
- /** The characters it keeps as they are (keptCharacters): a Length under them is out of reach. */
- kept?: number;
+ /** What it keeps, the least it comes to and what the last one came to: a Length under them is out of reach. */
+ reach?: RewriteReach;
}
/** Run Agent's two ways: the open rules fixed a few passages at a time, or the whole page. */
@@ -248,9 +250,11 @@ export function RulesTab({
];
// Rewrite the page whole when small edits can't get there.
- const advice = pageRewrite ? rewriteAdvice(state.rules, pageRewrite.kept ?? 0) : null;
- // A Length the rewrite can't reach for what it keeps: said, never recommended.
- const outOfReach = pageRewrite ? lengthOutOfReach(state.rules, pageRewrite.kept ?? 0) : null;
+ const advice = pageRewrite ? rewriteAdvice(state.rules, pageRewrite.reach) : null;
+ // A Length the rewrite can't reach: said with a Length it can, never recommended.
+ const outOfReach = pageRewrite
+ ? lengthOutOfReach(state.rules, pageRewrite.reach ?? NO_REACH)
+ : null;
// The rules the page doesn't meet now, in the tab's order, and those the agent fixes.
const open = state.rules.filter(({ rule, status }) => rule.on && status.state === 'bad');
const { forAgent, notForAgent } = openRulesForAgent(state.rules);
@@ -336,10 +340,35 @@ export function RulesTab({
</p>
)}
{outOfReach && (
- <p className="flex gap-1.5 text-xs" role="note">
+ <div className="flex gap-1.5 text-xs" role="note">
<Info aria-hidden className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />
- <span>{t('lengthOutOfReach', { ...outOfReach })}</span>
- </p>
+ <div className="min-w-0 space-y-1.5">
+ <p>
+ {t(
+ outOfReach.why === 'reached'
+ ? 'lengthOutOfReachRun'
+ : outOfReach.kept > 0
+ ? 'lengthOutOfReach'
+ : 'lengthOutOfReachHeadings',
+ {
+ count: outOfReach.count,
+ target: outOfReach.target,
+ kept: outOfReach.kept,
+ least: outOfReach.least,
+ suggested: outOfReach.suggested,
+ },
+ )}
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7 text-xs"
+ onClick={() => state.change('length', { value: String(outOfReach.suggested) })}
+ >
+ {t('raiseLength', { suggested: outOfReach.suggested })}
+ </Button>
+ </div>
+ </div>
)}
</RunCard>
)}
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 a2cf1bb1b..1837203b2 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
@@ -72,6 +72,8 @@ const getDraftHandoffs = vi.fn();
const restoreDraftVersion = vi.fn();
const getCitedPassages = vi.fn();
const getDraftSuggestions = vi.fn();
+// What the page's last rewrite came to (Length's reach): none unless a test gives one.
+const getLastPageRewrite = vi.fn();
const decideDraftSuggestions = vi.fn();
const keepAgentBeforeVersion = vi.fn();
const fixDraftRules = vi.fn();
@@ -87,6 +89,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({
startAgentWriting: (...args: unknown[]) => startAgentWriting(...args),
startPageRewrite: (...args: unknown[]) => startPageRewrite(...args),
getDraftSuggestions: (...args: unknown[]) => getDraftSuggestions(...args),
+ getLastPageRewrite: (...args: unknown[]) => getLastPageRewrite(...args),
decideDraftSuggestions: (...args: unknown[]) => decideDraftSuggestions(...args),
keepAgentBeforeVersion: (...args: unknown[]) => keepAgentBeforeVersion(...args),
getCitedPassages: (...args: unknown[]) => getCitedPassages(...args),
@@ -369,6 +372,7 @@ beforeEach(() => {
restoreDraftVersion.mockReset();
getCitedPassages.mockReset().mockResolvedValue([]);
getDraftSuggestions.mockReset().mockResolvedValue([]);
+ getLastPageRewrite.mockReset().mockResolvedValue(null);
decideDraftSuggestions.mockReset().mockResolvedValue(1);
keepAgentBeforeVersion.mockReset().mockResolvedValue(undefined);
fixDraftRules.mockReset().mockResolvedValue({ count: 0 });
@@ -6622,6 +6626,8 @@ describe('the side panel', () => {
it('sends the rules in effect, how the page reads against each, and the page waits', async () => {
getContentDraft.mockResolvedValue(long);
await openRules();
+ // What the last rewrite came to is read once, for Length's reach.
+ expect(getLastPageRewrite).toHaveBeenCalledWith('d1');
// ▾ › Rewrite the whole page: the button says so, then runs it.
await act(async () =>
@@ -6657,6 +6663,8 @@ describe('the side panel', () => {
await act(async () => {});
expect(bar()!.textContent).toContain('Content Agent rewrote the page to its rules');
+ // What the last rewrite came to is read on opening, and again for the one now shown.
+ expect(getLastPageRewrite).toHaveBeenCalledTimes(2);
// A whole page is never a card in the page.
expect(container.querySelector('[data-suggestion]')).toBeNull();
await act(async () => button(bar()!, 'Compare').click());
diff --git a/web/src/lib/actions/content-drafts-rewrite.test.ts b/web/src/lib/actions/content-drafts-rewrite.test.ts
new file mode 100644
index 000000000..00245dc7c
--- /dev/null
+++ b/web/src/lib/actions/content-drafts-rewrite.test.ts
@@ -0,0 +1,65 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The draft's last page rewrite, as the API keeps it (00285): numbers only,
+ * none for a rewrite made before them.
+ */
+
+const DRAFT = '2f1d1c52-0f7a-4c1e-9b8a-5d6e7f8a9b0c';
+let row: Record<string, unknown> | null;
+let filters: [string, unknown][];
+let selected: string;
+
+vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: () => {
+ const chain: Record<string, unknown> = {
+ select: (cols: string) => ((selected = cols), chain),
+ eq: (col: string, value: unknown) => (filters.push([col, value]), chain),
+ order: () => chain,
+ limit: () => chain,
+ maybeSingle: async () => ({ data: row, error: null }),
+ };
+ return chain;
+ },
+ })),
+}));
+
+const { getLastPageRewrite } = await import('./content-drafts');
+
+beforeEach(() => {
+ row = null;
+ filters = [];
+ selected = '';
+});
+
+describe('getLastPageRewrite', () => {
+ it('reads the numbers of the latest page rewrite, not the page', async () => {
+ row = { after_chars: 5_468, length_target: 4_000, kept_chars: 3_125 };
+ await expect(getLastPageRewrite(DRAFT)).resolves.toEqual({
+ chars: 5_468,
+ target: 4_000,
+ kept: 3_125,
+ });
+ expect(selected).toBe('after_chars, length_target, kept_chars');
+ expect(filters).toEqual([
+ ['draft_id', DRAFT],
+ ['kind', 'page'],
+ ]);
+ });
+
+ it('says nothing for none, or for one made before 00285; Length off keeps its null', async () => {
+ await expect(getLastPageRewrite(DRAFT)).resolves.toBeNull();
+ row = { after_chars: null, length_target: null, kept_chars: null };
+ await expect(getLastPageRewrite(DRAFT)).resolves.toBeNull();
+ row = { after_chars: 6_000, length_target: null, kept_chars: 900 };
+ await expect(getLastPageRewrite(DRAFT)).resolves.toEqual({
+ chars: 6_000,
+ target: null,
+ kept: 900,
+ });
+ await expect(getLastPageRewrite('nope')).rejects.toThrow('invalid');
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 6e82e3e38..4e469a597 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -55,6 +55,7 @@ import {
savedRuleSetSchema,
startingRules,
type DraftRulesInput,
+ type LastRewrite,
type SavedRuleSet,
} from '@/lib/content/rules';
import {
@@ -1853,6 +1854,29 @@ export async function keepAgentBeforeVersion(id: string): Promise<void> {
await keepVersion(supabase, id, 'agent_before');
}
+/**
+ * The draft's last page rewrite, whatever became of it, as the API kept it
+ * (00285): the characters it came to, the Length it was written to and what
+ * it kept. A Length it missed isn't offered again (rules.ts RewriteReach).
+ * Numbers only: the rewritten page isn't read for them. Null without one,
+ * or for one made before 00285.
+ */
+export async function getLastPageRewrite(id: string): Promise<LastRewrite | null> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_draft_suggestions')
+ .select('after_chars, length_target, kept_chars')
+ .eq('draft_id', id)
+ .eq('kind', 'page')
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data || data.after_chars === null || data.kept_chars === null) return null;
+ return { chars: data.after_chars, target: data.length_target, kept: data.kept_chars };
+}
+
/**
* An agent's suggestions on the draft (CE-018, 00217): its latest batch, in
* the order the agent left them, with the Action Center action it came from.
diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.ts
index 89dde6448..eb98e642f 100644
--- a/web/src/lib/content/rules.test.ts
+++ b/web/src/lib/content/rules.test.ts
@@ -30,6 +30,7 @@ import {
RULE_LENGTH_MIN,
RULE_LENGTH_MAX,
lengthBand,
+ keptOutOfReach,
lengthOutOfReach,
rewriteAdvice,
type RuleStatus,
@@ -798,28 +799,94 @@ describe('rewriteAdvice', () => {
expect(rewriteAdvice(statuses(60_001))).toBeNull();
});
- it("doesn't recommend shortening a page whose kept blocks are most of its Length", () => {
- // The user's page: 6,877 characters for 4,000, 3,799 of them quoted passages and tables.
+ it("doesn't recommend shortening a page a rewrite can't bring under its Length", () => {
const page = statuses(6_877, [], '4000');
- expect(rewriteAdvice(page, 3_799)).toBeNull();
- expect(lengthOutOfReach(page, 3_799)).toEqual({
+ // The least a rewrite comes to (kept + headings + least answers) past the band's top (4,800).
+ const floor = { kept: 3_799, floor: 5_100, last: null };
+ expect(rewriteAdvice(page, floor)).toBeNull();
+ expect(lengthOutOfReach(page, floor)).toEqual({
count: 6_877,
target: 4_000,
kept: 3_799,
- suggested: 6_000,
+ why: 'floor',
+ least: 5_100,
+ suggested: 5_500,
});
// Little kept: a rewrite still gets there.
- expect(rewriteAdvice(page, 1_000)).toMatchObject({ reason: 'length' });
- expect(lengthOutOfReach(page, 1_000)).toBeNull();
+ expect(rewriteAdvice(page, { kept: 1_000, floor: 1_800, last: null })).toMatchObject({
+ reason: 'length',
+ });
// Many rules open: still a rewrite, for them, the Length out of reach not among them.
expect(
- rewriteAdvice(statuses(6_877, ['faq', 'summary', 'h2Answer'], '4000'), 3_799),
+ rewriteAdvice(statuses(6_877, ['faq', 'summary', 'h2Answer'], '4000'), floor),
).toBeNull();
expect(
- rewriteAdvice(statuses(6_877, ['faq', 'summary', 'h2Answer', 'keywords'], '4000'), 3_799),
+ rewriteAdvice(statuses(6_877, ['faq', 'summary', 'h2Answer', 'keywords'], '4000'), floor),
).toMatchObject({ reason: 'open' });
// Under its Length, what is kept doesn't stop it.
- expect(lengthOutOfReach(statuses(2_000, [], '4000'), 3_799)).toBeNull();
+ expect(lengthOutOfReach(statuses(2_000, [], '4000'), floor)).toBeNull();
+ });
+
+ it('doesn’t offer a rewrite again for a Length the last one missed, and only then', () => {
+ const page = statuses(6_877, [], '4000');
+ // The user's test page (2026-10-25): 78% kept, so in reach by its kept blocks
+ // alone, but the last rewrite, written to 4,000, came to 5,468.
+ const missed = { chars: 5_468, target: 4_000, kept: 3_125 };
+ const run = { kept: 3_125, floor: 4_300, last: missed };
+ expect(rewriteAdvice(page, run)).toBeNull();
+ expect(lengthOutOfReach(page, run)).toMatchObject({
+ why: 'reached',
+ least: 5_468,
+ suggested: 5_500,
+ });
+ // Asked for a little less since (within its band): it didn't reach the longer one either.
+ expect(lengthOutOfReach(statuses(6_877, [], '3500'), run)).toMatchObject({ why: 'reached' });
+ // Asked for much less: what it came to for 4,000 says nothing; the estimate decides.
+ expect(lengthOutOfReach(statuses(6_877, [], '3000'), run)).toMatchObject({
+ why: 'floor',
+ least: 4_300,
+ });
+ // A near miss of 10,000 says nothing of 3,000 either.
+ const near = { ...run, floor: 1_800, last: { chars: 12_400, target: 10_000, kept: 3_125 } };
+ expect(lengthOutOfReach(statuses(6_877, [], '3000'), near)).toBeNull();
+ // A rewrite that met a longer Length says nothing of a shorter one.
+ const met = { ...run, last: { chars: 9_800, target: 10_000, kept: 3_125 } };
+ expect(lengthOutOfReach(page, met)).toBeNull();
+ expect(rewriteAdvice(page, { ...met, kept: 1_000, floor: 1_800 })).toMatchObject({
+ reason: 'length',
+ });
+ // Written with Length off: it was asked for none.
+ expect(lengthOutOfReach(page, { ...run, last: { ...missed, target: null } })).toBeNull();
+ // A passage unlocked since: a rewrite may go shorter now.
+ expect(lengthOutOfReach(page, { ...run, kept: 2_900 })).toBeNull();
+ // More locked since: what it came to then doesn't say it gets there now.
+ expect(
+ lengthOutOfReach(page, {
+ kept: 4_500,
+ floor: 5_200,
+ last: { chars: 4_500, target: 4_000, kept: 1_000 },
+ }),
+ ).toMatchObject({ why: 'floor', least: 5_200 });
+ // The last one got within the band: in reach, whatever the estimate says.
+ expect(
+ lengthOutOfReach(page, { ...run, floor: 5_000, last: { ...missed, chars: 4_700 } }),
+ ).toBeNull();
+ // Past both: the more of the two, so one Raise is enough.
+ expect(lengthOutOfReach(page, { ...run, floor: 6_200 })).toMatchObject({
+ why: 'floor',
+ least: 6_200,
+ suggested: 6_500,
+ });
+ // Never a Length past the page as it is.
+ expect(lengthOutOfReach(statuses(4_900, [], '4000'), run)?.suggested).toBe(5_000);
+ });
+
+ it('names what a rewrite keeps as why it missed only when that alone puts the Length out of reach', () => {
+ const page = statuses(6_877, [], '4000');
+ const missed = { chars: 5_468, target: 4_000, kept: 3_125 };
+ // The rewrite missed, but its kept blocks and headings alone fit: not their doing.
+ expect(keptOutOfReach(page, { kept: 3_125, floor: 4_300, last: missed })).toBe(false);
+ expect(keptOutOfReach(page, { kept: 3_799, floor: 5_100, last: missed })).toBe(true);
});
it('recommends it for 4 rules or more the agent can fix', () => {
diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.ts
index c1cffdc0c..105a933a5 100644
--- a/web/src/lib/content/rules.ts
+++ b/web/src/lib/content/rules.ts
@@ -814,12 +814,36 @@ export const REWRITE_OPEN_RULES = 4;
/** The most text a page sent whole may hold (content-rewrite.js MAX_REWRITE_CHARS). */
export const REWRITE_MAX_CHARS = 60_000;
+/** The page's last rewrite, as the API keeps it (00285). */
+export interface LastRewrite {
+ /** The characters it came to. */
+ chars: number;
+ /** The Length it was written to; null with Length off. */
+ target: number | null;
+ /** The characters it kept word for word. */
+ kept: number;
+}
+
/**
- * A Length out of a rewrite's reach: what a rewrite keeps as it is (the
- * passages AI answers quote, tables, images, quotes, HTML blocks, the
- * server's keepBlocks) is this share of it or more.
+ * What a page rewrite can't go under, and what the last one came to: a
+ * Length under either is out of its reach (editor test 2026-10-25, where a
+ * page kept 78% of its Length and three rewrites never got there).
*/
-export const KEPT_LENGTH_SHARE = 0.85;
+export interface RewriteReach {
+ /** The characters it keeps as they are (the passages AI answers quote, tables, images…). */
+ kept: number;
+ /**
+ * The least a rewrite that keeps them comes to: those, the headings, and
+ * the least answer under each heading and summary under the H1 where
+ * nothing kept stands (rewriteFloor in the editor). Kept low on purpose.
+ */
+ floor: number;
+ /** The page's last rewrite, or null for none (or one made before 00285). */
+ last: LastRewrite | null;
+}
+
+/** Nothing known about what a rewrite keeps or reached: every Length is in reach. */
+export const NO_REACH: RewriteReach = { kept: 0, floor: 0, last: null };
/** A long page whose Length a rewrite can't reach, and a Length it could. */
export interface LengthOutOfReach {
@@ -827,18 +851,52 @@ export interface LengthOutOfReach {
target: number;
/** The characters a rewrite keeps as they are. */
kept: number;
- /** A Length with room for the kept blocks and the words around them, to the 500. */
+ /** Why: the least a rewrite comes to is past the Length, or the last rewrite came to `least`. */
+ why: 'floor' | 'reached';
+ /** The least a rewrite comes to: the estimate, or what the last one came to, the more. */
+ least: number;
+ /** A Length the page can be rewritten to: that, up to the 500. */
suggested: number;
}
/**
- * Whether the page is over its Length by more than a rewrite could take out:
- * the blocks it keeps are KEPT_LENGTH_SHARE of the Length or more. Null
- * otherwise, and for a page under its Length.
+ * What the last rewrite says of this Length: the characters it came to, when
+ * it was written to a Length (not with Length off), the page keeps what it
+ * kept then (nothing unlocked or locked since; the counts differ by about a
+ * space a block, so a little slack), and it was asked for this Length or a
+ * shorter one, or missed its own and this one is within that one's band.
+ * Null when it says nothing (a rewrite to 10,000 says nothing of 3,000).
+ */
+function lastRewriteSays(last: LastRewrite | null, target: number, kept: number): number | null {
+ if (!last || last.target === null) return null;
+ if (Math.abs(kept - last.kept) > last.kept * 0.02 + 20) return null;
+ const band = lengthBand(last.target);
+ const missedItsOwn = last.chars > band.max && target >= band.min;
+ return target >= last.target || missedItsOwn ? last.chars : null;
+}
+
+/**
+ * Whether what a rewrite keeps, with the headings and their answers, puts
+ * the Length out of its reach on its own: what the agent card names as why
+ * a rewrite missed (the rewrite itself is no reason).
+ */
+export function keptOutOfReach<T extends { rule: ActiveRule; status: RuleStatus }>(
+ rules: T[],
+ reach: RewriteReach,
+): boolean {
+ return lengthOutOfReach(rules, { ...reach, last: null }) !== null;
+}
+
+/**
+ * Whether the page is over its Length by more than a rewrite could take
+ * out: the least a rewrite comes to (`reach.floor`) is past the top of the
+ * Length's band, or the last rewrite (lastRewriteSays) came to more than it.
+ * A last rewrite that got within the band says it's in reach, whatever the
+ * estimate. Null otherwise, and for a page under its Length.
*/
export function lengthOutOfReach<T extends { rule: ActiveRule; status: RuleStatus }>(
rules: T[],
- kept: number,
+ reach: RewriteReach,
): LengthOutOfReach | null {
const length = rules.find(({ rule }) => rule.key === 'length' && rule.on);
const target = Number(length?.rule.current);
@@ -851,17 +909,25 @@ export function lengthOutOfReach<T extends { rule: ActiveRule; status: RuleStatu
) {
return null;
}
- if (kept < target * KEPT_LENGTH_SHARE) return null;
- // Room for the kept blocks and the words around them, not past the page
- // as it is (that would read short) nor the rule's own top.
+ const { max } = lengthBand(target);
+ const reached = lastRewriteSays(reach.last, target, reach.kept);
+ if (reached !== null && reached <= max) return null;
+ if (reached === null && reach.floor <= max) return null;
+ // The more of the two, so the Length suggested is one a rewrite can reach.
+ const least = Math.max(reach.floor, reached ?? 0);
+ const why = reached !== null && reached >= reach.floor ? 'reached' : 'floor';
+ // A Length the page fits as a rewrite leaves it, never under the rule's
+ // own value nor past its top, nor past the page as it is (that would read short).
const roundUp = (n: number) => Math.ceil(n / 500) * 500;
return {
count: status.count,
target,
- kept,
+ kept: reach.kept,
+ why,
+ least,
suggested: Math.min(
RULE_LENGTH_MAX,
- Math.max(target, Math.min(roundUp(kept * 1.5), roundUp(status.count))),
+ Math.max(target, Math.min(roundUp(least), roundUp(status.count))),
),
};
}
@@ -874,12 +940,13 @@ export type RewriteAdvice =
/**
* Whether the Rules tab recommends Rewrite the page to these rules over
* Apply rules with Agent's few edits a run: the page more than 30% off its
- * Length (one a rewrite can reach, given the `kept` characters it keeps),
- * or 4 rules or more open that the agent can fix. Null otherwise.
+ * Length (one a rewrite can reach, given what it keeps and what the last
+ * one came to: never again after one missed it), or 4 rules or more open
+ * that the agent can fix. Null otherwise.
*/
export function rewriteAdvice<T extends { rule: ActiveRule; status: RuleStatus }>(
rules: T[],
- kept = 0,
+ reach: RewriteReach = NO_REACH,
): RewriteAdvice | null {
const length = rules.find(({ rule }) => rule.key === 'length' && rule.on);
const target = Number(length?.rule.current);
@@ -895,12 +962,12 @@ export function rewriteAdvice<T extends { rule: ActiveRule; status: RuleStatus }
target > 0
) {
const off = Math.abs(status.count - target) / target;
- if (off > REWRITE_LENGTH_OFF && !lengthOutOfReach(rules, kept)) {
+ if (off > REWRITE_LENGTH_OFF && !lengthOutOfReach(rules, reach)) {
return { reason: 'length', count: status.count, target, percent: Math.round(off * 100) };
}
}
// A Length out of reach is no rule a rewrite meets.
- const outOfReach = lengthOutOfReach(rules, kept) !== null;
+ const outOfReach = lengthOutOfReach(rules, reach) !== null;
const open = openRulesForAgent(rules).forAgent.filter(
({ rule }) => !(outOfReach && rule.key === 'length'),
).length;
@@ -1168,7 +1235,9 @@ export function lengthWarns(statuses: { rule: ActiveRule; status: RuleStatus }[]
*/
const LEAST_SECTION = 200;
const LEAST_QUESTION = 150;
-const LEAST_SUMMARY = 100;
+export const LEAST_SUMMARY = 100;
+/** The least answer under a heading, a sentence or two (rewriteFloor). */
+export const LEAST_ANSWER = 100;
/**
* Rules that can't both be met (Content Agent rule gaps, C): the fan-out
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index b16859a89..3a2992ae4 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1817,6 +1817,7 @@ export type Database = {
content_draft_suggestions: {
Row: {
action_id: string | null
+ after_chars: number | null
after_links: Json | null
after_text: string
agent: string
@@ -1829,7 +1830,9 @@ export type Database = {
decided_by: string | null
draft_id: string
id: string
+ kept_chars: number | null
kind: string
+ length_target: number | null
position: number
reason: string
rule_keys: string[]
@@ -1839,6 +1842,7 @@ export type Database = {
}
Insert: {
action_id?: string | null
+ after_chars?: number | null
after_links?: Json | null
after_text: string
agent?: string
@@ -1851,7 +1855,9 @@ export type Database = {
decided_by?: string | null
draft_id: string
id?: string
+ kept_chars?: number | null
kind: string
+ length_target?: number | null
position?: number
reason: string
rule_keys?: string[]
@@ -1861,6 +1867,7 @@ export type Database = {
}
Update: {
action_id?: string | null
+ after_chars?: number | null
after_links?: Json | null
after_text?: string
agent?: string
@@ -1873,7 +1880,9 @@ export type Database = {
decided_by?: string | null
draft_id?: string
id?: string
+ kept_chars?: number | null
kind?: string
+ length_target?: number | null
position?: number
reason?: string
rule_keys?: string[]