Repository navigation
feat(content): check for overlapping pages before a draft is started - #1287
Conversation
Content Editor CE-001 and CE-002. Content becomes a group in the sidebar, like Prompts: Opportunities keeps /dashboard/content, and the new Library (/dashboard/content/library) lists every page a person or the Content Agent writes or changes in Ansvisor, by status (Drafts, In review, Ready, Published), with its page type, method, author and AEO score. - Migration 00203: content_drafts with member RLS (select, insert, update; no delete yet). A guard trigger keeps author, created_by, brand and the scores server-side, so a member can't pass a draft off as the agent's. - Sidebar: each submenu remembers its own open state (Prompts keeps its key), and only the longest matching entry is current, so Opportunities isn't marked on the Library. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor CE-004, stacked on the Library (ansvisor#1256). A draft opens at /dashboard/content/editor/{id}: a header with its title, page type, method and status, whether it's saved, and Mark ready; the toolbar (H1 H2 H3, bold, italic, link, lists, quote, table with add row / add column / delete, image by address) with the length counter against the page type's target; and the page as rich text (TipTap 3.31.4, pinned). - Autosave after a pause in typing; saves never overlap, a failed one keeps the text and offers Retry, and leaving with unsaved text asks. The draft's title is its first H1. - saveContentDraft validates the body (500k chars) and title and says when RLS matched no row; markContentDraftReady moves draft or in review to ready only. - Links: http(s), mailto or a path on the brand's site; javascript:, //host and /\host are refused, in the dialog and when content loads. - The Library gets New content (a blank draft, until the Start screen), and its entry stays current while a draft is open in the editor. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content Editor CE-005 and CE-020, stacked on the editor core (ansvisor#1258). - Paste: from Word, Google Docs, Notion or a web page, headings (H4-H6 as H3), paragraphs, bold, italic, lists, links, tables and quotes stay; fonts, colors, classes, inline styles, scripts, iframes and utm_*, gclid, fbclid on links go. Google Docs' styled bold and italic become strong and em first. Pasted images wait for attachments. Cmd/Ctrl + Shift + V pastes plain text. - </> HTML shows the page's HTML as a draft stores it, one block per line; Back to visual cleans it with the same allow-list and says how many unsafe tags it removed. Schema JSON-LD is kept: a block in the editor, written again from its JSON so it can't carry markup. - The server checks every save against the allow-list again (sanitize-html), so a request made without the editor can't store a script, a handler or a javascript: link. - dompurify 3.4.16 and sanitize-html 2.18.0, pinned. Co-Authored-By: Claude Opus 5.5 <[email protected]>
sanitize-html 2.18.0 needs Node 22.12 or later, and CI and the web Docker image run Node 20, so yarn install refused it. 2.17.0 has no engine limit and the same API; @types/sanitize-html 2.16.0 matches it (both on htmlparser2 8). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Links in a draft looked like the text around them (dark, barely underlined), so a link just added seemed not to be there. They're blue and underlined now. With the cursor in a link, the toolbar shows its address, which opens it in a new tab; Cmd/Ctrl + click on it in the page does too. A click alone still puts the cursor in it to edit. A path on the brand's own site is shown, not opened: it has no address here. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-html # Conflicts: # web/messages/en.json # web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx # web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx # web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
On the user's request, as Webflow's custom code in rich text: as many HTML blocks as a page needs, each carrying code as written (an embed, a widget, a form), and one-click Copy HTML for a block or the whole page. - An HTML block is added from the toolbar where the cursor is, and edited or removed from its own Edit. The editor shows its code as text; it never runs in Ansvisor. A draft stores it as UTF-8 base64 in an empty element, so no markup in it can act, and the server checks each one decodes and fits 50,000 characters. - Copy HTML (header) puts the page on the clipboard as HTML to publish: each block as its own code, schema JSON-LD as its script. A block's own Copy HTML copies just its code. A refused Clipboard API falls back to the browser's copy command. - The HTML view shows each block between <!-- html-block --> markers, kept as written; code typed between new markers becomes a block. A paste from elsewhere can't bring blocks in. - The link, image and block dialogs focus their field when they open. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…locks # Conflicts: # web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx # web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
Inserting an HTML block scrolls the cursor into view, and ProseMirror measures a Range to do it. jsdom's ranges have no getClientRects, so on CI's Node 20 the measuring threw on a timer after the test and failed the run as an unhandled error. The editor test gives ranges an empty measurement, as jsdom has no layout anyway. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es to a draft A paperclip tool and drag-and-drop on the editor (CE-006). Excel and CSV open a preview (sheet picker, first 10 rows, header row) and insert as a table, asking first above 200 rows. Word (.docx, via mammoth), Markdown, HTML and plain text import as content through the same cleaning as a paste. Images, old .xls/.doc and files over 10 MB get a clear message. Imports land under a table when the cursor is inside one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Page types follow the kind of site (CE-023). Brand settings get a Site type (B2B SaaS, E-commerce, B2C; guessed from Shopping mode and the industry until picked), stored in brands.site_type (migration 00205). A draft's page type is detected from its URL, JSON-LD schema and title, and kept in step as the page changes, until the person picks one from the editor header's page type menu (content_drafts.page_type_source). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rary # Conflicts: # supabase/schema.sql
ansvisor#1257 took 00203 (citation gap rollups) on main, so the content drafts table moves to the next free number. The file is otherwise unchanged; schema.sql is rebuilt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
New content (CE-003) starts a page from an open Content Opportunity, a tracked prompt or a topic, or brings content to optimize by pasting (cleaned like the editor's paste) or uploading a Word, Markdown, HTML or text file. Start (CE-015) offers the site type's page types, the one the title or content shows picked first, and opens the editor. The draft keeps the opportunity it came from and the prompts it should answer (migration 00206: opportunity_id, prompt_ids, and a trigger that refuses another brand's opportunity or prompts). A new page starts with its title as the H1; content to optimize is checked against the draft allow-list. The editor's file readers move to lib/content/import-document so both use them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Start (CE-015) now shows which of the brand's own pages AI already cites for the prompts a new page would answer: prompts in common, citations in the last 30 days and the Google position from Search Console, through a new security-definer RPC, content_page_overlap (migration 00207). It recommends one option: optimize a page that already answers half the prompts or more, otherwise create the page and link the others to it, or say it is safe to create. Picking an existing page makes the draft that page's: optimize, its title as H1, the page type read from its address, and its URL kept in content_drafts.source_url, which the editor shows beside the page type. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Content Editor PR 6b (CE-015 overlap check): Start now lists the brand's own pages AI cites for the new page's prompts (prompts in common, citations, Google position) and recommends optimizing one that already answers half or more, else creating the page and linking them. New security-definer RPC content_page_overlap + content_drafts.source_url (migration 00207); it reads citation_urls' domain index first, as ga_page_ai_visibility does. Could you check the 50% threshold and the 30-day / 28-day windows? Stacked on #1286 → … → #1256. |
gkhngyk
left a comment
There was a problem hiding this comment.
A few fixes before merge:
-
content_page_overlapcan hit the 8 s timeout on a cold cache (supabase/migrations/00207_content_page_overlap.sql:72-81). I ran the function's query on prod data for the brand with the most citations (a source with 500 prompts, 30 days). The first run took 8.9 s and later runs took 0.5 s. The time goes into two lookups.prompt_result_citationsis probed by(url_id, brand_id), so every row needs a heap fetch forcreated_atandprompt_result_id. Then every citation does a primary-key heap read onprompt_results, a wide table (3.4 GB), just to getprompt_id. Start runs this check on every source pick, so the first pick for a big brand is the one that times out. Two fixes:- Read
prompt_idthroughidx_prompt_results_brand_created_cover(brand_id, created_atINCLUDEid, prompt_id). Addpr.brand_id = p_brand_id and pr.created_at >= p_sinceand materialize that set, so it's an index-only scan joined by hash instead of a heap read per citation. - Or add a covering index
prompt_result_citations (url_id, brand_id, created_at) include (prompt_result_id). Build it withcreate index concurrentlyoutside the migration transaction, because the table is 1.3 GB.
Also add
set plan_cache_mode = force_custom_planto the function. After five calls on one connection, plpgsql can switch to a generic plan, and with these CTE estimates that plan is much worse (see the review on #1290). - Read
-
ChatGPT Shopping citations are counted here but not in Impact (
00207_content_page_overlap.sql:75-81).content_page_impact(#1290) leaves outplatform = 'chatgpt-shopping'; this function doesn't. Start can then say "cited 4×" while the Impact tab for the same page and window shows 3. Addand pr.platform is distinct from 'chatgpt-shopping'tocited.
…unsaved text ready
- saveContentDraft takes the version the editor last saw (updated_at and
a SHA-256 of the page) and writes with .eq('updated_at', base). When
another write came first, the page tells which kind: the same page means
only other columns changed (Mark ready, the type), and the save goes over
them; another page comes back `conflict` and nothing is overwritten. The
header then says "Changed elsewhere · Reload" and autosave stops.
- Results are typed ({ ok: false, reason }) since Next.js hides server
action messages in production: a page over 500,000 characters says "Too
long to save" (and isn't sent at all), not "Couldn't save · Retry".
- Mark ready settles first: it waits for a save under way and isn't run
when the page can't be saved.
- Nit: the title limit comes from 00204.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-html # Conflicts: # web/src/lib/actions/content-drafts.test.ts # web/src/lib/actions/content-drafts.ts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…locks # Conflicts: # web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
…re Start's guess as detected - check_content_draft_links checks only the prompt ids a write adds, and a statement-level trigger on prompts removes deleted ids from every draft (prompt_ids has no foreign key), so the Brief tab's append no longer fails with 23514 once a tracked prompt is gone (00206). - Start sends whether the person picked the type: a pick is stored as 'user', Start's guess (or the Blog post fallback) as 'detected', so it follows the page. A save that finds no type keeps the one the draft had. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # supabase/schema.sql # web/src/components/content/new-content-dialog.tsx # web/src/lib/actions/content-drafts.ts
…and leave ChatGPT Shopping out content_page_overlap took 8.9 s cold on the brand with the most citations, mostly reading prompt_results' wide rows one citation at a time for prompt_id. The window's answers to the prompts now come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id and prompt_id included), materialized and hash-joined to the brand's citations and its own pages. ChatGPT Shopping answers are left out, as Impact does, so Start and Impact count the same citations. The function is planned for each call's values (plan_cache_mode = force_custom_plan). Checked against the old version on a fixture: same pages and prompts in common; the only difference is the Shopping citations. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Review fixes for #1287 are in 956303b (merged up the stack):
Checked against the old function on a fixture in a rolled-back transaction (dev data is tiny): same pages and prompts in common. The citation counts differ by exactly the Shopping citations. Could you re-run your cold/warm timing on the brand with the most citations? I can't run anything on prod. Checked on the stack's top (#1310): web 2,346 tests, tsc, lint, Prettier and |
…İ before them keeps them `toLowerCase()` turns 'İ' into two UTF-16 units, so every İ before a JSON-LD script shifted the positions taken from the lower-cased copy: the schema was dropped on save, with as many characters of the text after it. Only ASCII letters are lower-cased now, which keeps the length and stays linear. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…locks # Conflicts: # web/src/lib/content/sanitize-draft-html.test.ts
The test merged up from ansvisor#1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
left a comment
There was a problem hiding this comment.
The Shopping filter and force_custom_plan check out. The timeout risk is still there on a cold cache.
I timed the new content_page_overlap on prod: the brand with the most citations, a 500-prompt source, 30 days, custom plan.
| Run | Time |
|---|---|
| Cold-ish | 9.1 s, 10.6 s, 5.8 s |
| Warm | 0.29–0.31 s |
| Generic plan, warm | 0.22 s |
answersdoesn't use the cover index (supabase/migrations/00207_content_page_overlap.sql:81-88). Because ofpr.prompt_id = any(p_prompt_ids), the planner picks aBitmapAndofidx_prompt_results_prompt_idandidx_prompt_results_brand_created, then a Bitmap Heap Scan. That reads about 16k heap blocks ofprompt_resultson every call. Move the prompt filter out of the materialized CTE and apply it incited(and a.prompt_id = any(p_prompt_ids)). Then the CTE is an index-only scan onidx_prompt_results_brand_created_cover; I measured that variant at 0.32 s warm.- The index-only scan still goes to the heap until the visibility map is current. That scan currently does 19.5k heap fetches for the brand's 30-day window (out of 81.8k rows), so the first run of the variant was still 6.5 s.
prompt_resultswas last autovacuumed 13 days ago and has had 78k inserts since. At the defaultautovacuum_vacuum_insert_scale_factor(0.2 × 580k rows), it is only vacuumed about every three weeks, and that is exactly the window these functions read. A per-table setting keeps the visibility map current and makes the cover index truly index-only:00209 and 00211 depend on this too, so it fits best in this first migration or in a small separate one.alter table public.prompt_results set (autovacuum_vacuum_insert_scale_factor = 0.01); alter table public.prompt_result_citations set (autovacuum_vacuum_insert_scale_factor = 0.01);
The PRs below this one are squash-merged on main; this keeps only this branch's own change on top. Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
left a comment
There was a problem hiding this comment.
Merging with the stack. The open items from the last review go into a follow-up PR on main. 00204–00221 are applied on production now, so changes to them need new migration files.
The vacuum part is done separately: #1315 makes autovacuum's insert pass and analyze run about daily on prompt_results and prompt_result_citations, which keeps the cover-index scans index-only. It's applied on production.
…My rules per site type (00227) (#1316) * perf(content): bound the overlap, Sources and Plan reads in migration 00226 The third review timed four content reads on production. 00204–00221 are applied there, so 00226 redefines them: - content_page_overlap (#1287): the window's answers come from idx_prompt_results_brand_created_cover alone; the prompts are picked where the citations meet them. - content_draft_sources (#1292): the window from the cover index, each prompt's answers counted there, "named in" from mentions_prompt_daily plus the first partial day, fan-outs from each prompt's latest 30 answers, citations from their cover index hash-joined to the answers. - content_plan_pages (#1308, 00221's copy): the overlap pairs take their window from the current answers alone, no prc.created_at bounds. - content_plan_insights (#1309): own ids from the domain index, rows picked on url ids before citation_urls is read, own list capped at 5,000, force_custom_plan. Each matches its 00207–00221 version on a rolled-back dev DB fixture; the Sources fan-outs differ only where a prompt has more than 30 answers in the window. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep My rules per kind of site (00227) content_rule_sets was keyed by organization and page type, so a "guide" set saved for a B2B brand also applied to the same organization's shops and travel sites. 00227 adds site_type to the key; getMyRuleSets and saveMyRuleSet use the brand's kind of site (chosen, or guessed). A set saved before is copied to each kind, so it keeps applying where it did. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): the third review's Plan, Start, page type and prompt items - Plan (#1308): the reason reads "Citation rate −{pct}%"; Start lists the page the plan named first when the overlap check recommends another, so a person can come back to it (pages matched by address). - Collection sign (#1310): whole words of the slug, so /collections/kitchen or /collections/limited-edition are categories; the best-of sign leaves best-sellers to it. - #1310's low items: a title naming FAQ with a policy word reads as Policy, as its address does; "what is the best/difference/cost/benefits …" and "what is new" aren't definitions, in titles and paths; the numbered-steps rule checks only a how-to H1 ("Not a how-to" otherwise); "Defined first" needs the verb within the first eight words, after a subject that isn't a pronoun; the writer, brief and agent prompts name the page type and its format (content-page-types.js) instead of its key. Co-Authored-By: Claude Opus 5.5 <[email protected]> * perf(content): count the Sources tab's cited pages over the fan-outs' sample cited_ids needed every citation of the draft's window answers (106k for a 92-prompt draft on the biggest brand), read one answer at a time, and the cold first call still took 10.7 s on prod. It now reads the citations of the same sample as the fan-outs, each prompt's latest 30 answers (2,760 answers instead of 13,618). With the cap lifted it matches the previous read on the dev DB fixture. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): show the plan's page in Start when nothing overlaps Start pre-selects the page the Content plan named, but when the overlap check found no page, the box only said "Safe to create" and offered no option: the person couldn't see the draft would optimize that page, or switch to a new one. With a page from the plan and nothing overlapping, Start now offers "Optimize /page" (chosen) and "Create a new page instead". Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): fingerprint a lost save as the server stores it When a save's answer never came back, the editor sent the hash of its raw HTML as unconfirmedHash, but the server compares it with the stored page, which is sanitizeDraftHtml's output. sanitize-html rewrites most real pages (<br> to <br />, to U+00A0, links without target/rel, tables without style/colgroup), so on those pages the lost save still ended in a conflict. The editor now hashes the sanitized page, loading the sanitizer only on that path, and the server also takes a stored page equal to the one being saved as its own. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): make a decision again on the page at once, before the second save When the page changed while a decision was saved, redo.tr was built on the new page, but dispatched only after the second save (the suggestions it no longer fits going back to review). If the page changed again during that call, dispatching threw "Applying a mismatched transaction": the person saw the save-failed toast, and the page and the cards stayed as they were. The redo is now dispatched right after it is built. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): write the detected type only over the save or restore it follows The type update after a save or a restore wasn't tied to that version. A write landing between them would have its updated_at become the editor's base, and the next autosave would go over it. Both updates now match the version they follow (updated_at); otherwise the type catches up on the next save, as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs(content): put ruleSet's doc comment back above ruleSet Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): read "Defined first" past punctuation, and in English only - The verb check compared words with their punctuation attached, so "Cold brew is, simply, …" read as Missing; words are compared bare now. - The check reads English words ("is", "means", "refers to"), so for a brand whose language isn't English it shows "English only" and isn't counted. The rule context carries the brand's language. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Cihan <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Gökhan Geyik <[email protected]>
Summary
Content Editor, PR 6b of the plan: the overlap check in Start (CE-015, spec §5): "Ansvisor finds existing pages that answer the same prompts … and recommends one option."
What Start shows (v2 mockup)
Picking an existing page makes the draft that page's:
content_drafts.source_url.Migration
00207_content_page_overlap.sqlcontent_drafts.source_url text: http(s), at most 2,048 characters.content_page_overlap(p_brand_id, p_prompt_ids, p_since default now() - 30 days).ai_traffic_page_citations(00176).citation_urlshas no member select policy.citation_urls' domain index first, thenprompt_result_citationsbyurl_id, asga_page_ai_visibilitydoes.lower(normalize_page_path), so/x/and/x?utm_source=…are one page; the most cited address stands for it.gsc_page_stats.schema.sqlrebuilt.Related issue
Content Editor CE-015 (overlap check). Stacked on #1286 → #1262 → #1261 → #1260 → #1259 → #1258 → #1256.
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
Apply 00204–00207 first. The brand needs a page on its own domain cited for tracked prompts in the last 30 days.
method = 'optimize'andsource_urlis the page.Tests:
overlap.test.ts: none / covered (the 50% boundary) / partial; page paths.content-drafts-start.test.ts:getContentOverlapresolves the source's prompts and maps the RPC;sourceUrlis stored with the H1 body;new-content-dialog.test.tsx:editor/page.test.tsx: the tag names an optimize draft's page.Checked in light and dark, and at 1024 px.
Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/) (0 errors; the 6 warnings are in untouched files, as on main)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)yarn test(2,076 tests) andyarn buildpass.bash supabase/build-schema.shwas run.🤖 Generated with Claude Code