Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): let agents link over the API, to the brand's pages and the draft's sources (#1372)

Cihan03bfd33f3aba
diff --git a/web/src/lib/content/agent-suggestions.test.ts b/web/src/lib/content/agent-suggestions.test.ts
index b74121d83..8651b8039 100644
--- a/web/src/lib/content/agent-suggestions.test.ts
+++ b/web/src/lib/content/agent-suggestions.test.ts
@@ -3,9 +3,11 @@ import { passageKey } from './cited-passages';
import {
cleanInsertHtml,
draftPassages,
+ inlineText,
keepAgentSuggestions,
splitReplace,
} from './agent-suggestions';
+import { linkKey } from './link-targets';
const HTML =
'<h1>How to brew pour-over</h1><p>Use good coffee &amp; hot water.</p>' +
@@ -216,7 +218,7 @@ describe('a replace on a heading', () => {
'What is LLM SEO? LLM SEO optimizes pages for large language models.<ul><li>a</li></ul>',
'h2',
),
- ).toEqual({
+ ).toMatchObject({
words: 'What is LLM SEO?',
blocks: '<p>LLM SEO optimizes pages for large language models.</p><ul><li>a</li></ul>',
});
@@ -230,7 +232,7 @@ describe('a replace on a heading', () => {
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(subtitle, 'h1')).toMatchObject({ words: subtitle, blocks: '' });
expect(
splitReplace(
'AEOとは?AEOはAIアシスタントの回答に引用されるための最適化の方法です。詳しく順番に説明します。',
@@ -253,13 +255,104 @@ describe('a replace on a heading', () => {
'h2',
).words,
).toBe('AEO とは?');
- expect(splitReplace('AEO or SEO? Which matters more in 2026', 'h2')).toEqual({
+ expect(splitReplace('AEO or SEO? Which matters more in 2026', 'h2')).toMatchObject({
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({
+ expect(splitReplace('<p>Use 15 g.</p><ul><li>a scale</li></ul>', 'p')).toMatchObject({
words: 'Use 15 g.',
blocks: '<ul><li>a scale</li></ul>',
});
});
});
+
+/**
+ * Content Agent rule gaps, A, over the API: links only to get_content_draft's
+ * link_targets, a replace's beside its words, an insert's in its HTML.
+ */
+describe('links to the targets listed', () => {
+ const page = draftPassages(
+ '<h2>Pricing</h2><p>See our plans for teams.</p><p>Studies show it works.</p>',
+ );
+ const links = new Map(
+ ['https://acme.example/pricing', 'https://research.example/study'].map((url) => [
+ linkKey(url)!,
+ url,
+ ]),
+ );
+ const replace = (after: string) => ({
+ kind: 'replace' as const,
+ passage: 2,
+ before: 'See our plans for teams.',
+ after,
+ reason: 'link the pricing page',
+ });
+
+ it('keeps a replace’s link to a listed page, by its words, with the page’s URL', () => {
+ const { kept, dropped } = keepAgentSuggestions(
+ [
+ replace(
+ 'See <a href="https://www.acme.example/pricing/?utm_source=x">our plans</a> for teams.',
+ ),
+ ],
+ page,
+ new Set(),
+ links,
+ );
+ expect(dropped).toEqual([]);
+ expect(kept[0]).toMatchObject({
+ after_text: 'See our plans for teams.',
+ after_links: [{ start: 4, end: 13, href: 'https://acme.example/pricing' }],
+ });
+ });
+
+ it('unwraps a link to anything not listed, and says when nothing then changes', () => {
+ const { kept, dropped } = keepAgentSuggestions(
+ [
+ replace('See <a href="https://made-up.example/x">our plans</a> for teams.'),
+ replace('See <a href="https://made-up.example/x">our team plans</a>.'),
+ ],
+ page,
+ new Set(),
+ links,
+ );
+ expect(dropped).toEqual([{ index: 0, reason: 'no_change' }]);
+ expect(kept[0].after_text).toBe('See our team plans.');
+ expect(kept[0]).not.toHaveProperty('after_links');
+ });
+
+ it('keeps an insert’s link to a listed source, never one in a heading', () => {
+ const { kept } = keepAgentSuggestions(
+ [
+ {
+ kind: 'insert',
+ passage: 3,
+ after:
+ '<h3><a href="https://research.example/study">Study</a></h3><p>A <a href="https://research.example/study" target="_blank" onclick="x()">2025 study</a> found it.</p>',
+ reason: 'cite a source',
+ },
+ ],
+ page,
+ new Set(),
+ links,
+ );
+ expect(kept[0].after_text).toBe(
+ '<h3>Study</h3><p>A <a href="https://research.example/study">2025 study</a> found it.</p>',
+ );
+ // A link with no words links nothing.
+ expect(
+ cleanInsertHtml('<p>A <a href="https://research.example/study"> </a>study.</p>', links),
+ ).toBe('<p>A study.</p>');
+ // Without targets, as before: no link at all.
+ expect(cleanInsertHtml('<p>A <a href="https://research.example/study">study</a>.</p>')).toBe(
+ '<p>A study.</p>',
+ );
+ });
+
+ it('reads inline words and their links, spaces collapsed', () => {
+ expect(inlineText('Read <a href="u"> the guide </a><br />now &amp; then')).toEqual({
+ text: 'Read the guide now & then',
+ links: [{ start: 5, end: 14, href: 'u' }],
+ });
+ });
+});
diff --git a/web/src/lib/content/agent-suggestions.ts b/web/src/lib/content/agent-suggestions.ts
index 91f4ef0c4..1a1c08991 100644
--- a/web/src/lib/content/agent-suggestions.ts
+++ b/web/src/lib/content/agent-suggestions.ts
@@ -1,6 +1,7 @@
import sanitizeHtml from 'sanitize-html';
import { passageKey } from './cited-passages';
-import { growsPastLimit, headingLimit } from './suggestions';
+import { linkKey } from './link-targets';
+import { growsPastLimit, headingLimit, type SuggestionLink } from './suggestions';
/**
* An agent's suggestions through the editor API (CE-022): the same contract
@@ -56,15 +57,77 @@ export function draftPassages(html: string): DraftPassage[] {
return passages;
}
-/** An insert's HTML, kept to the blocks the editor takes from an agent, with no attributes. */
-export function cleanInsertHtml(html: string): string {
- return sanitizeHtml(html ?? '', {
- allowedTags: ['h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'b', 'i', 'br'],
- allowedAttributes: {},
- // The page has its H1, its title: an agent's heading is an H2 at most.
- transformTags: { h1: 'h2' },
+/** The most links one replace keeps (after_links, 00240). */
+const MAX_LINKS = 20;
+
+/**
+ * An insert's HTML, kept to the blocks the editor takes from an agent, with
+ * no attributes. A link stays only to a URL in `links` (linkAllowList,
+ * get_content_draft's link_targets), with that URL, and never in a heading;
+ * any other is unwrapped to its words.
+ */
+export function cleanInsertHtml(html: string, links: Map<string, string> | null = null): string {
+ const cleaned = sanitizeHtml(html ?? '', {
+ allowedTags: ['h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'b', 'i', 'br', 'a'],
+ allowedAttributes: { a: ['href'] },
+ transformTags: {
+ // The page has its H1, its title: an agent's heading is an H2 at most.
+ h1: 'h2',
+ // A tag that isn't allowed is dropped and its words kept.
+ a: (_tagName, attribs) => {
+ const href = links?.get(linkKey(attribs.href ?? '') ?? '');
+ const kept: Record<string, string> = href ? { href } : {};
+ return { tagName: href ? 'a' : 'span', attribs: kept };
+ },
+ },
nonTextTags: ['script', 'style', 'textarea', 'option', 'noscript', 'template', 'title'],
+ // A link with no words to it links nothing.
+ exclusiveFilter: (frame) => frame.tag === 'a' && !frame.text.trim(),
}).trim();
+ return cleaned.replace(
+ /<(h[2-4])>([\s\S]*?)<\/\1>/g,
+ (_, tag: string, inner: string) => `<${tag}>${inner.replace(/<\/?a\b[^>]*>/g, '')}</${tag}>`,
+ );
+}
+
+/**
+ * Cleaned inline HTML's words and the links on them, with offsets into the
+ * words: runs of spaces and line breaks collapsed to one space (a
+ * non-breaking space stays), trimmed. As inlineText in content-agent.js.
+ */
+export function inlineText(html: string): { text: string; links: SuggestionLink[] } {
+ let text = '';
+ const links: SuggestionLink[] = [];
+ let open: { start: number; href: string } | null = null;
+ const add = (data: string) => {
+ const piece = decodeEntities(data).replace(/[ \t\r\n\f]+/g, ' ');
+ text += text === '' || text.endsWith(' ') ? piece.replace(/^ /, '') : piece;
+ };
+ const close = () => {
+ if (!open) return;
+ let from = open.start;
+ let to = text.length;
+ while (from < to && text[from] === ' ') from++;
+ while (to > from && text[to - 1] === ' ') to--;
+ if (to > from) links.push({ start: from, end: to, href: open.href });
+ open = null;
+ };
+ let at = 0;
+ for (const match of html.matchAll(/<(\/?)([a-z0-9]+)([^>]*)>/gi)) {
+ add(html.slice(at, match.index));
+ at = match.index! + match[0].length;
+ const [, closing, name, attrs] = match;
+ const tag = name.toLowerCase();
+ if (tag === 'br') add(' ');
+ if (tag !== 'a') continue;
+ close();
+ const href = closing ? undefined : /href="([^"]*)"/.exec(attrs)?.[1];
+ if (href) open = { start: text.length, href: decodeEntities(href) };
+ }
+ add(html.slice(at));
+ close();
+ const trimmed = text.replace(/ +$/, '');
+ return { text: trimmed, links: links.filter((link) => link.end <= trimmed.length) };
}
const textOf = (html: string) =>
@@ -98,10 +161,15 @@ const escapeHtml = (text: string) =>
* 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.
+ * question, and the answer becomes the first paragraph under it. The words'
+ * links (to a URL in `links`) come with their offsets; a heading's keep none.
*/
-export function splitReplace(after: string, tag: string): { words: string; blocks: string } {
- const html = cleanInsertHtml(after);
+export function splitReplace(
+ after: string,
+ tag: string,
+ links: Map<string, string> | null = null,
+): { words: string; links: SuggestionLink[]; blocks: string } {
+ const html = cleanInsertHtml(after, links);
const start = html.search(BLOCK_START);
let words = start === -1 ? html : html.slice(0, start);
let blocks = start === -1 ? '' : html.slice(start);
@@ -115,9 +183,9 @@ export function splitReplace(after: string, tag: string): { words: string; block
}
}
// 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();
+ const read = inlineText(words);
+ words = read.text;
+ const wordLinks = isHeading(tag) ? [] : read.links;
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
@@ -133,7 +201,7 @@ export function splitReplace(after: string, tag: string): { words: string; block
blocks = `<p>${escapeHtml(answered[2])}</p>${blocks}`;
}
}
- return { words, blocks: blocks.trim() };
+ return { words, links: wordLinks, blocks: blocks.trim() };
}
/** What an agent sends: passage numbers are 1-based, as get_content_draft lists them. */
@@ -151,6 +219,8 @@ export interface KeptSuggestion {
block_text: string;
before_text: string;
after_text: string;
+ /** A replace's links, by offset into after_text (00240). */
+ after_links?: SuggestionLink[];
reason: string;
rule_keys: string[];
}
@@ -178,6 +248,8 @@ export function keepAgentSuggestions(
raw: AgentSuggestionInput[],
passages: DraftPassage[],
lockedKeys: Set<string>,
+ /** The URLs links may keep (linkAllowList); without it, every link is unwrapped. */
+ links: Map<string, string> | null = null,
): { kept: KeptSuggestion[]; dropped: { index: number; reason: DroppedReason }[] } {
const kept: KeptSuggestion[] = [];
const dropped: { index: number; reason: DroppedReason }[] = [];
@@ -208,15 +280,19 @@ export function keepAgentSuggestions(
// replace never leaves a question without its answer.
const changes: { id: string; row: KeptSuggestion }[] = [];
if (s.kind !== 'replace') {
- const insert = insertOf(cleanInsertHtml(s.after));
+ const insert = insertOf(cleanInsertHtml(s.after, links));
if (!insert) return drop('empty');
changes.push(insert);
} else {
if (lockedKeys.has(passageKey(passage.text))) return drop('locked');
const before = (s.before ?? '').trim();
- const { words, blocks } = splitReplace(s.after, passage.tag);
+ const split = splitReplace(s.after, passage.tag, links);
+ const { words, blocks } = split;
+ // As many as a suggestion may keep (00240).
+ const wordLinks = split.links.slice(0, MAX_LINKS);
if (!before || (!words && !blocks)) return drop('empty');
- const changed = !!words && words !== before;
+ // Linking words the passage already has is a change too.
+ const changed = !!words && (words !== before || wordLinks.length > 0);
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');
@@ -239,6 +315,7 @@ export function keepAgentSuggestions(
block_text: passage.text,
before_text: before,
after_text: words,
+ ...(wordLinks.length ? { after_links: wordLinks } : {}),
reason,
rule_keys: rules,
},
diff --git a/web/src/lib/content/link-targets.test.ts b/web/src/lib/content/link-targets.test.ts
new file mode 100644
index 000000000..e5bd30377
--- /dev/null
+++ b/web/src/lib/content/link-targets.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import { linkAllowList, linkHref, linkKey, pickLinkTargets } from './link-targets';
+
+/** Where an agent may link: the brand's pages and the draft's own sources. */
+describe('linkKey and linkHref', () => {
+ it('compare links without www, tracking, a hash or a trailing slash', () => {
+ expect(linkKey('https://WWW.Acme.example/Pricing/?utm_source=x&plan=pro#top')).toBe(
+ 'acme.example/Pricing?plan=pro',
+ );
+ expect(linkKey('mailto:[email protected]')).toBeNull();
+ expect(linkKey('/pricing')).toBeNull();
+ expect(linkHref('https://www.acme.example/a/?utm_source=chatgpt.com&plan=pro#top')).toBe(
+ 'https://www.acme.example/a/?plan=pro',
+ );
+ });
+});
+
+describe('pickLinkTargets', () => {
+ const pages = [
+ { url: 'https://acme.example/pricing', title: 'Pricing', h1: null },
+ { url: 'https://acme.example/guides/brew', title: null, h1: 'Brew guide' },
+ { url: 'https://acme.example/guides/brew/', title: 'Duplicate', h1: null },
+ ];
+ const sources = {
+ citedPages: [
+ { url: 'https://research.example/study?utm_source=chatgpt.com', title: 'Coffee study' },
+ { url: 'https://www.rival.example/compare', title: 'Rival compares' },
+ { url: 'https://shop.other-rival.example/x', title: 'Other rival' },
+ { url: 'https://blog.acme.example/post', title: 'Our blog' },
+ { url: 'https://forum.example/thread', title: 'A thread' },
+ ],
+ brandDomains: ['acme.example'],
+ // A competitor's domain may be written with a path.
+ competitorDomains: ['rival.example', 'other-rival.example/en'],
+ };
+ const choices = [
+ { ref: 'https://forum.example/thread', included: false, added: false },
+ { ref: 'https://standards.example/spec', included: true, added: true },
+ ];
+
+ it("offers the brand's pages and the kept sources, never its own or a competitor's", () => {
+ const targets = pickLinkTargets({
+ pages,
+ sources,
+ choices,
+ sourceUrl: 'https://acme.example/pricing',
+ });
+ expect(targets.own).toEqual([{ url: 'https://acme.example/guides/brew', title: 'Brew guide' }]);
+ expect(targets.sources).toEqual([
+ { url: 'https://research.example/study', title: 'Coffee study' },
+ { url: 'https://standards.example/spec', title: 'https://standards.example/spec' },
+ ]);
+ });
+
+ it('offers no sources without their read: competitors could not be told apart', () => {
+ expect(pickLinkTargets({ pages, sources: null, choices, sourceUrl: null }).sources).toEqual([]);
+ });
+
+ it('allows each target by its key, giving back its URL', () => {
+ const allow = linkAllowList(pickLinkTargets({ pages, sources, choices, sourceUrl: null }));
+ expect(allow.get(linkKey('https://www.acme.example/pricing/')!)).toBe(
+ 'https://acme.example/pricing',
+ );
+ expect(allow.get(linkKey('https://made-up.example/')!)).toBeUndefined();
+ });
+});
diff --git a/web/src/lib/content/link-targets.ts b/web/src/lib/content/link-targets.ts
new file mode 100644
index 000000000..4a1f2488b
--- /dev/null
+++ b/web/src/lib/content/link-targets.ts
@@ -0,0 +1,125 @@
+import { classifyDomain, extractHostname, normalizeDomain } from '@/lib/citations/classify';
+
+/**
+ * Where an agent may link (Content Agent rule gaps, A): the brand's own pages
+ * for internal links, and the sources the draft keeps for outbound links and
+ * inline citations. A link to anything else is unwrapped, so an agent never
+ * invents one. The same rules as the Content Agent's on the server
+ * (server/src/lib/content-links.js).
+ */
+
+/** The brand's pages offered, the most cited and visited first. */
+export const MAX_OWN_PAGES = 40;
+/** The draft's sources offered, as the Sources tab lists them (its top 20). */
+export const MAX_SOURCE_PAGES = 20;
+
+export interface LinkTarget {
+ url: string;
+ title: string;
+}
+
+export interface LinkTargets {
+ /** The brand's own pages: internal links. */
+ own: LinkTarget[];
+ /** The draft's sources, not the brand's or a competitor's: outbound links and citations. */
+ sources: LinkTarget[];
+}
+
+/** Query parameters that only track a visit. */
+const TRACKING = /^(utm_\w+|gclid|fbclid|msclkid|mc_cid|mc_eid|ref)$/i;
+
+/**
+ * A URL as links compare: an http(s) address, its host lower-cased without
+ * www, no hash, no tracking parameters, no trailing slash. Null for anything else.
+ */
+export function linkKey(url: string): string | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(String(url ?? '').trim());
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
+ const host = parsed.hostname.toLowerCase().replace(/^www\./, '');
+ const params = [...parsed.searchParams].filter(([name]) => !TRACKING.test(name));
+ const search = params.length ? `?${new URLSearchParams(params).toString()}` : '';
+ return `${host}${parsed.pathname.replace(/\/+$/, '')}${search}`;
+}
+
+/** A URL as a link keeps it: without tracking parameters or a hash; null when not http(s). */
+export function linkHref(url: string): string | null {
+ if (!linkKey(url)) return null;
+ const parsed = new URL(String(url).trim());
+ for (const name of [...parsed.searchParams.keys()]) {
+ if (TRACKING.test(name)) parsed.searchParams.delete(name);
+ }
+ parsed.hash = '';
+ return parsed.toString();
+}
+
+/** The URL a link may keep, by its key: every target's. */
+export function linkAllowList(targets: LinkTargets): Map<string, string> {
+ return new Map(
+ [...targets.own, ...targets.sources].flatMap((p) => {
+ const key = linkKey(p.url);
+ return key ? [[key, p.url] as const] : [];
+ }),
+ );
+}
+
+const clean = (text: string | null | undefined) => (text ?? '').replace(/\s+/g, ' ').trim();
+
+/**
+ * The targets from what was read: the brand's pages (site_pages, the most
+ * cited first), and the draft's sources (the content_draft_sources RPC's
+ * cited pages and the ones the person added, without those they left out
+ * and without the brand's and its competitors' own). Without the sources
+ * read, competitors can't be told apart: no outbound targets.
+ */
+export function pickLinkTargets({
+ pages,
+ sources,
+ choices,
+ sourceUrl,
+}: {
+ pages: { url: string; title: string | null; h1: string | null }[];
+ sources: {
+ citedPages?: { url: string; title: string | null }[];
+ brandDomains?: string[];
+ competitorDomains?: string[];
+ } | null;
+ choices: { ref: string; included: boolean; added: boolean }[];
+ sourceUrl: string | null;
+}): LinkTargets {
+ const seen = new Set([linkKey(sourceUrl ?? '')].filter(Boolean));
+ const take = (list: LinkTarget[], max: number, url: string, title: string | null) => {
+ const key = linkKey(url);
+ const href = linkHref(url);
+ if (!key || !href || seen.has(key) || list.length >= max) return;
+ seen.add(key);
+ list.push({ url: href, title: clean(title) || href });
+ };
+
+ const own: LinkTarget[] = [];
+ for (const page of pages) take(own, MAX_OWN_PAGES, page.url, page.title || page.h1);
+ if (!sources) return { own, sources: [] };
+
+ const leftOut = new Set(choices.filter((c) => !c.included).map((c) => linkKey(c.ref)));
+ const ctx = {
+ brandDomains: (sources.brandDomains ?? []).map(normalizeDomain),
+ competitorDomains: (sources.competitorDomains ?? []).map(normalizeDomain),
+ };
+ const outbound: LinkTarget[] = [];
+ for (const page of [
+ ...(sources.citedPages ?? []),
+ // Added by the person in the Sources tab: kept, even with no answer citing them yet.
+ ...choices.filter((c) => c.added && c.included).map((c) => ({ url: c.ref, title: null })),
+ ]) {
+ const host = extractHostname(page.url);
+ if (!host || leftOut.has(linkKey(page.url))) continue;
+ const kind = classifyDomain(host, ctx);
+ if (kind === 'you' || kind === 'competitor') continue;
+ take(outbound, MAX_SOURCE_PAGES, page.url, page.title);
+ }
+ return { own, sources: outbound };
+}
diff --git a/web/src/lib/mcp/content-schemas.ts b/web/src/lib/mcp/content-schemas.ts
index ab516c44a..133d21f83 100644
--- a/web/src/lib/mcp/content-schemas.ts
+++ b/web/src/lib/mcp/content-schemas.ts
@@ -85,7 +85,9 @@ export const suggestionsShape = {
.string()
.min(1)
.max(20_000)
- .describe('replace: the new words (a heading stays one short line); insert: the HTML.'),
+ .describe(
+ 'replace: the new words (a heading stays one short line); insert: the HTML. Links only to link_targets URLs.',
+ ),
reason: z
.string()
.min(1)
diff --git a/web/src/lib/mcp/content.test.ts b/web/src/lib/mcp/content.test.ts
index 1bd17e950..83710bfb2 100644
--- a/web/src/lib/mcp/content.test.ts
+++ b/web/src/lib/mcp/content.test.ts
@@ -29,6 +29,7 @@ vi.mock('@/lib/supabase/admin', () => ({
eq: (col: string, v: unknown) => (db.filters.push([table, col, v]), chain),
in: () => chain,
is: (col: string, v: unknown) => (db.filters.push([table, col, v]), chain),
+ or: () => chain,
order: () => chain,
limit: () => chain,
insert: (value: unknown) => (db.writes.push({ table, op: 'insert', value }), chain),
@@ -221,6 +222,8 @@ describe('suggestContentChangesFor', () => {
]);
expect(result).toMatchObject({ kept: 1, dropped: [{ index: 0, reason: 'locked' }] });
+ // No suggestion links: the sources aren't read.
+ expect(db.rpcCalls.map(([name]) => name)).not.toContain('content_draft_sources');
const insert = db.writes.find((w) => w.table === 'content_draft_suggestions')!;
expect(insert.value).toEqual([
expect.objectContaining({
@@ -234,6 +237,43 @@ describe('suggestContentChangesFor', () => {
]);
});
+ it('keeps links only to the link targets get_content_draft lists (A)', async () => {
+ db.rows.content_drafts = draftRow();
+ db.rows.site_pages = [
+ { url: 'https://acme.example/accuracy', title: 'How we measure accuracy', h1: null },
+ ];
+ db.rpc.content_draft_sources = {
+ citedPages: [{ url: 'https://research.example/forecasting', title: 'A forecasting study' }],
+ brandDomains: ['acme.example'],
+ competitorDomains: [],
+ };
+
+ const draft = await getContentDraftFor(auth, 'd1');
+ expect(draft!.link_targets).toEqual({
+ own_pages: [{ url: 'https://acme.example/accuracy', title: 'How we measure accuracy' }],
+ sources: [{ url: 'https://research.example/forecasting', title: 'A forecasting study' }],
+ });
+
+ const result = await suggestContentChangesFor(auth, 'd1', [
+ {
+ kind: 'replace',
+ passage: 3,
+ before: 'very accurate',
+ after:
+ '<a href="https://acme.example/accuracy">shown per team</a>, as <a href="https://made-up.example">this</a> says',
+ reason: 'link how accuracy is measured',
+ },
+ ]);
+ expect(result).toMatchObject({ kept: 1, dropped: [] });
+ const insert = db.writes.find((w) => w.table === 'content_draft_suggestions')!;
+ expect(insert.value).toEqual([
+ expect.objectContaining({
+ after_text: 'shown per team, as this says',
+ after_links: [{ start: 0, end: 14, href: 'https://acme.example/accuracy' }],
+ }),
+ ]);
+ });
+
it('waits while a person still has the latest batch to decide', async () => {
db.rows.content_drafts = draftRow();
db.rows.content_draft_suggestions = [
diff --git a/web/src/lib/mcp/content.ts b/web/src/lib/mcp/content.ts
index fdd792559..788af51c1 100644
--- a/web/src/lib/mcp/content.ts
+++ b/web/src/lib/mcp/content.ts
@@ -15,6 +15,12 @@ import { IMPACT_PERIODS } from '@/lib/content/impact';
import { detectPageType, siteTypeOf } from '@/lib/content/page-types';
import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';
import { SOURCES_DAYS } from '@/lib/content/sources';
+import {
+ MAX_OWN_PAGES,
+ linkAllowList,
+ pickLinkTargets,
+ type LinkTargets,
+} from '@/lib/content/link-targets';
/**
* The Content Editor's API for agents (CE-022, spec §15): what a person does
@@ -186,6 +192,12 @@ export interface McpDraft {
passages: { n: number; tag: string; text: string; locked: boolean }[];
/** The latest batch's suggestions still waiting for a person. */
open_suggestions: { id: string; kind: string; reason: string }[];
+ /**
+ * Where suggest_content_changes may link (Content Agent rule gaps, A): the
+ * brand's own pages for internal links, the draft's sources for outbound
+ * links and inline citations. A link to anything else is unwrapped.
+ */
+ link_targets: { own_pages: LinkTargets['own']; sources: LinkTargets['sources'] };
}
/** One draft, its passages numbered and the locked ones marked; null outside the organization. */
@@ -196,11 +208,14 @@ export async function getContentDraftFor(
const draft = await draftFor(auth, draftId);
if (!draft) return null;
const passages = draftPassages(draft.body_html);
- const locked = await lockedKeys(
- draft,
- passages.map((p) => p.text),
- );
- const openSuggestions = await openSuggestionsOf(draft.id);
+ const [locked, openSuggestions, targets] = await Promise.all([
+ lockedKeys(
+ draft,
+ passages.map((p) => p.text),
+ ),
+ openSuggestionsOf(draft.id),
+ linkTargetsOf(draft),
+ ]);
return {
id: draft.id,
@@ -221,9 +236,52 @@ export async function getContentDraftFor(
locked: locked.has(passageKey(p.text)),
})),
open_suggestions: openSuggestions,
+ link_targets: { own_pages: targets.own, sources: targets.sources },
};
}
+/**
+ * The draft's link targets (pickLinkTargets): the brand's pages from
+ * site_pages, and its sources from the content_draft_sources RPC and the
+ * person's choices. A failed read leaves its list empty.
+ */
+async function linkTargetsOf(draft: {
+ id: string;
+ brand_id: string;
+ source_url: string | null;
+}): Promise<LinkTargets> {
+ const [pages, sources, choices] = await Promise.all([
+ supabaseAdmin
+ .from('site_pages')
+ .select('url, title, h1')
+ .eq('brand_id', draft.brand_id)
+ // Not fetched yet, or answered: 0 is a fetch that failed outright (00104).
+ .or('fetch_status.is.null,and(fetch_status.gte.200,fetch_status.lt.400)')
+ .order('ai_citations', { ascending: false })
+ .order('ga_sessions', { ascending: false })
+ .limit(MAX_OWN_PAGES + 1),
+ supabaseAdmin.rpc('content_draft_sources', { p_draft_id: draft.id, p_days: SOURCES_DAYS }),
+ supabaseAdmin
+ .from('content_draft_sources')
+ .select('ref, included, added')
+ .eq('draft_id', draft.id)
+ .eq('kind', 'cited_page'),
+ ]);
+ for (const [what, read] of [
+ ['site pages', pages],
+ ['sources', sources],
+ ['source choices', choices],
+ ] as const) {
+ if (read.error) console.error(`Failed to read the draft's link targets (${what}):`, read.error);
+ }
+ return pickLinkTargets({
+ pages: pages.error ? [] : (pages.data ?? []),
+ sources: sources.error ? null : sources.data,
+ choices: choices.error ? [] : (choices.data ?? []),
+ sourceUrl: draft.source_url,
+ });
+}
+
export interface CreateDraftInput {
brandId: string;
title: string;
@@ -422,11 +480,21 @@ export async function suggestContentChangesFor(
if (draft.status === 'published') return 'published';
if ((await openSuggestionsOf(draft.id)).length) return 'open_suggestions';
const passages = draftPassages(draft.body_html);
- const locked = await lockedKeys(
- draft,
- passages.map((p) => p.text),
+ // The targets only when a suggestion links: the sources read is the heavy one.
+ const linking = suggestions.some((s) => /<a\b/i.test(s.after));
+ const [locked, targets] = await Promise.all([
+ lockedKeys(
+ draft,
+ passages.map((p) => p.text),
+ ),
+ linking ? linkTargetsOf(draft) : null,
+ ]);
+ const { kept, dropped } = keepAgentSuggestions(
+ suggestions,
+ passages,
+ locked,
+ targets ? linkAllowList(targets) : null,
);
- const { kept, dropped } = keepAgentSuggestions(suggestions, passages, locked);
if (!kept.length) return { kept: 0, batch_id: null, dropped };
const batchId = crypto.randomUUID();
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 9f7662c32..1e3c22379 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -1579,7 +1579,7 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
'get_content_draft',
{
description:
- 'Read one Content Editor draft: its HTML, and the page passage by passage (numbered, as suggest_content_changes refers to them). Passages marked locked are quoted by AI answers today: never suggest changing them. Also the action it belongs to and the agent suggestions still waiting for review.',
+ 'Read one Content Editor draft: its HTML, and the page passage by passage (numbered, as suggest_content_changes refers to them). Passages marked locked are quoted by AI answers today: never suggest changing them. Also the action it belongs to, the agent suggestions still waiting for review, and link_targets: the only URLs suggest_content_changes may link to (own_pages for internal links, sources for outbound links and inline citations).',
inputSchema: {
draft_id: relaxedUuid.describe('Draft UUID, from list_content_drafts.'),
},
@@ -1688,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). 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).`,
+ 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). Either may link words as <a href="URL">words</a>, but only to a URL in get_content_draft's link_targets: any other link is unwrapped to its words, and a heading never keeps a link. 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,