Repository navigation
perf(citations): serve the Gaps tab from daily rollups - #1257
Merged
Merged
Conversation
The Gaps tab ran citation_gap_domains and citation_competitor_sources over every answer and citation in the window on each load. On the largest brand a 30-day window took 69 s, past the authenticated role's 8 s timeout. refresh_citations_daily now also writes, from one pass over a day range: - citation_result_daily.present_answers (answers where the brand is present); - citation_gap_domain_daily: gap answers, their weight and present answers per domain; - citation_gap_competitor_daily: per domain and competitor, the answers mentioning it, their weight and how many are gap answers. citation_gap_domains_daily and citation_competitor_sources_daily read them over whole UTC days with the page's filters; the brand/competitor domain tagging and the competitor names stay at read time. A brand_domains change queues the brand for a rebuild, since presence depends on its own domains. The page reads the daily functions unless a single prompt is selected. Closes #1002 Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
Contributor
Author
|
00203 is applied to production. The new tables now fill from every refresh, and the page keeps reading the raw functions until this merges. Next: run |
8 of 12 tasks
cihan-gyk
added a commit
to cihan-gyk/ansvisor
that referenced
this pull request
Oct 20, 2026
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]>
8 of 12 tasks
8 of 12 tasks
gkhngyk
pushed a commit
that referenced
this pull request
Oct 21, 2026
* feat(content): add the Content group and its Library of drafts 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]> * chore(content): renumber the content drafts migration to 00204 #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]> --------- Co-authored-by: Cihan <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
* feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * fix(content): show links in the editor as links, and open them 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): keep Mark ready off while the page can't be saved 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
* feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> --------- Co-authored-by: Cihan <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Gökhan Geyik <[email protected]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…ick (#1260) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…es to a draft (#1261) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…pe (#1262) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
* feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…1287) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
* feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…team (#1289) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…1290) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…mpact tab (#1291) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…ces tab (#1292) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
… from the sources kept (#1293) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
… tab (#1294) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): check the page against its rules in the editor's Rules tab The editor's side panel gets its Rules tab (CE-009, spec §10): the rule set for the page's type — its own rules, then length and structure, fan-outs and keywords, links and sources, style — each with an on/off switch, a value the person can change for this draft, and its status read live from the page as written. - lib/content/rules.ts: the default sets (spec §10) and their checks: sentence length, length (the editor's count), the summary under the H1, the answer under each H2, the top fan-outs kept used as H2s, the FAQ and the fan-outs in its questions, keywords (the brief's by default), internal links, outbound links to non-competitor sites, a dated data point in the first 100 words, inline citations, AI traces, banned words, and the page types' own (tables, proof per section, steps, fit questions, intro length, best time). Tone, language and the like say "AI check", the product feed rule "Needs feed"; neither is counted. - Migration 00213: content_drafts.rules keeps only what the person changed: the set's page type and per-rule {on, value}. - The header's chip "Rules met/total" opens the Rules tab; on a narrow window it and Copy HTML go short so the header stays one line. - The length goal comes from the Length rule: the toolbar's counter, the Brief tab and Rebuild outline use it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check the rules against the brief and sources the person sees, read once - The editor reads the draft's brief and sources once (useDraftReads) and shares them: the rules check against them, the side panel's Brief and Sources tabs show them, and Rebuild outline builds from them. A rebuild, an edit of the brief, or a source checked or unchecked changes them in place, so "Keywords to include" and the fan-out rules no longer check old values until a reload, and opening Sources no longer runs content_draft_sources a second time. - The Length rule is kept within 100–50,000 characters, the range Rebuild outline builds for (the server clamps too). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…or the workspace (#1295) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): check the page against its rules in the editor's Rules tab The editor's side panel gets its Rules tab (CE-009, spec §10): the rule set for the page's type — its own rules, then length and structure, fan-outs and keywords, links and sources, style — each with an on/off switch, a value the person can change for this draft, and its status read live from the page as written. - lib/content/rules.ts: the default sets (spec §10) and their checks: sentence length, length (the editor's count), the summary under the H1, the answer under each H2, the top fan-outs kept used as H2s, the FAQ and the fan-outs in its questions, keywords (the brief's by default), internal links, outbound links to non-competitor sites, a dated data point in the first 100 words, inline citations, AI traces, banned words, and the page types' own (tables, proof per section, steps, fit questions, intro length, best time). Tone, language and the like say "AI check", the product feed rule "Needs feed"; neither is counted. - Migration 00213: content_drafts.rules keeps only what the person changed: the set's page type and per-rule {on, value}. - The header's chip "Rules met/total" opens the Rules tab; on a narrow window it and Copy HTML go short so the header stays one line. - The length goal comes from the Length rule: the toolbar's counter, the Brief tab and Rebuild outline use it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): let people write their own rules and keep a rule set for the workspace The Rules tab (CE-009, spec §10) gets the person's own rules and the workspace's set per page type. - Your text rules: "Write a rule in your own words…" adds one rule per line; Paste many takes a whole style guide, bullets and numbering off. A line with a number is a number check, the rest an AI check; neither is counted until the Content Agent scores them. They are edited in place, turned off, and removed when emptied (50 at most, 300 characters each). Pasted text is writing guidance only. - Save as my rules keeps the draft's rule choices (values, switches, text rules) for the workspace's drafts of the page type (content_rule_sets, 00214); a draft no one has set rules on starts from them, and the rule set select lists "My rules · {type}". Reset takes the draft back to Ansvisor's default set; the workspace's set stays. - content_drafts.rules also keeps where the draft's rules come from (default or mine) and its text rules; rules saved before read as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check the rules against the brief and sources the person sees, read once - The editor reads the draft's brief and sources once (useDraftReads) and shares them: the rules check against them, the side panel's Brief and Sources tabs show them, and Rebuild outline builds from them. A rebuild, an edit of the brief, or a source checked or unchecked changes them in place, so "Keywords to include" and the fan-out rules no longer check old values until a reload, and opening Sources no longer runs content_draft_sources a second time. - The Length rule is kept within 100–50,000 characters, the range Rebuild outline builds for (the server clamps too). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave saving My rules to admins and managers, and change nothing before they're read - content_rule_sets insert and update need the admin or manager role (00214), as the workspace's other settings do; every member still reads them. The Rules tab shows Save as my rules to admins and managers only. - The Rules tab's controls stay off until My rules are read, and the hook saves nothing before, so an early change can't leave the workspace's set out of the draft. - A draft on My rules for a type the workspace has none for (its detected type changed, or the read failed) shows Ansvisor's set in the picker, not the raw value. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
… any of them (#1301) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): check the page against its rules in the editor's Rules tab The editor's side panel gets its Rules tab (CE-009, spec §10): the rule set for the page's type — its own rules, then length and structure, fan-outs and keywords, links and sources, style — each with an on/off switch, a value the person can change for this draft, and its status read live from the page as written. - lib/content/rules.ts: the default sets (spec §10) and their checks: sentence length, length (the editor's count), the summary under the H1, the answer under each H2, the top fan-outs kept used as H2s, the FAQ and the fan-outs in its questions, keywords (the brief's by default), internal links, outbound links to non-competitor sites, a dated data point in the first 100 words, inline citations, AI traces, banned words, and the page types' own (tables, proof per section, steps, fit questions, intro length, best time). Tone, language and the like say "AI check", the product feed rule "Needs feed"; neither is counted. - Migration 00213: content_drafts.rules keeps only what the person changed: the set's page type and per-rule {on, value}. - The header's chip "Rules met/total" opens the Rules tab; on a narrow window it and Copy HTML go short so the header stays one line. - The length goal comes from the Length rule: the toolbar's counter, the Brief tab and Rebuild outline use it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): let people write their own rules and keep a rule set for the workspace The Rules tab (CE-009, spec §10) gets the person's own rules and the workspace's set per page type. - Your text rules: "Write a rule in your own words…" adds one rule per line; Paste many takes a whole style guide, bullets and numbering off. A line with a number is a number check, the rest an AI check; neither is counted until the Content Agent scores them. They are edited in place, turned off, and removed when emptied (50 at most, 300 characters each). Pasted text is writing guidance only. - Save as my rules keeps the draft's rule choices (values, switches, text rules) for the workspace's drafts of the page type (content_rule_sets, 00214); a draft no one has set rules on starts from them, and the rule set select lists "My rules · {type}". Reset takes the draft back to Ansvisor's default set; the workspace's set stays. - content_drafts.rules also keeps where the draft's rules come from (default or mine) and its text rules; rules saved before read as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): keep a draft's earlier versions in History and restore any of them Content Editor PR 10a (CE-018). The editor's header gets History: the draft now, then its versions of the last 90 days with their time and origin. The live page a draft was imported from and each Mark ready are kept; picking a version restores it, and the page it replaces is kept as a version too, so nothing is lost. Migration 00215 adds content_draft_versions. Members only read them; the security-definer content_draft_snapshot and content_draft_restore copy the draft's own checked title and body, so no hand-made HTML can be restored. The server's daily run prunes versions older than 90 days (content_draft_versions_prune). A restore saves what is waiting first, locks the page while it runs and drops nothing newer than the server's page (autosave settle and discard); Mark ready settles too, so the version it keeps is the page on screen. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): expect the restore's save with the version it goes over Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check the rules against the brief and sources the person sees, read once - The editor reads the draft's brief and sources once (useDraftReads) and shares them: the rules check against them, the side panel's Brief and Sources tabs show them, and Rebuild outline builds from them. A rebuild, an edit of the brief, or a source checked or unchecked changes them in place, so "Keywords to include" and the fan-out rules no longer check old values until a reload, and opening Sources no longer runs content_draft_sources a second time. - The Length rule is kept within 100–50,000 characters, the range Rebuild outline builds for (the server clamps too). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave saving My rules to admins and managers, and change nothing before they're read - content_rule_sets insert and update need the admin or manager role (00214), as the workspace's other settings do; every member still reads them. The Rules tab shows Save as my rules to admins and managers only. - The Rules tab's controls stay off until My rules are read, and the hook saves nothing before, so an early change can't leave the workspace's set out of the draft. - A draft on My rules for a type the workspace has none for (its detected type changed, or the read failed) shows Ansvisor's set in the picker, not the raw value. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep a draft's newest 50 versions, skip repeats, and leave publish versions to the server - content_draft_keep_version (internal, used by content_draft_snapshot and content_draft_restore) skips the insert when the draft's latest version is already this page (a restore after a restore, Mark ready on an unchanged page) and deletes the draft's versions beyond the newest 50, the most History lists, in the same transaction. - A restore of the page the draft already is changes and keeps nothing. - Members write import, agent_before and ready versions; a publish version is the server's, so no one can add a "Published" entry by hand. Checked on the dev DB in a rolled-back transaction: one version for the same page twice, null for a member's publish, 50 kept after 60 pages, and no new version for a repeated restore. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…nging one (#1302) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): check the page against its rules in the editor's Rules tab The editor's side panel gets its Rules tab (CE-009, spec §10): the rule set for the page's type — its own rules, then length and structure, fan-outs and keywords, links and sources, style — each with an on/off switch, a value the person can change for this draft, and its status read live from the page as written. - lib/content/rules.ts: the default sets (spec §10) and their checks: sentence length, length (the editor's count), the summary under the H1, the answer under each H2, the top fan-outs kept used as H2s, the FAQ and the fan-outs in its questions, keywords (the brief's by default), internal links, outbound links to non-competitor sites, a dated data point in the first 100 words, inline citations, AI traces, banned words, and the page types' own (tables, proof per section, steps, fit questions, intro length, best time). Tone, language and the like say "AI check", the product feed rule "Needs feed"; neither is counted. - Migration 00213: content_drafts.rules keeps only what the person changed: the set's page type and per-rule {on, value}. - The header's chip "Rules met/total" opens the Rules tab; on a narrow window it and Copy HTML go short so the header stays one line. - The length goal comes from the Length rule: the toolbar's counter, the Brief tab and Rebuild outline use it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): let people write their own rules and keep a rule set for the workspace The Rules tab (CE-009, spec §10) gets the person's own rules and the workspace's set per page type. - Your text rules: "Write a rule in your own words…" adds one rule per line; Paste many takes a whole style guide, bullets and numbering off. A line with a number is a number check, the rest an AI check; neither is counted until the Content Agent scores them. They are edited in place, turned off, and removed when emptied (50 at most, 300 characters each). Pasted text is writing guidance only. - Save as my rules keeps the draft's rule choices (values, switches, text rules) for the workspace's drafts of the page type (content_rule_sets, 00214); a draft no one has set rules on starts from them, and the rule set select lists "My rules · {type}". Reset takes the draft back to Ansvisor's default set; the workspace's set stays. - content_drafts.rules also keeps where the draft's rules come from (default or mine) and its text rules; rules saved before read as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): keep a draft's earlier versions in History and restore any of them Content Editor PR 10a (CE-018). The editor's header gets History: the draft now, then its versions of the last 90 days with their time and origin. The live page a draft was imported from and each Mark ready are kept; picking a version restores it, and the page it replaces is kept as a version too, so nothing is lost. Migration 00215 adds content_draft_versions. Members only read them; the security-definer content_draft_snapshot and content_draft_restore copy the draft's own checked title and body, so no hand-made HTML can be restored. The server's daily run prunes versions older than 90 days (content_draft_versions_prune). A restore saves what is waiting first, locks the page while it runs and drops nothing newer than the server's page (autosave settle and discard); Mark ready settles too, so the version it keeps is the page on screen. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): lock the passages AI answers quote, and ask before changing one Content Editor PR 10b (CE-018). A draft of an existing page marks the passages AI answers quote today: a green line and "Cited by ChatGPT 14× and Perplexity 6× in 30 days · keep wording" above each, and "N cited passages kept" in the header on wide windows. Typing in one, deleting it, pasting over it or joining it to another is held and asked about ("AI quotes this passage"): Keep wording drops the change, Edit anyway lets it through, the held paste or keystroke included. Migration 00216 adds content_draft_cited_answers: the answers of the last 30 days whose citations name the draft's page (security definer, with the organization check). getCitedPassages matches them on the server: a run of eight of a passage's words in a row is a quote, or all of a six- or seven-word one. A restore and the HTML view may change locked passages: they were the person's to write. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): expect the restore's save with the version it goes over Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): read only the 200 latest cited answers' responses, and match the page on its host content_draft_cited_answers read and cut every citing answer's response before keeping 200 (5.0 s cold on the busiest page; 123 ms when the 200 are picked first). It now picks the latest 200 answer ids first and reads responses for those only. The page is the source URL's path on that URL's host, which must be one of the brand's domains, so /pricing on another of the brand's sites, or on a site that isn't the brand's, no longer brings locks. Planned for each call's values (plan_cache_mode = force_custom_plan). Checked against the old version on a fixture: identical for the brand's own page; a competitor's page with the same path now gets none. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check the rules against the brief and sources the person sees, read once - The editor reads the draft's brief and sources once (useDraftReads) and shares them: the rules check against them, the side panel's Brief and Sources tabs show them, and Rebuild outline builds from them. A rebuild, an edit of the brief, or a source checked or unchecked changes them in place, so "Keywords to include" and the fan-out rules no longer check old values until a reload, and opening Sources no longer runs content_draft_sources a second time. - The Length rule is kept within 100–50,000 characters, the range Rebuild outline builds for (the server clamps too). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave saving My rules to admins and managers, and change nothing before they're read - content_rule_sets insert and update need the admin or manager role (00214), as the workspace's other settings do; every member still reads them. The Rules tab shows Save as my rules to admins and managers only. - The Rules tab's controls stay off until My rules are read, and the hook saves nothing before, so an early change can't leave the workspace's set out of the draft. - A draft on My rules for a type the workspace has none for (its detected type changed, or the read failed) shows Ansvisor's set in the picker, not the raw value. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep a draft's newest 50 versions, skip repeats, and leave publish versions to the server - content_draft_keep_version (internal, used by content_draft_snapshot and content_draft_restore) skips the insert when the draft's latest version is already this page (a restore after a restore, Mark ready on an unchanged page) and deletes the draft's versions beyond the newest 50, the most History lists, in the same transaction. - A restore of the page the draft already is changes and keeps nothing. - Members write import, agent_before and ready versions; a publish version is the server's, so no one can add a "Published" entry by hand. Checked on the dev DB in a rolled-back transaction: one version for the same page twice, null for a member's publish, 50 kept after 60 pages, and no new version for a repeated restore. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check and mark locked passages only in the blocks a change touches Every keystroke used to run passageKey (NFKC and a regex split) on every text block of both docs, rebuild every mark, and count the page again. Now: - a block's key is kept in a WeakMap by node, so blocks a change didn't touch (the same node objects) are worked out once; - filterTransaction compares the locked passages among the blocks the transaction touched, before and after (from its step maps), so moving a passage is still fine and one taken out is held; - the marks live in the plugin state, mapped through each change, with only the touched blocks marked again; the header's count reads them. Test: typing in one paragraph of a 200-paragraph page reads at most that paragraph's key twice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep a locked passage's mark when typing beside it, and read an upper-case scheme - DecorationSet.find is inclusive at both ends, so re-marking an edited block also removed the marks of the blocks right before and after it: a quoted passage beside the edit lost its line and label while still locked. Only the block's own mark is taken off now, with a test. - 00216 lower-cases the source address before reading its host, so an HTTPS:// address gets its locks. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…eject each (#1303) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): check the page against its rules in the editor's Rules tab The editor's side panel gets its Rules tab (CE-009, spec §10): the rule set for the page's type — its own rules, then length and structure, fan-outs and keywords, links and sources, style — each with an on/off switch, a value the person can change for this draft, and its status read live from the page as written. - lib/content/rules.ts: the default sets (spec §10) and their checks: sentence length, length (the editor's count), the summary under the H1, the answer under each H2, the top fan-outs kept used as H2s, the FAQ and the fan-outs in its questions, keywords (the brief's by default), internal links, outbound links to non-competitor sites, a dated data point in the first 100 words, inline citations, AI traces, banned words, and the page types' own (tables, proof per section, steps, fit questions, intro length, best time). Tone, language and the like say "AI check", the product feed rule "Needs feed"; neither is counted. - Migration 00213: content_drafts.rules keeps only what the person changed: the set's page type and per-rule {on, value}. - The header's chip "Rules met/total" opens the Rules tab; on a narrow window it and Copy HTML go short so the header stays one line. - The length goal comes from the Length rule: the toolbar's counter, the Brief tab and Rebuild outline use it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): let people write their own rules and keep a rule set for the workspace The Rules tab (CE-009, spec §10) gets the person's own rules and the workspace's set per page type. - Your text rules: "Write a rule in your own words…" adds one rule per line; Paste many takes a whole style guide, bullets and numbering off. A line with a number is a number check, the rest an AI check; neither is counted until the Content Agent scores them. They are edited in place, turned off, and removed when emptied (50 at most, 300 characters each). Pasted text is writing guidance only. - Save as my rules keeps the draft's rule choices (values, switches, text rules) for the workspace's drafts of the page type (content_rule_sets, 00214); a draft no one has set rules on starts from them, and the rule set select lists "My rules · {type}". Reset takes the draft back to Ansvisor's default set; the workspace's set stays. - content_drafts.rules also keeps where the draft's rules come from (default or mine) and its text rules; rules saved before read as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): keep a draft's earlier versions in History and restore any of them Content Editor PR 10a (CE-018). The editor's header gets History: the draft now, then its versions of the last 90 days with their time and origin. The live page a draft was imported from and each Mark ready are kept; picking a version restores it, and the page it replaces is kept as a version too, so nothing is lost. Migration 00215 adds content_draft_versions. Members only read them; the security-definer content_draft_snapshot and content_draft_restore copy the draft's own checked title and body, so no hand-made HTML can be restored. The server's daily run prunes versions older than 90 days (content_draft_versions_prune). A restore saves what is waiting first, locks the page while it runs and drops nothing newer than the server's page (autosave settle and discard); Mark ready settles too, so the version it keeps is the page on screen. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): lock the passages AI answers quote, and ask before changing one Content Editor PR 10b (CE-018). A draft of an existing page marks the passages AI answers quote today: a green line and "Cited by ChatGPT 14× and Perplexity 6× in 30 days · keep wording" above each, and "N cited passages kept" in the header on wide windows. Typing in one, deleting it, pasting over it or joining it to another is held and asked about ("AI quotes this passage"): Keep wording drops the change, Edit anyway lets it through, the held paste or keystroke included. Migration 00216 adds content_draft_cited_answers: the answers of the last 30 days whose citations name the draft's page (security definer, with the organization check). getCitedPassages matches them on the server: a run of eight of a passage's words in a row is a quote, or all of a six- or seven-word one. A restore and the HTML view may change locked passages: they were the person's to write. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): review an agent's suggestions in the page, accept or reject each Content Editor PR 10c (CE-018). An agent's suggestions sit in the page as cards where they apply: who made each and why, the words it removes in red and adds in green, the target marked amber, and Reject / Accept. Accepting changes the page (a thin green line, "Accepted" and Undo); rejecting leaves a dashed card with Restore. The agent bar says how many are open and which action they came from, with Accept all / Reject all for open ones; once all are decided, how many were accepted and rejected and how many rules are still open, with Undo all. Migration 00217 adds content_draft_suggestions: a replace (words in a passage) or an insert (blocks after one), one batch per agent run. Members read them and decide through content_draft_decide_suggestions, which keeps who decided and when; agents write them through the server (part D). History keeps the page before the first change accepted ("Before agent changes"). A suggestion on a passage AI quotes is never applied, one the page changed since can only be rejected, and the HTML view waits until every one is decided. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): expect the restore's save with the version it goes over Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): read only the 200 latest cited answers' responses, and match the page on its host content_draft_cited_answers read and cut every citing answer's response before keeping 200 (5.0 s cold on the busiest page; 123 ms when the 200 are picked first). It now picks the latest 200 answer ids first and reads responses for those only. The page is the source URL's path on that URL's host, which must be one of the brand's domains, so /pricing on another of the brand's sites, or on a site that isn't the brand's, no longer brings locks. Planned for each call's values (plan_cache_mode = force_custom_plan). Checked against the old version on a fixture: identical for the brand's own page; a competitor's page with the same path now gets none. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check the rules against the brief and sources the person sees, read once - The editor reads the draft's brief and sources once (useDraftReads) and shares them: the rules check against them, the side panel's Brief and Sources tabs show them, and Rebuild outline builds from them. A rebuild, an edit of the brief, or a source checked or unchecked changes them in place, so "Keywords to include" and the fan-out rules no longer check old values until a reload, and opening Sources no longer runs content_draft_sources a second time. - The Length rule is kept within 100–50,000 characters, the range Rebuild outline builds for (the server clamps too). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave saving My rules to admins and managers, and change nothing before they're read - content_rule_sets insert and update need the admin or manager role (00214), as the workspace's other settings do; every member still reads them. The Rules tab shows Save as my rules to admins and managers only. - The Rules tab's controls stay off until My rules are read, and the hook saves nothing before, so an early change can't leave the workspace's set out of the draft. - A draft on My rules for a type the workspace has none for (its detected type changed, or the read failed) shows Ansvisor's set in the picker, not the raw value. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep a draft's newest 50 versions, skip repeats, and leave publish versions to the server - content_draft_keep_version (internal, used by content_draft_snapshot and content_draft_restore) skips the insert when the draft's latest version is already this page (a restore after a restore, Mark ready on an unchanged page) and deletes the draft's versions beyond the newest 50, the most History lists, in the same transaction. - A restore of the page the draft already is changes and keeps nothing. - Members write import, agent_before and ready versions; a publish version is the server's, so no one can add a "Published" entry by hand. Checked on the dev DB in a rolled-back transaction: one version for the same page twice, null for a member's publish, 50 kept after 60 pages, and no new version for a repeated restore. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check and mark locked passages only in the blocks a change touches Every keystroke used to run passageKey (NFKC and a regex split) on every text block of both docs, rebuild every mark, and count the page again. Now: - a block's key is kept in a WeakMap by node, so blocks a change didn't touch (the same node objects) are worked out once; - filterTransaction compares the locked passages among the blocks the transaction touched, before and after (from its step maps), so moving a passage is still fine and one taken out is held; - the marks live in the plugin state, mapped through each change, with only the touched blocks marked again; the header's count reads them. Test: typing in one paragraph of a 200-paragraph page reads at most that paragraph's key twice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save a suggestion decision before changing the page, take $ as written, and place cards only on change - decide builds the page's change, saves the decision with the page held still, and only then applies the change and the cards' new status: a failed save leaves the page and the row in step. - The accepted/undone text lookups use a replacement function, so $&, $$, $' and $` in the page or the agent's text are taken as written. - The cards and marks live in the plugin state and are placed again only when the page, the suggestions or the locks change, not on every selection move; block keys come from the locked-passages cache (blockKey), and an insert's blocks are parsed once per HTML. The locks are passed in from the transaction or the previous state, since the locks plugin may not have applied the transaction yet. Tests: a failed decision changes nothing; a passage with "$$" and "$&" can be accepted and undone. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): find JSON-LD scripts by ASCII lower case, so a Turkish İ 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]> * fix(content): read a source page's host from an upper-case scheme too `substring(source_url from '^https?://…')` is case-sensitive, while Start takes /^https?:\/\//i, so an HTTPS:// address got no host and no sources from its page. The address is lower-cased before the host is read (00211). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep a locked passage's mark when typing beside it, and read an upper-case scheme - DecorationSet.find is inclusive at both ends, so re-marking an edited block also removed the marks of the blocks right before and after it: a quoted passage beside the edit lost its line and label while still locked. Only the block's own mark is taken off now, with a test. - 00216 lower-cases the source address before reading its host, so an HTTPS:// address gets its locks. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): read the Turkish İ case through extractKeptBlocks The test merged up from #1259 used extractJsonLd, which this branch replaces with extractKeptBlocks. 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]>
gkhngyk
added a commit
that referenced
this pull request
Oct 21, 2026
…#1304) * feat(content): add the Content group and its Library of drafts 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]> * feat(content): write and save drafts in the content editor Content Editor CE-004, stacked on the Library (#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]> * feat(content): clean pasted content and edit a draft as HTML Content Editor CE-005 and CE-020, stacked on the editor core (#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]> * fix(content): use a sanitize-html that runs on Node 20 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]> * fix(content): show links in the editor as links, and open them 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]> * feat(content): add HTML blocks to a draft and copy its HTML in one click 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]> * test(content): measure ranges in jsdom for the editor's scroll 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]> * feat(content): attach spreadsheets, Word, Markdown, HTML and text files 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]> * feat(content): detect a draft's page type and set the brand's site type 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]> * chore(content): renumber the content drafts migration to 00204 #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]> * feat(content): start a draft from New content and Start 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]> * feat(content): check for overlapping pages before a draft is started 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]> * feat(content): import a brand page by its URL into a draft Optimize content gets a Page URL option (CE-003), and Start's "Optimize this page instead" now brings the page's live text. The API reads the page through a new guarded fetch (server lib/safe-fetch.js): - http(s) on the web ports, no credentials in the address; - every address the host resolves to must be public, checked in the connection's own lookup, and an address written as an IP checked before it, since a literal skips the lookup; - redirects followed by hand and checked the same way; 10 s, 3 MB, HTML only. POST /api/content-pages/import reads only the brand's own domains, before and after redirects, and returns the page's main content, title and JSON-LD (lib/page-content.js). The web cleans it like a paste and reads the page type from the address and the content. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): choose who does the page in Start, and send it to the team Start's Who does it (CE-015): Me opens the editor; Agent waits for the Content Agent; Team sends the draft to the Action Center as an action for someone on the team to write. The API gets a person-sent action kind, content_draft (from-content-draft.js, POST /api/action-center/content-drafts): a new page's or an existing page's library tasks, as an opportunity's page gets, prioritised and measured on the draft's prompts and page. The draft records its action (content_drafts.action_id, migration 00208, server-set: the drafts guard is redefined to keep members from writing it). The Action Center names it "Write: …" / "Optimize: …" and links back to the draft. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show what the page earns in the editor's Impact tab The editor gets its right side panel (Content Editor spec v2 §6), with the Impact tab first (CE-016): for the live page a draft optimizes, the last 7, 30, 90 or 365 days against the period before. - content_page_impact (00209): citations on the brand's own domains, AI visits by ai_traffic_merged's rule (snippet on its days, GA4 otherwise), Search Console clicks with the first day of page data, the prompts citing the page in either window with their platforms, and the brand's other pages cited for the same prompts. Security definer with an organization check; whole UTC days, today included. - Impact tab: four cards with their change (low sample under 30, as the AI Traffic page), prompts cited with the lost ones marked, "See in Citations", the overlap line and where the numbers come from; a new page says there is nothing to measure yet. - The panel opens beside the page on a wide window, closes from the header and remembers the choice. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave Analytics sessions without a landing page out of the page's AI visits normalize_page_path('') is '/', so a GA4 row with no landing page read as the home page's visit. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): show the results from AI visits per AI source in the Impact tab The Impact tab (CE-016, spec §7) now shows what visitors from AI assistants did after landing on the page, and which assistant sent them. - content_page_results (00210): per AI source key, the page's AI visits by ai_traffic_merged's rule (they add up to the AI visits card) and Google Analytics' AI sessions landing on it, with key events, sessions with a key event, purchases and revenue; whether a property is mapped and whether it reported purchases in the window. Security definer with an organization check, same window as content_page_impact. - Results from AI visits: key events and key event rate (low sample under 30 sessions), plus orders and revenue when the property reports purchases; a table by AI source (visits, key events, revenue), one row per platform name with unnamed keys as Other. Without Google Analytics, the visits per source and a link to AI Traffic to connect it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): list the sources a draft draws on in the editor's Sources tab The editor's side panel gets its Sources tab (CE-008, spec §10): every source the draft draws on, by name, with where the draft uses it. - content_draft_sources (00211): over the last 30 days, the draft's prompts and those whose answers cited its page, the searches AI ran for them (prompt_results.search_queries), the pages their answers cited, the brand's Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft's brand. A table of the same name keeps a person's choices: a source left out, a page or query added by hand (member RLS through content_drafts). - Sources tab: "Built from N sources" with counts per group; Prompts, Fan-outs, Cited pages (kind named by the citations classifier) and Search Console (queries sharing half their words with the draft); each row with a checkbox, its numbers and where the draft uses it now — a heading or paragraph carrying three quarters of its words, an outbound or internal link, or this page. - + Add source: a prompt joins the draft's prompts; a page address or a Search Console query is kept as added by hand. - The panel opens Sources only when its tab is picked and keeps a tab mounted once opened. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept The editor's side panel gets its Brief tab (CE-007, spec §10), between Impact and Sources: the page type and target address, then the goal, audience and length, and an outline whose H2s each answer a search AI ran (a fan-out) on a platform. - Rebuild outline: POST /api/content-drafts/:draftId/brief writes the brief from the sources the person kept in Sources (sent by the web; the server keeps only the brand's prompts), the page's headings and the length its type asks for. An H2 keeps a fan-out only when it is one kept, with a platform that ran it. Metered from the organization's AI usage (enforceImproveQuota, prompt_improve_usage), not the content brief quota, which stays with Opportunities' Generate Brief. - Migration 00212: content_drafts.brief (jsonb, 64 KB at most) and prompt_improve_usage.content_draft_id. - Edit brief changes the goal, audience, sections, key points and keywords by hand, keeping each H2's fan-out; a draft without a brief shows the brief of the opportunity it started from. - Sources gets "Rebuild with selection", and Impact "Use lost prompts in this draft" (they join the draft's prompts); both rebuild the brief and open it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): check the page against its rules in the editor's Rules tab The editor's side panel gets its Rules tab (CE-009, spec §10): the rule set for the page's type — its own rules, then length and structure, fan-outs and keywords, links and sources, style — each with an on/off switch, a value the person can change for this draft, and its status read live from the page as written. - lib/content/rules.ts: the default sets (spec §10) and their checks: sentence length, length (the editor's count), the summary under the H1, the answer under each H2, the top fan-outs kept used as H2s, the FAQ and the fan-outs in its questions, keywords (the brief's by default), internal links, outbound links to non-competitor sites, a dated data point in the first 100 words, inline citations, AI traces, banned words, and the page types' own (tables, proof per section, steps, fit questions, intro length, best time). Tone, language and the like say "AI check", the product feed rule "Needs feed"; neither is counted. - Migration 00213: content_drafts.rules keeps only what the person changed: the set's page type and per-rule {on, value}. - The header's chip "Rules met/total" opens the Rules tab; on a narrow window it and Copy HTML go short so the header stays one line. - The length goal comes from the Length rule: the toolbar's counter, the Brief tab and Rebuild outline use it. Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): mock the Supabase client in the draft brief route test The route test loaded the real content-brief module, whose Supabase client exits the process without credentials, as in CI. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): let people write their own rules and keep a rule set for the workspace The Rules tab (CE-009, spec §10) gets the person's own rules and the workspace's set per page type. - Your text rules: "Write a rule in your own words…" adds one rule per line; Paste many takes a whole style guide, bullets and numbering off. A line with a number is a number check, the rest an AI check; neither is counted until the Content Agent scores them. They are edited in place, turned off, and removed when emptied (50 at most, 300 characters each). Pasted text is writing guidance only. - Save as my rules keeps the draft's rule choices (values, switches, text rules) for the workspace's drafts of the page type (content_rule_sets, 00214); a draft no one has set rules on starts from them, and the rule set select lists "My rules · {type}". Reset takes the draft back to Ansvisor's default set; the workspace's set stays. - content_drafts.rules also keeps where the draft's rules come from (default or mine) and its text rules; rules saved before read as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): keep a draft's earlier versions in History and restore any of them Content Editor PR 10a (CE-018). The editor's header gets History: the draft now, then its versions of the last 90 days with their time and origin. The live page a draft was imported from and each Mark ready are kept; picking a version restores it, and the page it replaces is kept as a version too, so nothing is lost. Migration 00215 adds content_draft_versions. Members only read them; the security-definer content_draft_snapshot and content_draft_restore copy the draft's own checked title and body, so no hand-made HTML can be restored. The server's daily run prunes versions older than 90 days (content_draft_versions_prune). A restore saves what is waiting first, locks the page while it runs and drops nothing newer than the server's page (autosave settle and discard); Mark ready settles too, so the version it keeps is the page on screen. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): lock the passages AI answers quote, and ask before changing one Content Editor PR 10b (CE-018). A draft of an existing page marks the passages AI answers quote today: a green line and "Cited by ChatGPT 14× and Perplexity 6× in 30 days · keep wording" above each, and "N cited passages kept" in the header on wide windows. Typing in one, deleting it, pasting over it or joining it to another is held and asked about ("AI quotes this passage"): Keep wording drops the change, Edit anyway lets it through, the held paste or keystroke included. Migration 00216 adds content_draft_cited_answers: the answers of the last 30 days whose citations name the draft's page (security definer, with the organization check). getCitedPassages matches them on the server: a run of eight of a passage's words in a row is a quote, or all of a six- or seven-word one. A restore and the HTML view may change locked passages: they were the person's to write. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): review an agent's suggestions in the page, accept or reject each Content Editor PR 10c (CE-018). An agent's suggestions sit in the page as cards where they apply: who made each and why, the words it removes in red and adds in green, the target marked amber, and Reject / Accept. Accepting changes the page (a thin green line, "Accepted" and Undo); rejecting leaves a dashed card with Restore. The agent bar says how many are open and which action they came from, with Accept all / Reject all for open ones; once all are decided, how many were accepted and rejected and how many rules are still open, with Undo all. Migration 00217 adds content_draft_suggestions: a replace (words in a passage) or an insert (blocks after one), one batch per agent run. Members read them and decide through content_draft_decide_suggestions, which keeps who decided and when; agents write them through the server (part D). History keeps the page before the first change accepted ("Before agent changes"). A suggestion on a passage AI quotes is never applied, one the page changed since can only be rejected, and the HTML view waits until every one is decided. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(content): let the Content Agent suggest fixes for the open rules Content Editor PR 10d (CE-018). Fix open rules with agent, in the Rules tab and on the agent bar once a batch is decided, sends the rules the page doesn't meet yet (with what each asks and how the page reads now), the person's own text rules and the locked passages. The server's Content Agent reads the draft as saved and leaves a new batch of suggestions for review; "Remove AI traces" gets its own Fix that asks for that rule only. Nothing is offered while suggestions are still open. The agent is metered from the organization's AI usage, as Rebuild outline is. Its suggestions are kept only where the editor can apply them: a replace's words found in its passage and never on a passage AI quotes, an insert's HTML cleaned to simple blocks, at most eight, linked to the draft's Action Center action. A fact it doesn't have becomes a [placeholder], never an invented one. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): save only over the page the editor saw, and never mark 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]> * fix(content): find JSON-LD scripts with a linear scan, not a backtracking regex The JSON-LD pattern had two [^>]* runs around \btype, so input with many unclosed `<script type=application/ld+json ` tags took cubic time (about 16 s at 33k characters), and the server runs it on every save. It is now a scan (indexOf for the tag, its end and </script>, the type tested on the tag alone), linear in the length; a 500,000-character page built to backtrack takes milliseconds. The paste cleaner uses the same scan. sanitize-draft-html.ts now says stored HTML is untrusted: a member can write body_html through PostgREST past this check, so readers parse or clean it again. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): insert only the sheet rows that fit in the page's size limit "Insert all N rows" had no upper bound: the editor writes each cell as <td colspan="1" rowspan="1"><p>…</p></td>, so a wide sheet passed the 500,000-character body limit after a few hundred rows, and from then on nothing typed was saved. The preview now measures the table as the editor saves it against the room left in the page (rowsThatFit): a table that doesn't fit offers "Insert the first N rows" after saying why, and one with no room at all can't be inserted. The sheet picker passes `items` to Select, as the repo's Base UI selects do. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): drop the import the merge doubled Co-Authored-By: Claude Opus 5.5 <[email protected]> * test(content): expect the restore's save with the version it goes over Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep Mark ready off while the page can't be saved Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): keep drafts writable after a prompt is deleted, and store 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]> * fix(content): read the overlap check's answers from the cover index, 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]> * fix(content): make content_page_impact fast on big brands, count prompts in SQL, end windows yesterday - plan_cache_mode = force_custom_plan: after five calls plpgsql switched to a generic plan (7.8 s at 30 days, 83 s at 1 year on the biggest brand), so it would have started failing once pooled connections warmed. - Both windows' answers come from idx_prompt_results_brand_created_cover alone (brand_id, created_at, with id, platform and prompt_id included), materialized and hash-joined, instead of a primary-key read of prompt_results per citation; the brand's other pages are found from the prompts citing this one outward, not from every own URL. - promptCounts {cur, prev, lost} come from SQL over all prompts; the list stays capped at 100 for display, so the card, "N lost" and the overlap line no longer undercount. - Windows are whole UTC days ending yesterday, so today's partial day isn't compared with whole ones. Checked against the old version on a fixture (same windows): identical. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): end content_page_results' window yesterday, as Impact's, and plan each call The Results section's AI visits add up to the Impact tab's, so its window now ends yesterday too, and it is planned for each call's own values (plan_cache_mode = force_custom_plan), as the overview asked for every security-definer read in the stack. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): bound the Sources read by brand and window, match the page on its host, and stop per-keystroke re-renders content_draft_sources (00211): - answers are bounded by (brand_id, created_at), not every result each prompt ever had; the page's prompts come from the window's answers on the cover index; citations are grouped by address before the top 20 addresses are read; answer counts come from one group by; planned for each call's values (plan_cache_mode = force_custom_plan). - prompts are the brand's through prompt_sets, so a prompt with no topic shows its answers, fan-outs and cited pages. - the page is the source URL's path on that URL's host, which must be one of the brand's domains (the same fix as #1302's): /pricing on another site no longer matches, and a draft with no page no longer matches the brand's home page. - content_draft_sources.updated_at has the handle_updated_at trigger. Editor: the side panel and the type chip read the page once typing pauses (PAGE_READ_DELAY_MS), not on every keystroke. Sources: each toggle changes its own row from the latest state, and a failed one puts back only that row. Checked against the old version on a fixture: identical for the brand's own page. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): read only the 200 latest cited answers' responses, and match the page on its host content_draft_cited_answers read and cut every citing answer's response before keeping 200 (5.0 s cold on the busiest page; 123 ms when the 200 are picked first). It now picks the latest 200 answer ids first and reads responses for those only. The page is the source URL's path on that URL's host, which must be one of the brand's domains, so /pricing on another of the brand's sites, or on a site that isn't the brand's, no longer brings locks. Planned for each call's values (plan_cache_mode = force_custom_plan). Checked against the old version on a fixture: identical for the brand's own page; a competitor's page with the same path now gets none. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): cut the brief to the editor's limits, charge failed calls, and take long sources - The model's goal, audience, headings, key points and keywords are cut to the limits the web reads a brief with (draftBriefSchema), an empty heading or key point is dropped, and the lists are capped, so a brief saved and charged for no longer reads as lost. The model schema asks for the counts instead of enforcing them. - A call whose answer didn't fit the schema is charged from err.usage, as Improve does. - The rebuild's sources cut long fan-outs, queries and headings to 300 characters (dropping empty ones) and bring the length into 100–50,000, instead of failing the whole rebuild with a 400. - 402 (no active subscription) answers code no_subscription with its own message, not "AI usage is used up". - Prompts are the brand's through prompt_sets, so one with no topic counts. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): check the rules against the brief and sources the person sees, read once - The editor reads the draft's brief and sources once (useDraftReads) and shares them: the rules check against them, the side panel's Brief and Sources tabs show them, and Rebuild outline builds from them. A rebuild, an edit of the brief, or a source checked or unchecked changes them in place, so "Keywords to include" and the fan-out rules no longer check old values until a reload, and opening Sources no longer runs content_draft_sources a second time. - The Length rule is kept within 100–50,000 characters, the range Rebuild outline builds for (the server clamps too). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(content): leave saving My rules to admins and managers, and change nothing before they're read - content_rule_sets insert and update need the admin or manager role (00214), as the workspace's other settings do; every member still reads them. The Rules tab shows Save as my rules to admins and managers only. - The Rules tab's controls stay off until My rules are read, and the hook saves nothing before, so an early change can't leave the workspace's set out of the draft. - A draft on My rules for
Summary
The Citations page's Domains and URLs tabs read daily rollups since 00118, but the Gaps tab still ran
citation_gap_domainsandcitation_competitor_sourceson every load. Both scan every answer and citation in the window and unpackcompetitor_mentions. On the largest brand a 30-day window took 69 s, so the tab failed against the authenticated role's 8 s timeout.Database (
00203_citation_gap_rollups.sql)refresh_citations_dailywrites three more things, at the same grain ascitation_domain_daily(day, model, platform, region, topic), from one pass over the day range's answers and citations:citation_result_daily.present_answers: answers where the brand is present (mentioned, or one of its domains cited), forour_answer_count;citation_gap_domain_daily: per domain, the gap answers (a competitor mentioned, the brand absent), their weight, and the present answers (forappears_in_ours);citation_gap_competitor_daily: per domain and competitor, the answers mentioning it and their weight (forcitation_competitor_sources), and how many of them are gap answers (forcompetitor_names).nulls not distinct) and RLS select policies, like the other citation rollups.citation_gap_domains_dailyandcitation_competitor_sources_dailyreturn the same rows as the raw functions over whole UTC days.force_custom_plan.competitorstable, falling back to the name in the answer.brand_domains(insert, delete, or a changed domain) queues the brand incitation_rollup_rebuilds, and the existing drain (every five minutes) rebuilds its history, as for a topic move.Web
getCitationGapsreads the daily functions with the same windows as the other tabs (rollupWindow):A single-prompt filter, and 24h before the first completed run, stay on the raw functions. New tests in
citations-gaps.test.ts.Server
Comments only: the rebuild queue now also takes brand domain changes, and
backfill-citations-daily.jsfills the new tables too, through the same refresh.Measured on production
Everything below ran in rolled-back transactions.
Same results as the raw functions on a 7-day whole-day window, as a member of each brand's organization. Three brands: the largest, a mid-size one, and one with 102 competitors.
Speed, largest brand, 30 days:
Refresh cost. The gap pass adds about 24 s to a 14-day chunk on the largest brand. The existing refresh is ~12 s, so a backfill chunk is ~36 s, inside the service role's 120 s timeout. A 3-day refresh on a mid-size brand took 5 s in total.
The migration itself, run whole and rolled back:
is_primary-only update.Rollout
node src/scripts/backfill-citations-daily.jsso the history gets the new rows. It is idempotent and restartable.No server deploy is needed: the refresh is SQL, and the server changes are comments.
Related issue
Closes #1002
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 testsChecklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)Also: web tests (1,898) and server lint, format and tests (1,919);
supabase/schema.sqlrebuilt withbuild-schema.sh.🤖 Generated with Claude Code
https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A