Skip to content

feat(content): let the Content Agent link to the brand's pages and the draft's sources - #1371

Merged
gkhngyk merged 11 commits into
ansvisor:mainfrom
cihan-gyk:feature/agent-links
Oct 23, 2026
Merged

gkhngyk merged 11 commits into
ansvisor:mainfrom
cihan-gyk:feature/agent-links

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

The Content Agent can now link: to the brand's own pages, and to the draft's sources.

Stacked on #1369 and #1370 (both touch the same suggestion code). This PR's own changes are 91a4e5f and 1ae6e1e, on top of merges of those two branches (with their review fixes). Merge after them.

On prod, the agent left the Internal links, Outbound links and Cite sources inline rules open after every run (0 of 3, 0 of 2, Missing). It could never meet them:

  • a replace's new words were stored as plain text;
  • inserts allowed no <a>;
  • the prompt gave it nothing to link to;
  • so it wrote "(Source: [source, 2024])" and plain-text "links".

Server (server/src/lib/content-links.js, new)

  • What it reads. readLinkTargets reads only the lists the asked rules need, for both Apply rules with Agent (fixDraftRules) and Start Agent on an existing page (content-writer.js):
    • Internal links: the brand's own pages from site_pages, by AI citations then GA sessions. Up to 40; a failed fetch (fetch_status 0 or ≥ 400) and the draft's own URL are left out.
    • Outbound links / Cite sources inline: the draft's sources from the content_draft_sources RPC, i.e. the pages AI answers cite for its prompts, plus the ones the person added in the Sources tab. Up to 20. Pages on the brand's or a competitor's domain (ownDomainMatcher, a domain written with a path included) and ones the person left out are dropped. If the RPC fails, the outbound list is empty, since competitors can't be told apart.
  • What the model sees. linkTargetsPrompt lists the targets as "title — URL". The shared LINK_RULE in both prompts says to link only to a listed URL, copied exactly, never to invent one, and never to link a heading.

Keeping a suggestion's links (content-agent.js)

  • cleanInsertHtml(html, links) keeps an <a> only when its URL matches a target (linkKey: host without www, no tracking parameters, hash or trailing slash).
    • The href becomes the target's URL, with tracking parameters removed.
    • Every other attribute goes, and links inside headings are unwrapped.
    • An invented URL is unwrapped to its words. A replace that then changes nothing is dropped.
  • A replace keeps its words as plain text (the editor finds an accepted one by them), and its links go in a new after_links column: [{ start, end, href }], offsets into the words, at most 20 (inlineText).
    • Linking words the passage already has counts as a change.
    • A heading's words keep no links.
  • An insert keeps its links in its HTML, as before for its other blocks.

Migration 00240 adds content_draft_suggestions.after_links jsonb. It is null, or an array of 1–20, on replaces only. schema.sql is rebuilt, and the migration is applied on the dev DB.

Editor (web)

  • getDraftSuggestions reads after_links. suggestionLinks keeps only in-range, non-overlapping, ordered links whose href passes safeLinkHref.
  • Accept inserts the words, removes any link the old words had, and adds a link mark per range. Undo removes them.
  • The card underlines the linked words (their address on hover) and lists where they go, "Links: …". Anchors in an insert card are shown, not followed.

Deploy order: 00240 before the server and web.

  • The web selects after_links, so it can't read suggestions without the column.
  • A batch with a linked replace can't be written without it.

Known limit: the outbound list is the draft's cited pages, so it can include a forum thread (e.g. Reddit). The server has no forum/UGC classifier yet (the web's classifyDomain has one). Leaving those out is a follow-up.

Related issue

Content Agent rule gaps, item A, found by testing on prod on 2026-10-22. No issue.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00240.
  2. Open a draft whose Rules show Internal links / Outbound links / Cite sources inline open, and run Apply rules with Agent.
    • The agent's link cards underline the linked words and list "Links: …", only to the brand's pages and the draft's sources.
    • Accept all: the rules move (e.g. Internal links 0 → 2 of 3, Cite sources inline ✓) and the words are links in the page.
    • Undo all takes them off.

Checked locally on a temporary demo draft (since deleted):

  • Setup: this branch's server on :8081 and the web on :3002. There are no AI keys locally, so a hand-written model answer went through readLinkTargets and keepSuggestions against the real dev DB.
  • Targets read: 8 own pages and 3 sources.
  • Kept and dropped: the listed links were kept, and an invented one was unwrapped and dropped.
  • In the editor: Accept all moved Internal links 0 → 2 of 3, Outbound links 0 → 1 of 2 and Cite sources inline Missing → ✓. Undo all removed the links.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/) (0 errors; the 6 warnings are in untouched files, as on main)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • web yarn test (323 files, 2,845 tests) and yarn build;
  • server npm run format, npm run lint and npm test (173 files, 2,076 tests);
  • bash supabase/build-schema.sh.

🤖 Generated with Claude Code

cihan-gyk and others added 10 commits October 22, 2026 22:42
A replace on a heading that carried its answer ("What is X? X is …") or a
whole FAQ was flattened into the heading's line. Content Agent and the
editor API now split such a replace: the heading keeps its words and the
answer or blocks become an insert after it, kept together or not at all.
An agent change may not grow an H1 past 70 characters or another heading
past 90 (a long imported heading may still be shortened); both agent
prompts and the MCP description say a heading stays one line, and the
editor won't accept an older suggestion that would glue text into one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A page's H1 is its title. The editor now makes a second H1 an H2 however it
comes (typed, pasted, the HTML view, Add HTML or an agent suggestion),
keeping the page's own; Heading 1 is off while the page has one, and says
why on hover. A version restored from History and older drafts keep theirs,
and a new always-on "One H1 per page" rule flags them. The Content Agent is
never asked to fix it (it doesn't change heading levels) and its inserted
H1s become H2s. URL import keeps the H1 nearest the article's text, not a
logo's or a site name's, and makes the rest H2s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
…nly a real answer

Review fixes for ansvisor#1369 (gkhngyk):
- the question/answer split runs whenever the passage is a heading, also
  when blocks follow, and the answer goes first under it (inline answer
  plus a list, or <h2>Q? A.</h2><p>…);
- a heading that fits keeps a subtitle: only an answer that ends a
  sentence (. ! 。 !) is split off; past the limit the rest always goes;
- "?" ends a question only before a space; a full-width "?" with or
  without one;
- the regex has no catastrophic case on long text, and the garbled doc
  comment in agent-suggestions.ts reads again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ent, count HTML blocks'

Review fixes for ansvisor#1370 (gkhngyk):
- URL import picks the title's H1 once, before the frame and the root go:
  the last H1 with words before the text's first paragraph (a byline,
  date or breadcrumb line doesn't count as one), else the first; the
  title comes from it, and the root's other H1s become H2s;
- New content keeps one H1 in a pasted page, a file or an imported page
  (oneH1Html in bring(): the first H1 with words stays, others are H2s,
  empty ones unwrapped);
- "One H1 per page" counts H1s with words inside HTML blocks too;
- an empty H1 line never counts as the page's H1 in the editor, so it
  never stays over one with words, and Heading 1 stays on beside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e draft's sources

The agent could never meet the Internal links, Outbound links or Cite
sources inline rules: a replace's new words were plain text, inserts took
no <a>, and it had nowhere to link to. When one of those rules is asked
for, it now gets the brand's own pages (site_pages, the most cited and
visited first) and the draft's sources (cited pages, not the brand's or a
competitor's, not left out), and may link only to those URLs: any other
link is unwrapped, tracking parameters come off. A replace keeps its links
beside its words (after_links, 00240); an insert keeps them in its HTML.
The editor puts them on as link marks when a suggestion is accepted, takes
them off on undo, and shows on the card where each one goes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	server/src/lib/content-agent.js
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 22, 2026
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Content Agent rule gaps, part A1: the agent can now meet the link rules. It gets the brand's own pages and the draft's sources, may link only to those URLs (anything else is unwrapped), and the editor puts the links on as marks when a suggestion is accepted.

A review pass before pushing caught:

  • an uncapped number of links that would have failed the whole batch insert;
  • tracking parameters kept in the links;
  • a competitor domain written with a path slipping through;
  • failed fetches offered as internal links.

All are fixed. Next is A2: the same for MCP suggest_content_changes.

gkhngyk
gkhngyk previously approved these changes Oct 23, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. Two small follow-ups, fine to land after merge:

  1. Redirecting pages are offered as internal-link targets (server/src/lib/content-links.js:78).

    • The filter keeps fetch_status 200–399, so 3xx pages are listed. On prod there are 168 of them, and 25 have citations or GA sessions, so they can make the top 40.
    • An internal link to a redirect adds a hop, and SEO audits flag it.
    • Fix: keep 2xx only: .or('fetch_status.is.null,and(fetch_status.gte.200,fetch_status.lt.300)'), and update the comment.
  2. A link in a heading's split-off answer is lost (server/src/lib/content-agent.js:291, :304).

    • Take a heading replace like What is X? X is a platform that … per <a href="(listed source)">the 2025 study</a>. The answer goes under the heading as paragraph(answered[2]), which is built from plain text. wordLinks is already [] for headings, so the citation link is dropped without any notice.
    • This is the exact shape #1369 rescues, and an answer is where "Cite sources inline" wants its link.
    • Fix: keep read.links before clearing them for the heading. Then build the answer paragraph from the links that start at or after words.length - answered[2].length: shift their offsets, escape the text between them and wrap each range in <a href>. Mirror this on the web in #1372.

Checked and fine:

  • Merge commits. cf468c7 and 15464a5 match a plain re-merge of their parents. 48a23f9 had one conflict in content-agent.js, the splitReplace doc comment and body. It was resolved correctly: #1369's answer split now runs on inlineText's words, and nothing else changed.
  • Only listed URLs survive.
    • cleanInsertHtml keeps an <a> only when linkKey(href) is in the allow-list. It then removes every attribute and sets href to the target's own URL, so whatever the model wrote (javascript:, userinfo, a port, tracking parameters) is never kept.
    • Targets come only from linkHref, which is http(s) only. Links inside headings, and links with no words, are unwrapped.
  • after_links in the editor.
    • suggestionLinks drops unsafe hrefs (safeLinkHref), as well as out-of-range, overlapping and unordered ranges.
    • The card builds the linked words with textContent, and an insert card's anchors are replaced with spans.
    • Accept adds the link marks, and Undo removes them.
    • Saved HTML keeps only href on links (sanitizeDraftHtml). The editor's own rel="noopener noreferrer nofollow" and target stay in the editing view.
  • Migration 00240.
    • It adds one nullable column to content_draft_suggestions, with a check: replace only, an array of 1–20. Both sides slice to 20.
    • RLS is unchanged: members can select, and writes come only from the server and content_draft_decide_suggestions.
    • The table has 67 rows on prod, so the check's validation scan costs nothing. The column isn't on prod yet, and schema.sql and supabase.ts match.
  • Scope. fixDraftRules reads targets only after checking the draft's brand. runDraftWriting uses draft.brand_id. The RPC lets the service role through.
  • Cost. There's no extra LLM call. The prompt grows only when a link rule is asked for: at most 40 own pages and 20 sources. The largest own-page list on prod is about 7.5k characters, so roughly 2–3k input tokens in all. content_draft_sources took 1.3 s cold and 0.15 s warm on the largest brand's biggest draft.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-approving after merging main into the branch. The merge only brings in the squashed parent PR; the tree matches the one tested (web and server tests, typecheck, lint, format).

@gkhngyk
gkhngyk merged commit f2967ce into ansvisor:main Oct 23, 2026
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants