@aglyn/plugins-ai 1.20.3 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-improve.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * IMPROVE IT, GENERATIVE: A PAGE REDESIGNED FROM A LEDGER (AGL-4152).\n *\n * Today's Improve it draws the source's layout in a new design and rewords its\n * lines in place. Behind `SITE_IMPORT_GENERATIVE_RELEASE_FLAG` a main page is\n * instead designed the way Start with AI designs one, from what the import\n * read: one `submit_improved_page` answer plans the sections and the grid and\n * writes the words, and code places what the source holds.\n *\n * 1. The answer is told the page as a LEDGER (`aiSiteImportLedgerText`): each\n * picture, form, plan, table, quote, video and contact line by a ref a\n * `keep` block places, each link's destination, and the numbered lines it\n * rewrites freely.\n * 2. It is held by code: the honesty validator over its words and its refs\n * (`ai-site-import-honesty.ts`), then the page compiled and scored on the\n * kept ledger and the design lines (`siteImportFidelity`). A miss is named\n * in the one re-ask.\n * 3. Compiled by the site compiler with `keep` expanded to the source's own\n * blocks, and a picture asked for in words left as a slot the page step's\n * pictures fill or drop.\n *\n * Nothing here runs with the flag off, or for Keep my site.\n *=========================================*/\n\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport type { AiLayoutDesign, AiLayoutHeroVariant } from '../layout-language/ai-layout-design'\nimport { aiLayoutDesignChoices, aiLayoutGroupVariant } from '../layout-language/ai-layout-design'\nimport {\n AI_LAYOUT_ALIGNS,\n AI_LAYOUT_BANDS,\n AI_LAYOUT_MAX_COLS,\n AI_LAYOUT_STYLES,\n aiReadLayoutBlock,\n type AiLayoutBlock,\n type AiLayoutImportHero,\n type AiLayoutPicture,\n type AiLayoutItem,\n type AiLayoutSection,\n type AiLayoutSettlement,\n} from '../layout-language/ai-layout-language'\nimport { AI_ICON_WORDS } from '../runtime/ai-icon-library'\nimport type { AiSiteImportAddedSection, AiSiteImportPagePictures, AiSiteImportPageRole, AiSiteImportPlan, SiteImportLineRef } from '../model/ai-site-import'\nimport { aiSiteHomeArc } from '../model/ai-site-home-arcs'\nimport {\n SITE_IMPORT_IMPROVED_MEANING,\n SITE_IMPORT_MEANING_FLOOR,\n siteImportContentKept,\n siteImportContentWords,\n type SiteImportFidelityTheme,\n type SiteImportPageFidelity,\n} from '../model/ai-site-import-fidelity'\nimport { aiSiteImportImageIsMark } from '../model/ai-site-import-marks'\nimport { siteImportLedger, type SiteImportLedger, type SiteImportLedgerItem, type SiteImportLedgerLine } from '../model/ai-site-import-ledger'\nimport { AI_SITE_IMPORT_PAGE_CEILING_CREDITS } from '../model/ai-site-import'\nimport { estimateAiBilledUsd } from '../providers/catalog'\nimport type { AiSystemBlock, AiTool, AiUsage } from '../providers/contract'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport type { AiGenerationCheck } from '../runtime/ai-doctrine'\nimport type { AiCopyFraming, AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport type { SiteImportBlock } from '../site-import/site-import-html'\nimport { siteImportLabel } from '../site-import/site-import-page'\nimport { aiSiteImportHonesty, aiSiteImportImprovedPlaced, type AiSiteImportImprovedBlock, type AiSiteImportImprovedSection } from './ai-site-import-honesty'\nimport { aiSiteImportSectionActions } from './ai-site-import-actions'\nimport {\n aiSiteImportLayoutOf,\n aiSiteImportLinkTo,\n aiSiteImportMapScope,\n aiSiteImportNodeBlocks,\n aiSiteImportTakePicture,\n type AiSiteImportDesigned,\n} from './ai-site-import-compile'\nimport { aiSiteImportTextParts, type AiSiteImportDocument } from './ai-site-import-document'\n\nconst clean = (text: unknown): string => (typeof text === 'string' ? text.replace(/\\s+/g, ' ').trim() : '')\n\n/*------------------------------------------\n * The tool and its cached text\n *-----------------------------------------*/\n\n/** The answer's kind of generation: the name its re-ask and its doctrine scope go by. */\nexport const AI_SITE_IMPORT_IMPROVE_KIND = 'page-improve'\n\n/**\n * The most items a redesign's group keeps (AGL-4152): every item its owner's\n * page has, where the layout language's own pages stop at seven. A page\n * brought in is compiled as its source lays it out, with no such limit.\n */\nexport const AI_SITE_IMPORT_IMPROVE_MAX_ITEMS = 24\n\n/** What a block may be: the layout language's words and groups, and `keep`. A customer's quote and a figure only ever arrive by `keep`. */\nexport const AI_SITE_IMPORT_IMPROVE_BLOCK_KINDS = ['eyebrow', 'heading', 'lede', 'text', 'note', 'list', 'button', 'image', 'cards', 'steps', 'faq', 'keep'] as const\n\nconst ITEM_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['title', 'text', 'to', 'icon', 'ref'],\n properties: {\n title: { type: 'string' },\n text: { type: 'string' },\n to: { type: 'string' },\n icon: { type: 'string' },\n ref: { type: 'string' },\n },\n} as const\n\nconst BLOCK_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'col', 'text', 'to', 'style', 'icon', 'items', 'ref'],\n properties: {\n kind: { type: 'string', enum: [...AI_SITE_IMPORT_IMPROVE_BLOCK_KINDS] },\n col: { type: 'integer' },\n text: { type: 'string' },\n to: { type: 'string' },\n style: { type: 'string', enum: [...AI_LAYOUT_STYLES, 'none'] },\n icon: { type: 'string' },\n items: { type: 'array', items: ITEM_SCHEMA },\n ref: { type: 'string' },\n },\n} as const\n\n/** The redesign tool: the `submit_page` language, a `keep` block, and a picture on an item by its ref. */\nexport const AI_SITE_IMPORT_IMPROVE_TOOL: AiTool = {\n name: 'submit_improved_page',\n description: 'Submit the redesigned page: its sections in order, in the layout language, each thing the page must keep placed with a keep block.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['sections'],\n properties: {\n sections: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['band', 'cols', 'align', 'blocks'],\n properties: {\n band: { type: 'string', enum: [...AI_LAYOUT_BANDS] },\n cols: { type: 'array', items: { type: 'integer' } },\n align: { type: 'string', enum: [...AI_LAYOUT_ALIGNS] },\n blocks: { type: 'array', items: BLOCK_SCHEMA },\n },\n },\n },\n },\n },\n}\n\n/** What a redesign is told, cached: every page of every site shares these bytes. */\nexport const AI_SITE_IMPORT_IMPROVE_TEXT = [\n \"You redesign one page of a small business's existing website the way a professional web designer and copywriter would, so the new page looks far better than the old one: polished, organized and inviting, never the old page restyled. The old page is usually plain: one column, flat grounds, a text link for a call to action, its sections in the order someone typed them. Plan the page again from what a visitor needs, in the order they need it, add the sections it lacks, and write every word. The platform turns your design into the page in the site's own theme, so never describe styling beyond the words below.\",\n '',\n 'Answer with submit_improved_page. A page is a list of sections, top to bottom, and you decide how many and what each one is. A section has:',\n '- band: plain (the page), soft (a set-apart ground), brand (the brand color) or dark.',\n '- cols: relative column widths for a row: [1, 1] for halves, [7, 5] for a wide and a narrow column, [1, 1, 1]; at most 4. [] for one column.',\n '- align: start or center. Center only a short section: an opening, a closing call to action, a heading over a group.',\n '- blocks: what it shows, top to bottom. A block with col 0 or more goes in that column of the row; col -1 spans the section, above the row when it comes first and below it when it comes last.',\n 'Every field is always written: a block that does not use one writes \"\" (text, to, icon, ref), \"none\" (style), -1 (col) or [] (items); an item that does not use one writes \"\".',\n '',\n 'Block kinds:',\n '- eyebrow: a short label over a heading. heading: the first heading of the first section is the page title; the first heading of any other section is its heading. lede: the larger sentence under a heading. text: a paragraph. note: small print.',\n '- button: text is its label, to where it goes, style primary (filled), secondary (outlined) or quiet. Two in a row read as a pair.',\n '- cards, steps, faq: a group of items, each a title and a text. cards are services, features or reasons; steps are numbered and in order; faq items are a question and its answer. An item may carry an icon, a to, and ref naming a picture of the page, shown on the card: a picture the ledger lists with lines goes on the card written of those lines, so like cards each show their own.',\n '- list: short lines, title only.',\n '- image: text describes a picture the page should have where none of its own fits; the platform finds one, or leaves it out.',\n '- keep: ref names one thing of the ledger, drawn exactly as the owner has it, so write nothing for it: a picture, form, plan, table, quote, video, contact line, figures, logos, a gallery of photos (drawn as a grid of them), tabs, or a group. Place every thing the ledger marks must, exactly once, wherever it serves the page best, in a column if that helps.',\n '- A group:n of the ledger is a set of like items the old page shows (its cards, steps, questions or list). keep it to draw it whole as the owner has it, with the pictures and links it holds; or write its items again as a group of your own, every link and fact of it kept. A page too long to show whole has its groups folded: each is shown by its titles, marked must, and kept whole, and you write only what is around them.',\n 'icon (on a block or an item) is one of: ' + AI_ICON_WORDS.join(', ') + '.',\n '',\n 'Where a link goes (to): page:<id> for a page the ledger names, #<n> for section n of this page, form for the form on this page, phone or email for the number or address the page gives, or an https: address the ledger lists. Every link the ledger lists must go somewhere on the page, as a button or an item.',\n '',\n \"A designer's page is made of sections like these; choose and order the ones this page needs:\",\n '- Hero: the page title, a lede, a filled primary button and a quieter second one, beside a picture (cols [7, 5]: the words in col 0, the picture in col 1) or with the picture behind the words (one column, the picture first). Every opening places a picture: the page\\'s own by keep, else an image block.',\n '- Offer as a card grid: a heading, a lede, then cards, one item for each service or thing offered, each with an icon; three or four across.',\n '- Figures or badges: figures the ledger holds, kept (keep stats:n); plain facts the page states, such as how long the business has run or that it is licensed, as cards of two to four items with icons, each saying the fact exactly as the page does.',\n '- How it works: a heading and steps of three or four items, from first asking to done.',\n '- Why choose it: cards of three with icons, each a reason the site supports.',\n '- A quote drawn as a quote: its own section on a soft or dark ground, centered: a short heading and the kept quote alone.',\n '- Pictures in a row: cols [1, 1, 1] or [1, 1], one picture kept in each column with a one-line caption under it; a gallery kept whole is its own grid, under a short heading. Pictures are never stacked one under another.',\n '- Words beside a picture: cols [1, 1] or [5, 7]: a heading, a lede, a paragraph and a button in one column and a picture in the other, the side alternating down the page.',\n '- Questions: a heading and a faq of three to six questions a visitor of this kind of business asks, each answered only with what the site says.',\n '- Contact: the kept form on a framed ground (a soft band, cols [5, 7]): beside it a heading, a welcoming line, the kept contact line and a call or email button.',\n '- Closing band: the last section, on a brand or dark ground, centered: a heading that says what the visitor gets, one line, and a filled primary button.',\n '',\n 'Plan it as a designer would:',\n '- Give the page the sections its role asks for. The request names its role and how many new sections it needs: a new section is one the old page has nowhere, such as how it works, why choose it or the questions people ask, written from what the site says and what this kind of business generally does.',\n '- Draw like things as a group: three or more services, reasons or steps are cards or steps, never headings and paragraphs one under another; a set of questions is a faq; two or three pictures are a row.',\n '- Vary it: no two neighboring sections share a shape or a ground. Alternate plain and soft, and keep brand and dark to one or two sections a page, usually the closing band.',\n '- Each heading says what the visitor gets, in a few specific words; never \"Welcome\", \"Our services\" or \"Ready when you are\" alone.',\n '- Put the phone or email the page gives on a button (to phone, to email) where a visitor would call or write, beside the kept contact line.',\n '',\n \"Writing: plain, specific and in the owner's voice, each heading a clear promise, each paragraph leading with the benefit, nothing that does not earn its place. Headings and card titles are in sentence case, so a capital reads as a name. Say what the page says, in stronger words, keeping every fact it gives; and you may say what this kind of business generally does.\",\n 'Never write a name, number, price, date, testimonial, client, award, credential, address or guarantee the page or the site does not give. A fact you do not have is left out, never a gap or a placeholder. Say a figure, a price, a phone or a name exactly as the page does.',\n].join('\\n')\n\n/** The site's own digest, which every page of one import reads ahead of its ledger: cached once per site. */\nexport function aiSiteImportImproveDigest(input: {\n siteName: string | null\n /** What the home page says of the site, and the pages of the import. */\n scope: readonly string[]\n plan?: AiSiteImportPlan | null\n}): string {\n return [\n fenceUntrustedText(\"What the owner's site says of itself\", [clean(input.siteName), ...input.scope].filter(Boolean).join('\\n'), { maxChars: AI_SITE_IMPORT_IMPROVE_DIGEST_CHARS }),\n ...(input.plan ? [fenceUntrustedText('The plan every page of this site is drawn to', JSON.stringify(input.plan), { maxChars: 4_000 })] : []),\n ].join('\\n')\n}\n\n/** The most of a site's own words the digest holds. */\nexport const AI_SITE_IMPORT_IMPROVE_DIGEST_CHARS = 16_000\n\n/** A redesign's system blocks: the platform's text cached across sites, then this site's digest, cached once per site. The ledger rides the user turn. */\nexport function aiSiteImportImproveInstructions(digest: string): readonly AiSystemBlock[] {\n return [\n { text: AI_SITE_IMPORT_IMPROVE_TEXT, cacheBreakpoint: true },\n { text: UNTRUSTED_TEXT_RULE },\n { text: digest, cacheBreakpoint: true, site: true },\n ]\n}\n\n/*------------------------------------------\n * The ledger as the answer reads it\n *-----------------------------------------*/\n\n/** The most characters a page's ledger shows. */\nexport const AI_SITE_IMPORT_LEDGER_MAX_CHARS = 16_000\n\nconst textOf = (block: SiteImportBlock | undefined): string => (block && block.kind !== 'image' ? clean(block.text) : '')\n\nconst short = (text: string, most = 80) => (text.length > most ? `${text.slice(0, most - 1)}…` : text)\n\n/**\n * The lines each picture of a page stands with (AGL-4152): the words after it\n * in its section, up to the next picture, as a row of pictured services or a\n * photo over its caption lays them out. What the ledger tells a redesign a\n * picture goes with, and what a card written of those words is given it by.\n */\nexport function aiSiteImportPictureCaptions(ledger: Pick<SiteImportLedger, 'items' | 'lines'>): Map<string, SiteImportLedgerLine[]> {\n const pictures = ledger.items.filter((item) => item.kind === 'picture' && item.lines[0] !== undefined)\n const out = new Map<string, SiteImportLedgerLine[]>()\n for (const item of pictures) {\n const at = item.lines[0] as number\n const next = Math.min(...pictures.filter((other) => other.section === item.section && (other.lines[0] as number) > at).map((other) => other.lines[0] as number), Number.POSITIVE_INFINITY)\n const lines = ledger.lines.filter((line) => line.section === item.section && line.line > at && line.line < next && !line.group).slice(0, 2)\n if (lines.length) out.set(item.ref, lines)\n }\n return out\n}\n\n/** A ledger item, in a few words: what it is and what it shows. */\nfunction shownItem(item: SiteImportLedgerItem, doc: Pick<AiSiteImportDocument, 'blocks' | 'photos'>, captions?: ReadonlyMap<string, SiteImportLedgerLine[]>): string {\n const must = item.must ? ' must' : ''\n const words = item.lines.map((ref) => textOf(doc.blocks[ref])).filter(Boolean)\n switch (item.kind) {\n case 'picture': {\n const block = doc.blocks[item.lines[0] as number]\n const url = block?.kind === 'image' ? block.url : ''\n const photo = doc.photos.find((entry) => entry.from === url)\n const alt = block?.kind === 'image' ? clean(block.alt) : ''\n // The words it stands with, by their numbers: a card written of them takes it by its ref (AGL-4152).\n const with_ = captions?.get(item.ref)?.map((line) => `[${line.line}]`).join(', ')\n return `${item.ref}${must} (${photo?.width && photo.height ? `${photo.width}×${photo.height}, ` : ''}\"${short(alt, 60)}\"${with_ ? `, with ${with_}` : ''})`\n }\n case 'form':\n return `${item.ref}${must} (a form)`\n case 'video':\n return `${item.ref}${must} (a film)`\n case 'plan':\n return `${item.ref}${must} (${item.node?.kind === 'group' ? item.node.items.length : 0} plans: ${short(words.slice(0, 6).join(', '), 120)})`\n case 'table':\n return `${item.ref}${must} (${item.node?.kind === 'table' ? item.node.rows.length : 0} rows: ${short(words.slice(0, 6).join(', '), 120)})`\n case 'stats':\n return `${item.ref}${must} (figures: ${short(words.join(', '), 120)})`\n case 'logos':\n return `${item.ref}${must} (a strip of logos)`\n case 'gallery': {\n const node = item.node?.kind === 'group' ? item.node : null\n const alts = item.lines.flatMap((ref) => {\n const entry = doc.blocks[ref]\n return entry?.kind === 'image' && clean(entry.alt) ? [`\"${short(clean(entry.alt), 40)}\"`] : []\n })\n return `${item.ref}${must} (a gallery of ${node?.items.length ?? 0} photos, drawn as a grid${node?.columns ? ` ${node.columns} across` : ''}${alts.length ? `: ${alts.slice(0, 4).join(', ')}${alts.length > 4 ? ', …' : ''}` : ''})`\n }\n case 'tabs':\n return `${item.ref}${must} (tabs: ${short(words.slice(0, 4).join(', '), 120)})`\n case 'group': {\n const node = item.node?.kind === 'group' ? item.node : null\n // Each item by its first line that says something in words: a step's number is no title.\n const titles = (node?.items ?? []).map((entry) => textOf(doc.blocks[entry.lines.find((ref) => /\\p{L}/u.test(textOf(doc.blocks[ref]))) as number])).filter(Boolean)\n const linked = (node?.items ?? []).filter((entry) => entry.to || entry.lines.some((ref) => doc.blocks[ref]?.kind === 'link')).length\n const kind = node?.group === 'text' || !node ? 'like items' : node.group\n const shown = titles.slice(0, item.folded ? 16 : 6).map((title) => `\"${short(title, 40)}\"`).join(', ')\n return `${item.ref}${must} (${node?.items.length ?? 0} ${kind}${linked ? `, ${linked} linked` : ''}: ${shown}${titles.length > (item.folded ? 16 : 6) ? ', …' : ''}${item.holds?.length ? `; holds ${item.holds.join(', ')}` : ''})`\n }\n default:\n return `${item.ref}${must} (${short(words.join(' '), 160)})`\n }\n}\n\n/**\n * A page's ledger as its answer reads it (AGL-4152): what it may place, where\n * each link goes, and every line it rewrites, numbered. Uncached, per page, and\n * fenced by the prompt: every word of it is the owner's.\n */\nexport function aiSiteImportLedgerText(ledger: SiteImportLedger, doc: Pick<AiSiteImportDocument, 'blocks' | 'photos'>, destinations: ReadonlyMap<string, string>): string {\n // A link a folded group holds goes where it went by its keep: it is not listed again.\n const folded = new Set(ledger.items.flatMap((item) => (item.folded ? item.lines : [])))\n const links = ledger.links.flatMap((link) => {\n const to = destinations.get(link.ref)\n return to && !folded.has(link.line) ? [`${link.ref} → ${to} (\"${short(link.text, 60)}\")`] : []\n })\n // A long page shows each group by its titles alone, kept whole: what is around them is written (AGL-4152).\n const lines = ledger.folded ? ledger.lines.filter((line) => !line.group) : ledger.lines\n const captions = aiSiteImportPictureCaptions(ledger)\n return [\n ...(ledger.folded ? ['This page is long: its groups are folded, each shown by its titles and kept whole with keep.'] : []),\n 'Things to place with keep, each once; \"must\" may not be left out:',\n ...(ledger.items.length ? ledger.items.map((item) => shownItem(item, doc, captions)) : ['(none)']),\n '',\n 'Links that must go somewhere on the page:',\n ...(links.length ? links : ['(none)']),\n '',\n 'The lines of the old page, by section, which you rewrite as the page needs:',\n ...lines.map((line) => `[${line.line}] section ${line.section + 1}, ${line.kind}${line.group && !ledger.folded ? ` in ${line.group}` : ''}: ${line.text}`),\n ].join('\\n')\n}\n\n/** Everywhere a link may go on this page, as an answer writes it, each with the destination it means. */\nexport function aiSiteImportImproveDestinations(doc: AiSiteImportDocument, ledger: SiteImportLedger, input: { sections?: number; formSection?: number | null } = {}): Map<string, string> {\n const scope = { doc, pathTo: new Map(doc.links.map((link) => [link.path.replace(/\\/+$/, '') || '/', link.id])) }\n const out = new Map<string, string>()\n for (const link of ledger.links) {\n const to = aiSiteImportLinkTo(scope, link.href)\n if (to) {\n out.set(link.ref, to)\n out.set(to, to)\n }\n }\n for (const page of doc.links) out.set(`page:${page.id}`, `page:${page.id}`)\n // A new page has no contact line of its own: it may send a visitor to what the site gives (AGL-4152).\n const text = [...doc.blocks.map((block) => (block.kind === 'image' ? '' : block.text)), ...(doc.proposed ? (doc.siteLines ?? []) : [])].join(' \\n ')\n const phone = /(?:\\+\\d{1,3}[\\s.-]?)?(?:\\(\\d{2,4}\\)[\\s.-]?)?\\d{2,4}[\\s.-]\\d{3,4}(?:[\\s.-]\\d{2,4})?/.exec(text)?.[0]\n if (phone && phone.replace(/\\D/g, '').length >= 7) out.set('phone', `tel:${phone.replace(/[^\\d+]/g, '')}`)\n const email = /[\\p{L}\\p{N}._%+-]+@[\\p{L}\\p{N}-]+(?:\\.[\\p{L}\\p{N}-]+)+/u.exec(text)?.[0]\n if (email) out.set('email', `mailto:${email}`)\n for (const [key, to] of [...out]) if (key === 'phone' || key === 'email') out.set(to, to)\n if (input.formSection !== null && input.formSection !== undefined) out.set('form', `#${input.formSection + 1}`)\n else {\n // A page with no form of its own sends `form` to the site's page that holds one, as a link to that page goes (AGL-4152).\n const formPage = aiSiteImportFormPageOf(doc)\n if (formPage) out.set('form', formPage)\n }\n for (let n = 1; n <= (input.sections ?? 0); n += 1) out.set(`#${n}`, `#${n}`)\n return out\n}\n\n/**\n * The site's page that holds its form (AGL-4152), as `page:<id>`: the one the\n * plan's header button sends `form` to, else the one the import read a form\n * on. `null` where no page of the site holds one, where that page is not one a\n * link may go to, or where it is the page itself, which holds its form in place.\n */\nexport function aiSiteImportFormPageOf(doc: Pick<AiSiteImportDocument, 'plan' | 'formPage' | 'links' | 'url'>): string | null {\n const cta = doc.plan?.nav.primaryCta\n const id = (cta?.target === 'form' ? cta.page : undefined) ?? doc.formPage\n if (!id || !doc.links.some((page) => page.id === id)) return null\n const to = `page:${id}`\n return to === aiSiteImportOwnPage(doc) ? null : to\n}\n\n/**\n * The page's own `page:<id>` on the new site (AGL-4152), by its address: a\n * link to it from itself goes nowhere a visitor is not already. `null` where\n * the import plans it under no id, as the home page.\n */\nexport function aiSiteImportOwnPage(doc: Pick<AiSiteImportDocument, 'url' | 'links'>): string | null {\n let path: string\n try {\n path = new URL(doc.url).pathname.replace(/\\/+$/, '') || '/'\n } catch {\n return null\n }\n const own = doc.links.find((link) => link.path === path)\n return own ? `page:${own.id}` : null\n}\n\n/** A redesign's user turn: the page, its kind of site, how its opening is drawn, and its ledger, fenced as the owner's data. */\nexport function aiSiteImportImprovePrompt(input: {\n screen: { title: string; slug: string }\n doc: Pick<AiSiteImportDocument, 'url' | 'blocks' | 'photos' | 'proposed'>\n ledger: SiteImportLedger\n destinations: ReadonlyMap<string, string>\n kindLines: readonly string[]\n seed: string\n /** What the page is for and what it needs (`aiSiteImportImproveRoleLines`). */\n roleLines?: readonly string[]\n}): string {\n return [\n `Page: \"${input.screen.title}\" at ${input.screen.slug}`,\n // A page the site's plan proposed: there is no old page to keep, so it is written whole from what the site says.\n ...(input.doc.proposed ? ['This page is new: the site has no such page yet. Its one line says what it tells a visitor. Write it from what the site says of itself and what this kind of business generally does, inventing no fact.'] : []),\n ...(input.roleLines ?? []),\n ...input.kindLines,\n \"The page's ledger, what it holds and where it links:\",\n fenceUntrustedText(`The owner's page ${input.doc.url}`, aiSiteImportLedgerText(input.ledger, input.doc, input.destinations), { maxChars: AI_SITE_IMPORT_LEDGER_MAX_CHARS }),\n `Design seed: ${input.seed}.`,\n ].join('\\n')\n}\n\n/*------------------------------------------\n * What the page is for, and what it needs\n *-----------------------------------------*/\n\n/**\n * How many new sections a page of each role is asked for (AGL-4152): a home\n * or a main service page two, a contact page none, its form framed instead,\n * and a gallery none: its pictures are what it is for, and a section added\n * to a page of photos only stands between a visitor and them.\n */\nexport const AI_SITE_IMPORT_NEW_SECTIONS: Readonly<Record<AiSiteImportPageRole, number>> = {\n home: 2,\n service: 2,\n about: 1,\n gallery: 0,\n pricing: 1,\n other: 1,\n contact: 0,\n faq: 0,\n}\n\n/**\n * The share of the old page's words a redesign keeps, by role (AGL-4152),\n * where it is not `SITE_IMPORT_IMPROVED_MEANING`. A contact page is asked for\n * a short, welcoming opening over its form: what it must keep is its form,\n * its contact lines and its facts, each held whole on their own lines, and its\n * intent, so its prose is held only at the floor a rewritten line is.\n */\nexport const AI_SITE_IMPORT_ROLE_MEANING: Readonly<Partial<Record<AiSiteImportPageRole, number>>> = { contact: SITE_IMPORT_MEANING_FLOOR }\n\n/** The share of its old words a page of a role keeps. */\nexport function aiSiteImportMeaningShare(role: AiSiteImportPageRole): number {\n return AI_SITE_IMPORT_ROLE_MEANING[role] ?? SITE_IMPORT_IMPROVED_MEANING\n}\n\n/** The fewest content words an old section says for a new one to be its rework (AGL-4152): fewer is a label, which any section may echo. */\nexport const AI_SITE_IMPORT_REWORK_LEAST_WORDS = 4\n\n/** The most sections a redesigned page runs to: a page the source already fills has no room for more. */\nexport const AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS = 10\n\n/** What a page is for, as its plan says, else from its address and what it holds. */\nexport function aiSiteImportPageRoleOf(doc: Pick<AiSiteImportDocument, 'role' | 'proposed' | 'url' | 'title' | 'blocks' | 'forms' | 'layout'>, slug: string): AiSiteImportPageRole {\n if (doc.role) return doc.role\n if (slug === '/' || slug === '') return 'home'\n const words = `${slug} ${doc.title}`.toLowerCase()\n if (/\\b(?:faq|faqs|questions)\\b/.test(words)) return 'faq'\n if (/\\b(?:contact|visit|find-us|location|book|booking|estimate|quote)\\b/.test(words)) return 'contact'\n if (/\\b(?:about|story|team|people)\\b/.test(words)) return 'about'\n if (/\\b(?:pricing|prices|rates|plans)\\b/.test(words)) return 'pricing'\n if (/\\b(?:gallery|portfolio|projects|work)\\b/.test(words)) return 'gallery'\n if (doc.proposed) return 'other'\n return 'service'\n}\n\n/** How many new sections a page is asked for: its role's, where the page has room, and none on a long page, whose groups fold. */\nexport function aiSiteImportNewSectionsWanted(role: AiSiteImportPageRole, ledger: Pick<SiteImportLedger, 'folded' | 'lines' | 'items'>, proposed = false): number {\n if (proposed || ledger.folded) return 0\n const sections = new Set([...ledger.lines.map((line) => line.section), ...ledger.items.map((item) => item.section)]).size\n return Math.max(0, Math.min(AI_SITE_IMPORT_NEW_SECTIONS[role], AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS - 1 - sections))\n}\n\n/** What each role's page tells, in the order a designer would tell it. */\nconst ROLE_PLAN: Readonly<Record<AiSiteImportPageRole, string>> = {\n home: 'the front door of the site: the hero, what the business offers, why choose it, how it works, the questions people ask, and the closing band',\n service: 'what the service is: the hero, what is included as cards, how it works as steps, why choose it, the questions people ask about it, and the closing band',\n about: 'the story and the people: the hero, the story beside a picture, what the business values or why choose it as cards, a kept quote where the ledger has one, and the closing band',\n contact: 'how to reach the business: a short, welcoming opening, the form on a framed ground beside how to reach it, what happens after a visitor writes where the site says so, and no closing band',\n gallery: 'the work in pictures: the hero, the pictures in rows with short captions, what the work is, and the closing band',\n pricing: 'the prices, exactly as kept: the hero, the plans or table kept whole, what is included, the questions people ask about paying, and the closing band',\n faq: 'the questions: a short opening, the questions as a faq, and the closing band',\n other: 'what the page is for: the hero, its content drawn as groups and pictures, and the closing band',\n}\n\n/** The lines a redesign's request says of its page's role and what it needs (AGL-4152). */\nexport function aiSiteImportImproveRoleLines(input: { role: AiSiteImportPageRole; wanted: number; folded: boolean; kind?: string | null; seed: number }): string[] {\n const { role, wanted } = input\n // A home tells its story as a site start's does (`ai-site-home-arcs.ts`), one of its kind's arcs by the job's seed.\n const arc = role === 'home' ? aiSiteHomeArc({ kind: input.kind ?? null, seed: input.seed }) : null\n return [\n `This page's role: ${role}, ${ROLE_PLAN[role]}.`,\n ...(arc ? [`This home tells its story in this order, after the hero: ${arc.sections.map((section) => section.words).join('; ')}. Where it says the brief, read what the site says. Fold the old page's sections into these, and keep the order.`] : []),\n wanted ? `It needs at least ${wanted} new ${wanted === 1 ? 'section' : 'sections'}: ${wanted === 1 ? 'one' : 'sections'} the old page has nowhere, for this role.` : input.folded ? 'It is long: plan its order and its grounds, keep its groups whole, and add nothing it does not need.' : 'It needs no new section; organize and draw what it has.',\n ]\n}\n\n/**\n * The sections a redesign added (AGL-4152), by index: neither the opening nor\n * a closing band, holding nothing kept but a picture, saying something of\n * its own, and the rework of no section of the old page. Each section of the\n * old page past its opening is reworked by the one section that says most\n * of it; another section drawing on its words, such as a why-us of the\n * opening's facts, is new. An old section of a few words, a heading over a\n * band or a label over a kept group, reworks nothing: any new section that\n * happens to say its two or three words would otherwise read as its rework.\n */\nexport function aiSiteImportImproveNewSections(answer: readonly AiSiteImportImprovedSection[], ledger: Pick<SiteImportLedger, 'lines' | 'items'>): number[] {\n const kinds = new Map(ledger.items.map((item) => [item.ref, item.kind]))\n const sources = new Map<number, string[]>()\n for (const line of ledger.lines) sources.set(line.section, [...(sources.get(line.section) ?? []), line.text])\n const said = answer.map((section) =>\n section.blocks\n .flatMap((block) => (block.kind === 'keep' ? [] : [block.kind === 'image' ? '' : (block.text ?? ''), ...(block.items ?? []).flatMap((item) => [item.title, item.text])]))\n .join(' '),\n )\n const reworked = new Set<number>()\n // The old page's opening is the new page's: a section drawing on its facts, such as a why-us, is new.\n for (const [at, lines] of sources) {\n if (at === 0) continue\n const text = lines.join(' ')\n if (siteImportContentWords(text) < AI_SITE_IMPORT_REWORK_LEAST_WORDS) continue\n let best = -1\n let most = 0.5\n said.forEach((words, index) => {\n const kept = siteImportContentKept(text, words)\n if (kept >= most) {\n most = kept\n best = index\n }\n })\n if (best >= 0) reworked.add(best)\n }\n const last = answer.length - 1\n return answer.flatMap((section, index) => {\n if (index === 0 || reworked.has(index)) return []\n if (section.blocks.some((block) => block.kind === 'keep' && kinds.get(block.ref) !== 'picture')) return []\n const groups = section.blocks.filter((block) => block.kind !== 'keep' && (block.items?.length ?? 0) >= 2)\n const words = section.blocks.filter((block) => block.kind === 'text' || block.kind === 'lede')\n // A closing band: a heading, a line at most and a button, last.\n if (index === last && !groups.length && words.length <= 1 && section.blocks.some((block) => block.kind === 'button')) return []\n return groups.length || words.length ? [index] : []\n })\n}\n\n/** A section's shape, as a designer tells sections apart: what the variety of a page is counted in. */\nfunction shapeOf(section: AiSiteImportImprovedSection, kinds: ReadonlyMap<string, string>): string {\n const kept = section.blocks.flatMap((block) => (block.kind === 'keep' ? [kinds.get(block.ref) ?? ''] : []))\n const pictures = kept.filter((kind) => kind === 'picture').length + section.blocks.filter((block) => block.kind === 'image').length\n const group = section.blocks.find((block) => block.kind !== 'keep' && (block.items?.length ?? 0) >= 2)\n if (kept.includes('form')) return 'form'\n if (kept.includes('quote')) return 'quote'\n if (group) return group.kind\n const whole = kept.find((kind) => kind !== 'picture' && kind !== 'contact')\n if (whole) return whole\n if (pictures >= 2) return 'pictures'\n if (pictures && section.cols) return 'split'\n return section.blocks.some((block) => block.kind === 'button') && !section.blocks.some((block) => block.kind === 'text') ? 'band' : 'words'\n}\n\n/** What a redesign is asked to be, by its role (AGL-4152). */\nexport interface AiSiteImportImproveNeeds {\n role: AiSiteImportPageRole\n /** New sections it needs (`aiSiteImportNewSectionsWanted`). */\n wanted: number\n}\n\n/** The fewest shapes a page of four sections or more is drawn in. */\nexport const AI_SITE_IMPORT_IMPROVE_LEAST_SHAPES = 3\n\n/** Roles whose opening holds a picture. */\nconst PICTURED_OPENINGS: ReadonlySet<AiSiteImportPageRole> = new Set(['home', 'service', 'about', 'gallery', 'other'])\n\n/**\n * Whether a redesign is planned as a designer's page (AGL-4152), answer by\n * answer: the new sections its role asks for, a picture in its opening, and\n * sections drawn in more than one or two shapes. Each miss is named for the\n * one re-ask.\n */\nexport function aiSiteImportImprovePlanMisses(answer: readonly AiSiteImportImprovedSection[], input: { ledger: Pick<SiteImportLedger, 'lines' | 'items' | 'folded'>; needs: AiSiteImportImproveNeeds }): AiDoctrineViolation[] {\n const out: AiDoctrineViolation[] = []\n const added = aiSiteImportImproveNewSections(answer, input.ledger)\n if (added.length < input.needs.wanted) {\n out.push({\n rule: null,\n code: 'improve-new-sections',\n message: `The page adds ${added.length} new ${added.length === 1 ? 'section' : 'sections'}; as a ${input.needs.role} page it needs at least ${input.needs.wanted}: sections the old page has nowhere, such as how it works as steps, why choose it as cards, or the questions people ask as a faq, written from what the site says.`,\n })\n }\n const opening = answer[0]?.blocks ?? []\n if (PICTURED_OPENINGS.has(input.needs.role) && !opening.some((block) => block.kind === 'image' || (block.kind === 'keep' && block.ref.startsWith('picture:')))) {\n out.push({ rule: null, code: 'improve-opening', message: \"The opening has no picture. Place the page's own picture there with keep, or an image block, beside the words or behind them.\" })\n }\n const kinds = new Map(input.ledger.items.map((item) => [item.ref, item.kind as string]))\n const shapes = new Set(answer.slice(1).map((section) => shapeOf(section, kinds)))\n if (answer.length >= 4 && shapes.size < AI_SITE_IMPORT_IMPROVE_LEAST_SHAPES) {\n out.push({ rule: null, code: 'improve-shapes', message: `The sections after the opening are drawn in ${shapes.size === 1 ? 'one shape' : `${shapes.size} shapes`}. Vary them: a card grid, steps, words beside a picture, a row of pictures, a faq, a quote on its own ground, a closing band.` })\n }\n return out\n}\n\n/*------------------------------------------\n * The answer read\n *-----------------------------------------*/\n\n/** A redesign's answer, read by position: `null` where it gave no section it can draw. */\nexport function aiReadImprovedPage(raw: unknown, settled: AiLayoutSettlement[] = []): AiSiteImportImprovedSection[] | null {\n const given = raw && typeof raw === 'object' && Array.isArray((raw as Record<string, unknown>)['sections']) ? ((raw as Record<string, unknown>)['sections'] as unknown[]) : null\n if (!given) return null\n const sections: AiSiteImportImprovedSection[] = []\n given.forEach((entry, index) => {\n const section = entry && typeof entry === 'object' ? (entry as Record<string, unknown>) : null\n if (!section) return\n const cols = Array.isArray(section['cols']) ? section['cols'].filter((value): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0).slice(0, AI_LAYOUT_MAX_COLS).map((value) => Math.min(12, Math.max(1, Math.round(value)))) : []\n const blocks: AiSiteImportImprovedBlock[] = []\n ;(Array.isArray(section['blocks']) ? section['blocks'] : []).forEach((raw: unknown, position: number) => {\n const entry = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null\n if (!entry) return\n const col = typeof entry['col'] === 'number' && Number.isInteger(entry['col']) && entry['col'] >= 0 && cols.length >= 2 ? Math.min(entry['col'], cols.length - 1) : undefined\n if (entry['kind'] === 'keep') {\n const ref = clean(entry['ref'])\n if (ref) blocks.push({ kind: 'keep', ref, ...(col !== undefined ? { col } : {}) })\n return\n }\n const block = aiReadLayoutBlock(entry, `sections[${index}].blocks[${position}]`, settled, { mostItems: AI_SITE_IMPORT_IMPROVE_MAX_ITEMS })\n if (!block) return\n const { col: _col, ...rest } = block\n blocks.push({ ...rest, ...(col !== undefined ? { col } : {}) })\n })\n if (!blocks.length) return\n const band = AI_LAYOUT_BANDS.find((value) => value === section['band'])\n const align = AI_LAYOUT_ALIGNS.find((value) => value === section['align'])\n sections.push({ ...(band ? { band } : {}), ...(cols.length >= 2 ? { cols } : {}), ...(align ? { align } : {}), blocks })\n })\n return sections.length ? sections : null\n}\n\n/*------------------------------------------\n * The answer in the compiler's language\n *-----------------------------------------*/\n\n/** The least width over height of an opening photo a redesign lays its words over (AGL-4152): a landscape, not a square or a portrait. */\nexport const AI_SITE_IMPORT_COVER_LEAST_RATIO = 1.3\n\n/** The heroes that box their photo under the words: a masthead's and an editorial's. */\nconst BOXED_HEROES: ReadonlySet<AiLayoutHeroVariant> = new Set(['column', 'editorial'])\n\n/** The heroes that lay their photo edge to edge behind the words, which a square or a portrait cannot fill. */\nconst COVERING_HEROES: ReadonlySet<AiLayoutHeroVariant> = new Set(['cover', 'poster', 'panel'])\n\n/**\n * The site's hero as a page brought in draws it: a collage or a portrait holds\n * what a page brought in does not. A redesign whose opening holds the page's\n * own landscape photo lays its words over it (AGL-4152): a hero that boxes a\n * wide photo under centered words reads as a picture pasted below a heading,\n * the way an old page looks, never as a brand's opening.\n */\nexport function aiSiteImportImproveHero(design: AiLayoutDesign, plan?: AiSiteImportPlan | null, opening?: { ratio?: number } | null): AiLayoutImportHero {\n const chosen = (plan?.design.hero as AiLayoutHeroVariant | undefined) ?? aiLayoutDesignChoices(design).hero\n const ratio = opening?.ratio ?? 0\n if (BOXED_HEROES.has(chosen) && ratio >= AI_SITE_IMPORT_COVER_LEAST_RATIO) return 'cover'\n // A square or a portrait is never stretched behind the words (AGL-4152): it sits beside them.\n if (COVERING_HEROES.has(chosen) && ratio > 0 && ratio < AI_SITE_IMPORT_COVER_LEAST_RATIO) return 'split'\n return chosen === 'collage' || chosen === 'portrait' ? 'split' : chosen\n}\n\n/** How many of a group's items sit across: planned for how much each says. */\nexport function aiSiteImportImproveColumns(items: readonly AiLayoutItem[]): number {\n const count = items.length\n if (count <= 3) return count\n const longest = Math.max(...items.map((item) => item.text.length))\n if (count === 4) return longest > 110 ? 2 : 4\n return 3\n}\n\nconst WORD_KINDS = new Set(['eyebrow', 'heading', 'lede', 'text', 'note', 'button'])\n\n/** The longest quote a kept set of quotes sets side by side. */\nconst QUOTE_ACROSS_CHARS = 220\n\n/**\n * The height a source's picture is cropped to where a redesign places it on\n * its own, in px (AGL-4152): wide across the page, closer in a column. A\n * height, not a shape: the Image takes it as its own height field, so a page\n * of pictures kept one by one repeats one style key on each (its rounding),\n * never two, which rule 16 refuses as a repeated inline style. Pictures side\n * by side in a row are cropped alike, whatever shapes they came in.\n */\nexport const AI_SITE_IMPORT_IMPROVE_FRAME_PX: Readonly<Record<'wide' | 'column', number>> = { wide: 420, column: 300 }\n\n/** The shape a picture on a card is cropped to (AGL-4152): every card of a row alike. */\nconst CARD_FRAME = '4 / 3'\n\nexport interface AiSiteImportImproveCompileInput {\n doc: AiSiteImportDocument\n ledger: SiteImportLedger\n design: AiLayoutDesign\n destinations: ReadonlyMap<string, string>\n formId: string | null\n plan?: AiSiteImportPlan | null\n /** The theme the page is drawn in, where it is known: a brand band only where the brand itself fills. */\n theme?: SiteImportFidelityTheme | null\n}\n\n/** The least share of a picture's own words a card says for the card to take that picture (AGL-4152). */\nconst CARD_PICTURE_KEPT = 0.5\n\n/**\n * The source's own pictures each set of written cards takes (AGL-4152), by\n * block: where an answer wrote like services as cards and gave none of them a\n * picture, while the page's photos of those same services sit unplaced, each\n * card takes the photo whose words it says. Every card must find one, or the\n * set takes none: a grid of cards half of which show a photo reads as broken.\n * Where no card says a photo's words but the one section's unplaced photos\n * number exactly the cards, they are taken in order, as the source laid them.\n */\nexport function aiSiteImportCardPictures(answer: readonly AiSiteImportImprovedSection[], ledger: Pick<SiteImportLedger, 'items' | 'lines'>): Map<AiSiteImportImprovedBlock, string[]> {\n const placed = new Set(aiSiteImportImprovedPlaced(answer, ledger))\n const captions = aiSiteImportPictureCaptions(ledger)\n const taken = new Set<string>()\n const out = new Map<AiSiteImportImprovedBlock, string[]>()\n for (const section of answer) {\n for (const block of section.blocks) {\n if (block.kind !== 'cards') continue\n const items = block.items ?? []\n if (items.length < 2 || items.some((item) => item.ref)) continue\n const pool = ledger.items.filter((item) => item.kind === 'picture' && !placed.has(item.ref) && !taken.has(item.ref))\n if (pool.length < items.length) continue\n const said = (ref: string) => (captions.get(ref) ?? []).map((line) => line.text)\n const chosen: string[] = []\n for (const item of items) {\n const words = `${item.title} ${item.text}`\n let best: string | null = null\n let most = CARD_PICTURE_KEPT\n for (const picture of pool) {\n if (chosen.includes(picture.ref)) continue\n const lines = said(picture.ref)\n if (!lines.length) continue\n const kept = Math.max(siteImportContentKept(lines[0] as string, words), siteImportContentKept(lines.join(' '), words))\n if (kept >= most) {\n most = kept\n best = picture.ref\n }\n }\n if (!best) break\n chosen.push(best)\n }\n const sections = new Set(pool.map((picture) => picture.section))\n const refs = chosen.length === items.length ? chosen : !chosen.length && sections.size === 1 && pool.length === items.length ? pool.map((picture) => picture.ref) : null\n if (!refs) continue\n for (const ref of refs) taken.add(ref)\n out.set(block, refs)\n }\n }\n return out\n}\n\n/** What a redesign compiles into, and what its row and its check say of it. */\nexport interface AiSiteImportImprovedPage {\n given: AiSiteImportDesigned\n names: string[]\n written: string[]\n added: AiSiteImportAddedSection[]\n pictures: AiSiteImportPagePictures\n}\n\n/** The sections' names: each heading's words, as a label, told apart. */\nfunction sectionNames(sections: readonly AiLayoutSection[], title: string): string[] {\n const taken = new Set<string>()\n return sections.map((section, index) => {\n const heading = section.blocks.find((block) => block.kind === 'heading' && block.text)?.text\n const base = siteImportLabel(heading ?? '') || (index === 0 ? siteImportLabel(title) : '') || `Section ${index + 1}`\n let name = base\n for (let at = 2; taken.has(name.toLowerCase()); at += 1) name = `${base.slice(0, 50)} (${at})`\n taken.add(name.toLowerCase())\n return name\n })\n}\n\n/**\n * The opening of a redesign without a brand's mark for its photo (AGL-4152):\n * a picture the source names a logo, a badge or an icon, or whose pixels make\n * it a graphic (`aiSiteImportIsBrandMark`),\n * that the answer keeps in its first section takes the page's widest photo no\n * section placed instead, or, where it has none, is left out, and a row it\n * leaves a column empty in is drawn as one column. A client's logo the source\n * showed beside its words read, as a cover, as the page's own work.\n */\nexport function aiSiteImportOpeningPhoto(answer: readonly AiSiteImportImprovedSection[], input: { doc: Pick<AiSiteImportDocument, 'blocks' | 'photos'>; ledger: Pick<SiteImportLedger, 'items'> }): AiSiteImportImprovedSection[] {\n const [first, ...rest] = answer\n if (!first) return [...answer]\n const { doc, ledger } = input\n const items = new Map(ledger.items.map((item) => [item.ref, item]))\n const imageOf = (ref: string) => {\n const item = items.get(ref)\n const block = item?.kind === 'picture' ? doc.blocks[item.lines[0] as number] : undefined\n return block?.kind === 'image' ? block : null\n }\n const markAt = (ref: string) => {\n const image = imageOf(ref)\n return !!image && aiSiteImportImageIsMark(image, doc.photos)\n }\n const marks = new Set(first.blocks.filter((block) => block.kind === 'keep' && markAt(block.ref)))\n if (!marks.size) return [...answer]\n const placed = new Set(aiSiteImportImprovedPlaced(answer, ledger))\n const ratioOf = (ref: string) => {\n const url = imageOf(ref)?.url\n const photo = url ? doc.photos.find((entry) => entry.from === url) : undefined\n return photo?.width && photo.height ? photo.width / photo.height : 0\n }\n const spare = ledger.items.filter((item) => item.kind === 'picture' && !placed.has(item.ref) && !markAt(item.ref)).sort((a, b) => ratioOf(b.ref) - ratioOf(a.ref))\n let next = 0\n const blocks = first.blocks.flatMap((block) => {\n if (!marks.has(block) || block.kind !== 'keep') return [block]\n const instead = spare[next++]\n return instead ? [{ ...block, ref: instead.ref }] : []\n })\n // A row with a column left empty is no row.\n const cols = first.cols\n const emptied = !!cols && cols.some((_, col) => !blocks.some((block) => block.col === col))\n const opening: AiSiteImportImprovedSection = emptied\n ? { ...(first.band ? { band: first.band } : {}), ...(first.align ? { align: first.align } : {}), blocks: blocks.map(({ col: _col, ...block }) => block as AiSiteImportImprovedBlock) }\n : { ...first, blocks }\n return [opening, ...rest]\n}\n\n/** The sections a redesign holds, in the compiler's language: every `keep` expanded to the source's own blocks, every link resolved. */\nexport function aiSiteImportImprovedPage(given: readonly AiSiteImportImprovedSection[], input: AiSiteImportImproveCompileInput): AiSiteImportImprovedPage {\n const { doc, ledger, design, destinations } = input\n // A brand's mark is never the opening's photo (AGL-4152).\n const answer = aiSiteImportOpeningPhoto(given, { doc, ledger })\n const scope = aiSiteImportMapScope(doc, { formId: input.formId, finish: 'improve' })\n const items = new Map(ledger.items.map((item) => [item.ref, item]))\n const choices = aiLayoutDesignChoices(design)\n const written: string[] = []\n // A brand band in a brand the theme had to deepen would read as neither: dark holds its place.\n const deepened = !!input.theme && !!input.theme.button.fill && input.theme.button.fill !== input.theme.light.brand\n // A link to the page it is on, or to the section it sits in, goes nowhere (AGL-4152): to the page's form where it\n // keeps one, which is what a contact page's \"Request a quote\" means, else it is left out.\n const own = aiSiteImportOwnPage(doc)\n const resolve = (to: string | undefined, at: number): string | undefined => {\n if (!to) return undefined\n const resolved = destinations.get(to) ?? undefined\n if (!resolved || (resolved !== own && resolved !== `#${at + 1}`)) return resolved\n const form = destinations.get('form')\n return form && form !== `#${at + 1}` ? form : undefined\n }\n const say = (text: string | undefined) => {\n if (text?.trim()) written.push(clean(text))\n }\n const pictureOf = (ref: string, frame: { ratio: string } | { height: number }) => {\n const item = items.get(ref)\n if (item?.kind !== 'picture') return null\n const picture = aiSiteImportTakePicture(scope, item.lines[0])\n return picture ? { ...picture, fit: { ...frame, cropped: true as const, objectFit: 'cover' as const, rounded: true as const } } : null\n }\n // A few short quotes kept whole sit side by side, as a designer sets them, wherever the old page stacked them; in a column, one under another.\n const across = (block: AiLayoutBlock, inColumn: boolean): Partial<AiLayoutBlock> => {\n const items = block.items ?? []\n if (block.kind !== 'quotes' || inColumn || items.length < 2 || items.length > 4 || items.some((entry) => entry.title.length > QUOTE_ACROSS_CHARS)) return {}\n return { columns: Math.min(3, items.length) }\n }\n const keepOf = (ref: string, col: number | undefined): AiLayoutBlock[] => {\n const item = items.get(ref)\n if (!item) return []\n const placed = col !== undefined ? { col } : {}\n if (item.kind === 'picture') {\n const picture = pictureOf(ref, { height: col !== undefined ? AI_SITE_IMPORT_IMPROVE_FRAME_PX.column : AI_SITE_IMPORT_IMPROVE_FRAME_PX.wide })\n return picture ? [{ kind: 'image', picture, ...placed }] : []\n }\n if (!item.node) return []\n scope.answer = null\n scope.groupAt = 0\n return aiSiteImportNodeBlocks(scope, [item.node], { cols: null, allowed: false }).map((block) => ({ ...block, ...placed, ...across(block, col !== undefined) }))\n }\n // The source's pictures a written set of cards stands for, where the answer gave them none (AGL-4152).\n const carded = aiSiteImportCardPictures(answer, ledger)\n // The page's own photo an opening that asks for a picture takes (AGL-4152), and which of its things it was.\n const asked = new Set([...aiSiteImportImprovedPlaced(answer, ledger), ...[...carded.values()].flat()])\n const ownOpening = { ref: null as string | null, taken: false }\n const openingPicture = (): AiLayoutPicture | null => {\n if (ownOpening.taken) return null\n const ratioOf = (line: SiteImportLineRef | undefined) => {\n const image = line === undefined || scope.used.has(line) ? undefined : doc.blocks[line]\n if (image?.kind !== 'image' || aiSiteImportImageIsMark(image, scope.photos)) return 0\n const photo = scope.photos.get(image.url)\n return photo?.width && photo.height ? photo.width / photo.height : 0\n }\n const widest = (found: Array<{ ref: string | null; line: SiteImportLineRef | undefined }>) => found.filter((entry) => ratioOf(entry.line) > 0).sort((a, b) => ratioOf(b.line) - ratioOf(a.line))[0]\n // Its photo no section places; else one of a gallery it keeps, which shows the rest.\n const pick =\n widest(ledger.items.filter((item) => item.kind === 'picture' && !asked.has(item.ref)).map((item) => ({ ref: item.ref, line: item.lines[0] }))) ??\n widest(ledger.items.filter((item) => item.kind === 'gallery' && asked.has(item.ref)).flatMap((item) => item.lines.map((line) => ({ ref: null, line }))))\n const picture = pick ? aiSiteImportTakePicture(scope, pick.line) : null\n if (!picture) return null\n ownOpening.taken = true\n ownOpening.ref = pick?.ref ?? null\n return picture\n }\n const sections = answer.map((section, index): AiLayoutSection => {\n scope.at = `sections[${index}]`\n const words = section.blocks.flatMap((block) => (block.kind === 'heading' || block.kind === 'eyebrow' ? [block.text ?? ''] : [])).join(' ')\n const drawn = section.blocks.flatMap((raw): AiLayoutBlock[] => {\n if (raw.kind === 'keep') return keepOf(raw.ref, raw.col)\n const block = raw\n const placed = block.col !== undefined ? { col: block.col } : {}\n if (block.kind === 'image') {\n const { col: _col, ...rest } = block\n // An opening that asks for a picture shows the page's own where it has one (AGL-4152): a slot the\n // library fills is searched by words alone, and put a stranger's desk on a builder's gallery.\n const own = index === 0 && !block.picture?.src ? openingPicture() : null\n return [{ ...rest, ...(own ? { picture: own } : {}), ...placed }]\n }\n if (block.kind === 'text' || block.kind === 'lede' || block.kind === 'note') {\n say(block.text)\n return aiSiteImportTextParts(block.text ?? '').map((part) => ({ ...block, text: part }))\n }\n if (block.kind === 'heading' || block.kind === 'eyebrow') {\n say(block.text)\n return [block]\n }\n if (block.kind === 'button') {\n const to = resolve(block.to, index)\n // A button that goes nowhere a visitor is not already is no call to action: it is left out.\n if (block.to && !to) return []\n say(block.text)\n const { to: _asked, ...rest } = block\n return [{ ...rest, ...(to ? { to } : {}) }]\n }\n const groupItems = (block.items ?? []).map((item, at): AiLayoutItem => {\n say(item.title)\n say(item.text)\n const given = item.ref || carded.get(block)?.[at]\n const picture = given ? pictureOf(given, { ratio: CARD_FRAME }) : null\n const to = resolve(item.to, index)\n const { ref: _ref, to: _to, ...rest } = item\n return { ...rest, ...(block.kind === 'steps' ? { figure: String(at + 1) } : {}), ...(picture ? { picture } : {}), ...(to ? { to } : {}) }\n })\n if (block.kind === 'list') return [{ ...block, items: groupItems, columns: groupItems.length >= 6 ? 2 : 1 }]\n if (block.kind === 'faq') return [{ ...block, items: groupItems, columns: 1 }]\n const pictured = groupItems.every((item) => item.picture)\n const iconed = groupItems.every((item) => item.icon)\n const wanted = aiLayoutGroupVariant(design, choices, words)\n const variant = pictured ? (choices.group === 'cards' ? 'articles' : 'pictures') : wanted === 'icons' && !iconed ? 'cards' : wanted === 'menu' || wanted === 'pictures' || wanted === 'articles' ? 'cards' : wanted\n return [{ ...block, items: groupItems, columns: aiSiteImportImproveColumns(groupItems), variant }]\n })\n // Each call to action once, in its place (AGL-4152).\n const tidy = aiSiteImportSectionActions({ cols: section.cols, blocks: drawn }, input.plan?.nav.primaryCta?.label)\n const blocks = tidy.blocks\n const pictures = blocks.filter((block) => block.kind === 'image' || block.kind === 'video')\n const opens = index === 0 && pictures.length === 1 && blocks.every((block) => block.kind === 'image' || block.kind === 'video' || WORD_KINDS.has(block.kind))\n const opening = pictures[0]?.kind === 'image' ? (pictures[0].picture ?? null) : null\n const hero = opens ? aiSiteImportImproveHero(design, input.plan, opening) : null\n const band = section.band === 'brand' && deepened ? 'dark' : section.band\n return {\n ...(band ? { band } : {}),\n ...(section.align ? { align: section.align } : {}),\n // A hero draws its own columns, and frames its own picture.\n ...(tidy.cols && !hero ? { cols: tidy.cols } : {}),\n ...(hero ? { hero, blocks: blocks.map((block) => (block.kind === 'image' && block.picture ? { ...block, picture: { ...block.picture, fit: undefined } } : block)) } : { blocks }),\n }\n })\n const names = sectionNames(sections, doc.title)\n const added: AiSiteImportAddedSection[] = aiSiteImportImproveNewSections(answer, ledger).map((index) => {\n const group = sections[index]?.blocks.find((block) => block.items?.length)\n return { heading: names[index] as string, ...(group?.items?.length ? { items: group.items.length } : {}) }\n })\n const placed = new Set([...asked, ...(ownOpening.ref ? [ownOpening.ref] : [])])\n const allPictures = ledger.items.filter((item) => item.kind === 'picture')\n const unplaced = allPictures.filter((item) => !placed.has(item.ref)).flatMap((item) => {\n const block = doc.blocks[item.lines[0] as number]\n return block?.kind === 'image' ? [block.url] : []\n })\n return {\n given: { sections, used: scope.used, missing: scope.missing, settled: scope.settled },\n names,\n written,\n added,\n pictures: {\n // A gallery's photo the opening shows is the source's too.\n source: allPictures.length - unplaced.length + (ownOpening.taken && !ownOpening.ref ? 1 : 0),\n stock: 0,\n generated: 0,\n slots: sections.reduce((total, section) => total + section.blocks.filter((block) => block.kind === 'image' && !block.picture).length, 0),\n unplaced,\n },\n }\n}\n\n/*------------------------------------------\n * The check\n *-----------------------------------------*/\n\n/** The most an answer may ask for, whatever the page and the model: a whole page's design and words, with its thinking. */\nexport const AI_SITE_IMPORT_IMPROVE_MOST_TOKENS = 8_000\n\n/**\n * Room a page's ceiling keeps for its listing pass (AGL-4152): its p90 is 1,\n * and it runs a model only where the source left the listing empty.\n */\nexport const AI_SITE_IMPORT_LISTING_ROOM_CREDITS = 10\n\n/**\n * What a page's redesign may spend, its answer and its re-ask together\n * (AGL-4152): the page's ceiling, less its listing pass's room. Held in code\n * (`aiSiteImportImproveTokensWithin`): an answer asks no more than the\n * ceiling buys, and a re-ask it cannot pay for is not asked.\n */\nexport const AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS = AI_SITE_IMPORT_PAGE_CEILING_CREDITS - AI_SITE_IMPORT_LISTING_ROOM_CREDITS\n\n/** Characters a token is counted at, before a request is sent: fewer than the text runs, so a guess is never under. */\nconst CHARS_PER_TOKEN = 3\n\nconst ZERO: AiUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }\n\nconst plus = (a: AiUsage, b: AiUsage): AiUsage => ({\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,\n cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,\n})\n\n/** What a request reads before it is sent, at worst: its system blocks written to the cache, its turn as input. */\nexport function aiSiteImportImproveInputUsage(input: { systemChars: number; promptChars: number }): AiUsage {\n return { ...ZERO, inputTokens: Math.ceil(input.promptChars / CHARS_PER_TOKEN), cacheWriteTokens: Math.ceil(input.systemChars / CHARS_PER_TOKEN) }\n}\n\n/** What a usage is billed in credits on a model. */\nexport function aiSiteImportImproveCredits(usage: AiUsage, model: string): number {\n return assistCreditsFromUsd(estimateAiBilledUsd(usage, model))\n}\n\n/**\n * The most output tokens a request may write (AGL-4152) with `spent` already\n * spent and `input` still to read, and stay inside `ceiling` credits; at\n * most `most`, and 0 where its reading alone would pass the ceiling.\n */\nexport function aiSiteImportImproveTokensWithin(input: { model: string; spent: AiUsage; input: AiUsage; ceiling?: number; most: number }): number {\n const ceiling = input.ceiling ?? AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS\n const before = plus(input.spent, input.input)\n const fits = (tokens: number) => aiSiteImportImproveCredits({ ...before, outputTokens: before.outputTokens + tokens }, input.model) <= ceiling\n if (!fits(0)) return 0\n let low = 0\n let high = Math.max(0, Math.floor(input.most))\n while (low < high) {\n const mid = Math.ceil((low + high) / 2)\n if (fits(mid)) low = mid\n else high = mid - 1\n }\n return low\n}\n\n/** The least share of the last answer's length a re-ask must have room for: less, and it would be cut off. */\nexport const AI_SITE_IMPORT_REASK_ROOM = 0.9\n\n/** What a re-ask reads beyond its first request: the re-ask's own words naming what missed. */\nconst REASK_TOKENS = 600\n\n/**\n * Whether a redesign's re-ask fits its page's ceiling (AGL-4152): the most\n * tokens it may ask, given what the first answer spent, or 0 where the room\n * left is under what the first answer wrote, and the page falls back with\n * no re-ask rather than pass its ceiling.\n */\nexport function aiSiteImportImproveReaskTokens(input: { model: string; spent: AiUsage; lastOutput: number; most: number; ceiling?: number }): number {\n // The re-ask reads what the first request read, its system now from the cache at worst at the write's rate, and the re-ask's words.\n const again: AiUsage = { ...ZERO, inputTokens: input.spent.inputTokens + REASK_TOKENS, cacheReadTokens: input.spent.cacheReadTokens, cacheWriteTokens: input.spent.cacheWriteTokens }\n const room = aiSiteImportImproveTokensWithin({ model: input.model, spent: input.spent, input: again, most: input.most, ...(input.ceiling !== undefined ? { ceiling: input.ceiling } : {}) })\n return room >= Math.ceil(input.lastOutput * AI_SITE_IMPORT_REASK_ROOM) ? room : 0\n}\n\n/** What a redesign settled: the page built, what it added and what it shows. */\nexport interface AiSiteImportImproved<T> {\n built: T\n page: AiSiteImportImprovedPage\n /** The design lines it was taken with still missed, by code (`AI_SITE_IMPORT_IMPROVE_SOFT_CODES`): only where no re-ask was left. */\n missed?: string[]\n}\n\n/**\n * What a redesign may still miss when no re-ask is left and be taken all the\n * same (AGL-4152): how it is planned and drawn, never what it says or holds.\n * Each is asked for in the one re-ask where it can be paid for; past it, the\n * old layout redrawn is no better on any of them than the redesign, and worse\n * on every other, so a miss here is noted on the page's row, not fallen back\n * on. What it says, holds, links and reads as (facts, invented, held, links,\n * meaning, contrast, a phone's width) stays a fallback.\n */\nexport const AI_SITE_IMPORT_IMPROVE_SOFT_CODES: ReadonlySet<string> = new Set([\n 'improve-new-sections',\n 'improve-opening',\n 'improve-shapes',\n 'improve-cta',\n 'improve-rhythm',\n 'improve-columns',\n 'improve-framing',\n])\n\n/** The most reasons a page's record keeps of why its redesign missed (AGL-4152). */\nexport const AI_SITE_IMPORT_REDESIGN_WHY_MOST = 8\n\n/** The most characters one reason keeps: the line it names and what it says of it. */\nexport const AI_SITE_IMPORT_REDESIGN_WHY_CHARS = 300\n\n/**\n * Why a redesign missed, line by line (AGL-4152): each violation's code, its\n * message (which names the line it found, `section 1, block 2, \"…\"`) and its\n * detail, cut short, at most `AI_SITE_IMPORT_REDESIGN_WHY_MOST`. What the\n * page's log and its record say, so a miss can be read after the job, when\n * the answer itself is gone. For the job's record, never the owner's row.\n */\nexport function aiSiteImportRedesignWhy(violations: readonly AiDoctrineViolation[]): string[] {\n const out: string[] = []\n for (const violation of violations) {\n const said = clean(`${violation.code}: ${violation.message}${violation.detail ? ` ${violation.detail}` : ''}`)\n const line = said.length > AI_SITE_IMPORT_REDESIGN_WHY_CHARS ? `${said.slice(0, AI_SITE_IMPORT_REDESIGN_WHY_CHARS - 1)}…` : said\n if (!out.includes(line)) out.push(line)\n if (out.length >= AI_SITE_IMPORT_REDESIGN_WHY_MOST) break\n }\n return out\n}\n\n/** Whether every miss of an answer is one it may be taken with past its last re-ask. */\nexport function aiSiteImportImproveOnlySoft(violations: readonly AiDoctrineViolation[]): boolean {\n return violations.length > 0 && violations.every((violation) => AI_SITE_IMPORT_IMPROVE_SOFT_CODES.has(violation.code))\n}\n\n/**\n * The words of a site's plan (AGL-4152): what it says the site is and who it\n * is for, its menu's and footer's labels, its call to action and its proposed\n * page. A redesign is told the plan as its digest, and the plan's own words\n * were held to what the site says when it was made, so a redesign that\n * repeats them invents nothing.\n */\nexport function aiSiteImportPlanLines(plan: AiSiteImportPlan | null | undefined): string[] {\n if (!plan) return []\n return [\n plan.site.what,\n plan.site.audience,\n ...plan.nav.groups.map((group) => group.label),\n ...plan.nav.footer.map((group) => group.label),\n ...(plan.nav.primaryCta ? [plan.nav.primaryCta.label] : []),\n ...(plan.proposed ? [plan.proposed.title, plan.proposed.purpose] : []),\n ].filter((line): line is string => typeof line === 'string' && !!line.trim())\n}\n\n/** A web address's top-level part, which says nothing of a name. */\nconst TLD = /\\.(?:com|org|net|io|co|ai|app|dev|us|uk|ca|au|de|fr|info|biz|me|shop|store|site|online)(?:\\.[a-z]{2})?$/i\n\n/**\n * The ways a site's name is said (AGL-4152), where it is written as one run\n * of letters: a web address (\"RidgelineBuilders.com\") or a name run together.\n * Its address part dropped, its capitals and digits split (\"Ridgeline\n * Builders\"), a run of capitals on its own (\"ABC\" of \"ABCroofing\"), and a run\n * of small letters split into the words the site says elsewhere (\"roofing\n * site\" of \"roofingsite\"). A redesign that names the business as a visitor\n * would invents nothing.\n */\nexport function aiSiteImportNameVariants(name: string, said: ReadonlySet<string>): string[] {\n const text = clean(name)\n if (!text || /\\s/.test(text) || text.length < 4) return []\n const bare = text.replace(/^https?:\\/\\//i, '').replace(/^www\\./i, '').replace(/\\/.*$/, '').replace(TLD, '')\n // A run of small letters as the words the site says, longest first; itself where they do not make it up.\n const segment = (run: string): string[] => {\n if (run.length < 6 || said.has(run.toLowerCase())) return [run]\n const out: string[] = []\n let rest = run.toLowerCase()\n while (rest) {\n let found = ''\n for (let end = rest.length; end >= 3 && !found; end -= 1) if (said.has(rest.slice(0, end))) found = rest.slice(0, end)\n if (!found) return [run]\n out.push(found)\n rest = rest.slice(found.length)\n }\n return out\n }\n const words = bare\n .split(/[-_.]+|(?<=[a-z])(?=[A-Z])|(?<=[A-Za-z])(?=\\d)|(?<=\\d)(?=[A-Za-z])/)\n .filter(Boolean)\n .flatMap((part) => {\n // A run of capitals before small letters: \"ABCroofing\" is \"ABC\" and \"roofing\", \"ABCRoofing\" \"ABC\" and \"Roofing\".\n const lead = /^([A-Z]{2,})([a-z]+)$/.exec(part)\n if (!lead) return segment(part)\n const caps = lead[1] as string\n const tail = `${caps.slice(-1)}${lead[2] as string}`\n return said.has(tail.toLowerCase()) ? [caps.slice(0, -1), tail] : [caps, ...segment(lead[2] as string)]\n })\n const titled = words.map((word) => (/^[a-z]/.test(word) ? `${word[0]?.toUpperCase()}${word.slice(1)}` : word)).join(' ')\n return [...new Set([bare, titled])].filter((variant) => variant && variant !== text)\n}\n\n/** Every line a redesign's facts may come from: its page, what the site says of itself, its wave's other pages, its plan, its name. */\nexport function aiSiteImportImproveScope(doc: Pick<AiSiteImportDocument, 'blocks' | 'siteLines' | 'scope' | 'title'> & { plan?: AiSiteImportPlan | null }, siteName: string | null): string[] {\n const own = doc.blocks.flatMap((block) => (block.kind === 'image' ? (block.alt ? [block.alt] : []) : block.text ? [block.text] : []))\n const lines = [...own, ...(doc.siteLines ?? []), ...(doc.scope ?? []), ...aiSiteImportPlanLines(doc.plan), doc.title, ...(siteName ? [siteName] : [])].map(clean).filter(Boolean)\n // The site's name as a visitor says it, where it is written as an address or run together (AGL-4152).\n const said = new Set(lines.flatMap((line) => line.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []))\n const names = [...new Set([...(siteName ? [siteName] : []), ...(doc.siteLines ?? []).slice(0, 6)])]\n const variants = names.flatMap((name) => aiSiteImportNameVariants(name, said)).filter((variant) => !lines.includes(variant))\n return [...lines, ...variants]\n}\n\n/** What each line that missed says to the one re-ask. */\nconst MISS: Readonly<Record<string, string>> = {\n facts: 'The page leaves out a fact the owner gives. Say every name, number, price, date, phone and address the ledger shows.',\n invented: 'The page says something nothing on the site supports.',\n held: 'Something the ledger marks must is not on the page. Place it with a keep block.',\n links: 'A link the ledger lists goes nowhere on the page. Link to it from a button or an item.',\n meaning: \"The page has drifted from what the owner says. Keep more of the old page's substance in the new words.\",\n cta: 'The opening needs a filled primary button with a real destination, and the last section a button or the form: close on a call to action.',\n rhythm: 'Neighboring sections sit on one ground. Alternate plain and soft, or set one on a strong band.',\n columns: 'Sections stack like things in one column, or the page draws no group at all. Set a picture beside its words, and three or more like items as cards, steps or a faq.',\n framing: 'A picture is drawn taller than a screen holds. Set it in a column, or on a card.',\n contrast: 'A section is drawn on a ground its words do not read on. Choose another band.',\n phone: 'A section does not hold on a phone. Use the language’s rows and groups, which stack.',\n}\n\n/** A scored redesign's misses, each as the re-ask names it: what is red on its ledger and its design lines. */\nexport function aiSiteImportImprovedMisses(report: Pick<SiteImportPageFidelity, 'improved'>): AiDoctrineViolation[] {\n const improved = report.improved\n if (!improved) return []\n return improved.red.flatMap((name) => {\n if (name === 'frame') return []\n const ledger = improved.ledger as unknown as Record<string, { missing?: string[]; found?: string[] } | undefined>\n const shown = [...(ledger[name]?.missing ?? []), ...(ledger[name]?.found ?? [])].map((token) => token.replace(/^[a-z]+:/, ''))\n const message = MISS[name] ?? `The page falls short on ${name}.`\n return [{ rule: null, code: `improve-${name}`, message, ...(shown.length ? { detail: `Named: ${shown.join(', ')}.` } : {}) }]\n })\n}\n\n/** A redesign's read for a page: its ledger, and everywhere a link may go. */\nexport function aiSiteImportImproveLedger(doc: AiSiteImportDocument): SiteImportLedger {\n return siteImportLedger({ layout: aiSiteImportLayoutOf(doc), blocks: doc.blocks, photos: doc.photos })\n}\n\n/**\n * A redesign's check (AGL-4152), answer by answer: its words and refs held to\n * what the import read, its page compiled and held to the doctrine as a page\n * written (`build`), and scored (`score`). Any miss is named for the one\n * re-ask; a second miss is the caller's fallback.\n */\nexport function aiSiteImportImproveCheck<T>(input: {\n doc: AiSiteImportDocument\n ledger: SiteImportLedger\n design: AiLayoutDesign\n scope: readonly string[]\n formId: string | null\n framing?: AiCopyFraming | null\n plan?: AiSiteImportPlan | null\n theme?: SiteImportFidelityTheme | null\n /** What the page is for and the new sections it needs; absent, nothing is asked of its plan. */\n needs?: AiSiteImportImproveNeeds | null\n /** Words the platform's own request put to the answer (its role's lines), no one's name or fact. */\n vocabulary?: readonly string[]\n build: (page: AiSiteImportImprovedPage) => { value: T | null; violations: AiDoctrineViolation[] }\n score: (built: T, destinations: readonly string[]) => AiDoctrineViolation[]\n /**\n * The last answer read again once no re-ask is left (AGL-4152): its soft\n * misses (`AI_SITE_IMPORT_IMPROVE_SOFT_CODES`) are noted, not refused.\n * Every other line holds exactly as on the first read.\n */\n lenient?: boolean\n}): AiGenerationCheck<AiSiteImportImproved<T>> {\n return (answer) => {\n const read = aiReadImprovedPage(answer)\n if (!read) return { value: null, violations: [{ rule: null, code: 'improve-unreadable', message: `The answer gave no section that can be drawn. Answer with ${AI_SITE_IMPORT_IMPROVE_TOOL.name}.` }] }\n const formAt = read.findIndex((section) => section.blocks.some((block) => block.kind === 'keep' && block.ref.startsWith('form:')))\n const destinations = aiSiteImportImproveDestinations(input.doc, input.ledger, { sections: read.length, formSection: formAt === -1 ? null : formAt })\n const own = aiSiteImportOwnPage(input.doc)\n const honesty = aiSiteImportHonesty(read, { ledger: input.ledger, scope: input.scope, destinations, framing: input.framing ?? null, vocabulary: input.vocabulary ?? [], own })\n // What it lost and how it is planned, named together, so the one re-ask mends both.\n const planned = input.needs ? aiSiteImportImprovePlanMisses(read, { ledger: input.ledger, needs: input.needs }) : []\n const missed: string[] = input.lenient ? planned.map((violation) => violation.code) : []\n if (honesty.length || (planned.length && !input.lenient)) return { value: null, violations: [...honesty, ...planned] }\n const page = aiSiteImportImprovedPage(read, { doc: input.doc, ledger: input.ledger, design: input.design, destinations, formId: input.formId, plan: input.plan ?? null, theme: input.theme ?? null })\n const built = input.build(page)\n if (!built.value) return { value: null, violations: built.violations }\n // A link the source makes to the page it is on asks nothing of the page (AGL-4152).\n const wanted = input.ledger.links.flatMap((link) => {\n const to = destinations.get(link.ref)\n return to && to !== own ? [to] : []\n })\n const scored = input.score(built.value, [...new Set(wanted)])\n const refused = input.lenient ? scored.filter((violation) => !AI_SITE_IMPORT_IMPROVE_SOFT_CODES.has(violation.code)) : scored\n if (refused.length) return { value: null, violations: refused }\n missed.push(...scored.map((violation) => violation.code))\n return { value: { built: built.value, page, ...(missed.length ? { missed: [...new Set(missed)] } : {}) }, violations: [] }\n }\n}\n"],"names":["fenceUntrustedText","UNTRUSTED_TEXT_RULE","aiLayoutDesignChoices","aiLayoutGroupVariant","AI_LAYOUT_ALIGNS","AI_LAYOUT_BANDS","AI_LAYOUT_MAX_COLS","AI_LAYOUT_STYLES","aiReadLayoutBlock","AI_ICON_WORDS","aiSiteHomeArc","SITE_IMPORT_IMPROVED_MEANING","SITE_IMPORT_MEANING_FLOOR","siteImportContentKept","siteImportContentWords","aiSiteImportImageIsMark","siteImportLedger","AI_SITE_IMPORT_PAGE_CEILING_CREDITS","estimateAiBilledUsd","assistCreditsFromUsd","siteImportLabel","aiSiteImportHonesty","aiSiteImportImprovedPlaced","aiSiteImportSectionActions","aiSiteImportLayoutOf","aiSiteImportLinkTo","aiSiteImportMapScope","aiSiteImportNodeBlocks","aiSiteImportTakePicture","aiSiteImportTextParts","clean","text","replace","trim","AI_SITE_IMPORT_IMPROVE_KIND","AI_SITE_IMPORT_IMPROVE_MAX_ITEMS","AI_SITE_IMPORT_IMPROVE_BLOCK_KINDS","ITEM_SCHEMA","type","additionalProperties","required","properties","title","to","icon","ref","BLOCK_SCHEMA","kind","enum","col","style","items","AI_SITE_IMPORT_IMPROVE_TOOL","name","description","strict","inputSchema","sections","band","cols","align","blocks","AI_SITE_IMPORT_IMPROVE_TEXT","join","aiSiteImportImproveDigest","input","siteName","scope","filter","Boolean","maxChars","AI_SITE_IMPORT_IMPROVE_DIGEST_CHARS","plan","JSON","stringify","aiSiteImportImproveInstructions","digest","cacheBreakpoint","site","AI_SITE_IMPORT_LEDGER_MAX_CHARS","textOf","block","short","most","length","slice","aiSiteImportPictureCaptions","ledger","pictures","item","lines","undefined","out","Map","at","next","Math","min","other","section","map","Number","POSITIVE_INFINITY","line","group","set","shownItem","doc","captions","must","words","url","photo","photos","find","entry","from","alt","with_","get","width","height","node","rows","alts","flatMap","columns","titles","test","linked","some","shown","folded","holds","aiSiteImportLedgerText","destinations","Set","links","link","has","aiSiteImportImproveDestinations","pathTo","path","id","href","page","proposed","siteLines","phone","exec","email","key","formSection","formPage","aiSiteImportFormPageOf","n","cta","nav","primaryCta","target","aiSiteImportOwnPage","URL","pathname","own","aiSiteImportImprovePrompt","screen","slug","roleLines","kindLines","seed","AI_SITE_IMPORT_NEW_SECTIONS","home","service","about","gallery","pricing","contact","faq","AI_SITE_IMPORT_ROLE_MEANING","aiSiteImportMeaningShare","role","AI_SITE_IMPORT_REWORK_LEAST_WORDS","AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS","aiSiteImportPageRoleOf","toLowerCase","aiSiteImportNewSectionsWanted","size","max","ROLE_PLAN","aiSiteImportImproveRoleLines","wanted","arc","aiSiteImportImproveNewSections","answer","sources","kinds","said","reworked","best","forEach","index","kept","add","last","groups","shapeOf","includes","whole","AI_SITE_IMPORT_IMPROVE_LEAST_SHAPES","PICTURED_OPENINGS","aiSiteImportImprovePlanMisses","added","needs","push","rule","code","message","opening","startsWith","shapes","aiReadImprovedPage","raw","settled","given","Array","isArray","value","isFinite","round","position","isInteger","mostItems","_col","rest","AI_SITE_IMPORT_COVER_LEAST_RATIO","BOXED_HEROES","COVERING_HEROES","aiSiteImportImproveHero","design","chosen","hero","ratio","aiSiteImportImproveColumns","count","longest","WORD_KINDS","QUOTE_ACROSS_CHARS","AI_SITE_IMPORT_IMPROVE_FRAME_PX","wide","column","CARD_FRAME","CARD_PICTURE_KEPT","aiSiteImportCardPictures","placed","taken","pool","picture","refs","sectionNames","heading","base","aiSiteImportOpeningPhoto","first","imageOf","markAt","image","marks","ratioOf","spare","sort","a","b","instead","emptied","_","aiSiteImportImprovedPage","formId","finish","choices","written","deepened","theme","button","fill","light","brand","resolve","resolved","form","say","pictureOf","frame","fit","cropped","objectFit","rounded","across","inColumn","keepOf","groupAt","allowed","carded","asked","values","flat","ownOpening","openingPicture","widest","used","found","pick","drawn","src","part","_asked","groupItems","_ref","_to","figure","String","pictured","every","iconed","variant","tidy","label","opens","names","allPictures","unplaced","missing","source","stock","generated","slots","reduce","total","AI_SITE_IMPORT_IMPROVE_MOST_TOKENS","AI_SITE_IMPORT_LISTING_ROOM_CREDITS","AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS","CHARS_PER_TOKEN","ZERO","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","plus","aiSiteImportImproveInputUsage","ceil","promptChars","systemChars","aiSiteImportImproveCredits","usage","model","aiSiteImportImproveTokensWithin","ceiling","before","spent","fits","tokens","low","high","floor","mid","AI_SITE_IMPORT_REASK_ROOM","REASK_TOKENS","aiSiteImportImproveReaskTokens","again","room","lastOutput","AI_SITE_IMPORT_IMPROVE_SOFT_CODES","AI_SITE_IMPORT_REDESIGN_WHY_MOST","AI_SITE_IMPORT_REDESIGN_WHY_CHARS","aiSiteImportRedesignWhy","violations","violation","detail","aiSiteImportImproveOnlySoft","aiSiteImportPlanLines","what","audience","footer","purpose","TLD","aiSiteImportNameVariants","bare","segment","run","end","split","lead","caps","tail","titled","word","toUpperCase","aiSiteImportImproveScope","match","variants","MISS","facts","invented","held","meaning","rhythm","framing","contrast","aiSiteImportImprovedMisses","report","improved","red","token","aiSiteImportImproveLedger","layout","aiSiteImportImproveCheck","read","formAt","findIndex","honesty","vocabulary","planned","missed","lenient","built","build","scored","score","refused"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SAASA,kBAAkB,EAAEC,mBAAmB,QAAQ,0CAAyC;AAEjG,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,yCAAqC;AACjG,SACEC,gBAAgB,EAChBC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,QAOZ,2CAAuC;AAC9C,SAASC,aAAa,QAAQ,gCAA4B;AAE1D,SAASC,aAAa,QAAQ,gCAA4B;AAC1D,SACEC,4BAA4B,EAC5BC,yBAAyB,EACzBC,qBAAqB,EACrBC,sBAAsB,QAGjB,sCAAkC;AACzC,SAASC,uBAAuB,QAAQ,mCAA+B;AACvE,SAASC,gBAAgB,QAAqF,oCAAgC;AAC9I,SAASC,mCAAmC,QAAQ,6BAAyB;AAC7E,SAASC,mBAAmB,QAAQ,0BAAsB;AAE1D,SAASC,oBAAoB,QAAQ,6BAAyB;AAI9D,SAASC,eAAe,QAAQ,qCAAiC;AACjE,SAASC,mBAAmB,EAAEC,0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,MAAM;YAAEvG;YAAc6I,QAAQnN,MAAMmN,MAAM;YAAE5M,IAAI,GAAEP,cAAAA,MAAMO,IAAI,YAAVP,cAAc;YAAMwN,KAAK,GAAExN,eAAAA,MAAMwN,KAAK,YAAXxN,eAAe;QAAK;QACnM,MAAMsW,QAAQtW,MAAMuW,KAAK,CAACvR;QAC1B,IAAI,CAACsR,MAAMrM,KAAK,EAAE,OAAO;YAAEA,OAAO;YAAMoJ,YAAYiD,MAAMjD,UAAU;QAAC;QACrE,oFAAoF;QACpF,MAAMxL,SAAS7H,MAAMsB,MAAM,CAACkD,KAAK,CAACZ,OAAO,CAAC,CAACa;YACzC,MAAM/F,KAAK4F,aAAahB,GAAG,CAACmB,KAAK7F,GAAG;YACpC,OAAOF,MAAMA,OAAOwH,MAAM;gBAACxH;aAAG,GAAG,EAAE;QACrC;QACA,MAAM8X,SAASxW,MAAMyW,KAAK,CAACH,MAAMrM,KAAK,EAAE;eAAI,IAAI1F,IAAIsD;SAAQ;QAC5D,MAAM6O,UAAU1W,MAAMqW,OAAO,GAAGG,OAAOrW,MAAM,CAAC,CAACmT,YAAc,CAACL,kCAAkCvO,GAAG,CAAC4O,UAAUhK,IAAI,KAAKkN;QACvH,IAAIE,QAAQvV,MAAM,EAAE,OAAO;YAAE8I,OAAO;YAAMoJ,YAAYqD;QAAQ;QAC9DN,OAAOhN,IAAI,IAAIoN,OAAOrU,GAAG,CAAC,CAACmR,YAAcA,UAAUhK,IAAI;QACvD,OAAO;YAAEW,OAAO;gBAAEqM,OAAOA,MAAMrM,KAAK;gBAAEjF;eAAUoR,OAAOjV,MAAM,GAAG;gBAAEiV,QAAQ;uBAAI,IAAI7R,IAAI6R;iBAAQ;YAAC,IAAI,CAAC;YAAM/C,YAAY,EAAE;QAAC;IAC3H;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-improve.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * IMPROVE IT, GENERATIVE: A PAGE REDESIGNED FROM A LEDGER (AGL-4152).\n *\n * Today's Improve it draws the source's layout in a new design and rewords its\n * lines in place. Behind `SITE_IMPORT_GENERATIVE_RELEASE_FLAG` a main page is\n * instead designed the way Start with AI designs one, from what the import\n * read: one `submit_improved_page` answer plans the sections and the grid and\n * writes the words, and code places what the source holds.\n *\n * 1. The answer is told the page as a LEDGER (`aiSiteImportLedgerText`): each\n * picture, form, plan, table, quote, video and contact line by a ref a\n * `keep` block places, each link's destination, and the numbered lines it\n * rewrites freely.\n * 2. It is held by code: the honesty validator over its words and its refs\n * (`ai-site-import-honesty.ts`), then the page compiled and scored on the\n * kept ledger and the design lines (`siteImportFidelity`). A miss is named\n * in the one re-ask.\n * 3. Compiled by the site compiler with `keep` expanded to the source's own\n * blocks, and a picture asked for in words left as a slot the page step's\n * pictures fill or drop.\n *\n * Nothing here runs with the flag off, or for Keep my site.\n *=========================================*/\n\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport type { AiLayoutDesign, AiLayoutHeroVariant } from '../layout-language/ai-layout-design'\nimport { aiLayoutDesignChoices, aiLayoutGroupVariant } from '../layout-language/ai-layout-design'\nimport {\n AI_LAYOUT_ALIGNS,\n AI_LAYOUT_BANDS,\n AI_LAYOUT_MAX_COLS,\n AI_LAYOUT_STYLES,\n aiReadLayoutBlock,\n type AiLayoutBlock,\n type AiLayoutImportHero,\n type AiLayoutPicture,\n type AiLayoutItem,\n type AiLayoutSection,\n type AiLayoutSettlement,\n} from '../layout-language/ai-layout-language'\nimport { AI_ICON_WORDS } from '../runtime/ai-icon-library'\nimport type { AiSiteImportAddedSection, AiSiteImportPagePictures, AiSiteImportPageRole, AiSiteImportPlan, SiteImportLineRef } from '../model/ai-site-import'\nimport { aiSiteHomeArc } from '../model/ai-site-home-arcs'\nimport {\n SITE_IMPORT_IMPROVED_MEANING,\n SITE_IMPORT_MEANING_FLOOR,\n siteImportContentKept,\n siteImportContentWords,\n type SiteImportFidelityTheme,\n type SiteImportPageFidelity,\n} from '../model/ai-site-import-fidelity'\nimport { aiSiteImportImageIsMark } from '../model/ai-site-import-marks'\nimport { siteImportLedger, type SiteImportLedger, type SiteImportLedgerItem, type SiteImportLedgerLine } from '../model/ai-site-import-ledger'\nimport { AI_SITE_IMPORT_PAGE_CEILING_CREDITS } from '../model/ai-site-import'\nimport { aiCacheWriteHourSurchargeUsd } from '../providers/cache-write-hour'\nimport { aiBilledRatesForModel, estimateAiBilledUsd } from '../providers/catalog'\nimport type { AiSystemBlock, AiTool, AiUsage } from '../providers/contract'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport type { AiGenerationCheck } from '../runtime/ai-doctrine'\nimport type { AiCopyFraming, AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport type { SiteImportBlock } from '../site-import/site-import-html'\nimport { siteImportLabel } from '../site-import/site-import-page'\nimport { aiSiteImportHonesty, aiSiteImportImprovedPlaced, type AiSiteImportImprovedBlock, type AiSiteImportImprovedSection } from './ai-site-import-honesty'\nimport { aiSiteImportSectionActions } from './ai-site-import-actions'\nimport {\n aiSiteImportLayoutOf,\n aiSiteImportLinkTo,\n aiSiteImportMapScope,\n aiSiteImportNodeBlocks,\n aiSiteImportTakePicture,\n type AiSiteImportDesigned,\n} from './ai-site-import-compile'\nimport { aiSiteImportTextParts, type AiSiteImportDocument } from './ai-site-import-document'\n\nconst clean = (text: unknown): string => (typeof text === 'string' ? text.replace(/\\s+/g, ' ').trim() : '')\n\n/*------------------------------------------\n * The tool and its cached text\n *-----------------------------------------*/\n\n/** The answer's kind of generation: the name its re-ask and its doctrine scope go by. */\nexport const AI_SITE_IMPORT_IMPROVE_KIND = 'page-improve'\n\n/**\n * The most items a redesign's group keeps (AGL-4152): every item its owner's\n * page has, where the layout language's own pages stop at seven. A page\n * brought in is compiled as its source lays it out, with no such limit.\n */\nexport const AI_SITE_IMPORT_IMPROVE_MAX_ITEMS = 24\n\n/** What a block may be: the layout language's words and groups, and `keep`. A customer's quote and a figure only ever arrive by `keep`. */\nexport const AI_SITE_IMPORT_IMPROVE_BLOCK_KINDS = ['eyebrow', 'heading', 'lede', 'text', 'note', 'list', 'button', 'image', 'cards', 'steps', 'faq', 'keep'] as const\n\nconst ITEM_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['title', 'text', 'to', 'icon', 'ref'],\n properties: {\n title: { type: 'string' },\n text: { type: 'string' },\n to: { type: 'string' },\n icon: { type: 'string' },\n ref: { type: 'string' },\n },\n} as const\n\nconst BLOCK_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'col', 'text', 'to', 'style', 'icon', 'items', 'ref'],\n properties: {\n kind: { type: 'string', enum: [...AI_SITE_IMPORT_IMPROVE_BLOCK_KINDS] },\n col: { type: 'integer' },\n text: { type: 'string' },\n to: { type: 'string' },\n style: { type: 'string', enum: [...AI_LAYOUT_STYLES, 'none'] },\n icon: { type: 'string' },\n items: { type: 'array', items: ITEM_SCHEMA },\n ref: { type: 'string' },\n },\n} as const\n\n/** The redesign tool: the `submit_page` language, a `keep` block, and a picture on an item by its ref. */\nexport const AI_SITE_IMPORT_IMPROVE_TOOL: AiTool = {\n name: 'submit_improved_page',\n description: 'Submit the redesigned page: its sections in order, in the layout language, each thing the page must keep placed with a keep block.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['sections'],\n properties: {\n sections: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['band', 'cols', 'align', 'blocks'],\n properties: {\n band: { type: 'string', enum: [...AI_LAYOUT_BANDS] },\n cols: { type: 'array', items: { type: 'integer' } },\n align: { type: 'string', enum: [...AI_LAYOUT_ALIGNS] },\n blocks: { type: 'array', items: BLOCK_SCHEMA },\n },\n },\n },\n },\n },\n}\n\n/** What a redesign is told, cached: every page of every site shares these bytes. */\nexport const AI_SITE_IMPORT_IMPROVE_TEXT = [\n \"You redesign one page of a small business's existing website the way a professional web designer and copywriter would, so the new page looks far better than the old one: polished, organized and inviting, never the old page restyled. The old page is usually plain: one column, flat grounds, a text link for a call to action, its sections in the order someone typed them. Plan the page again from what a visitor needs, in the order they need it, add the sections it lacks, and write every word. The platform turns your design into the page in the site's own theme, so never describe styling beyond the words below.\",\n '',\n 'Answer with submit_improved_page. A page is a list of sections, top to bottom, and you decide how many and what each one is. A section has:',\n '- band: plain (the page), soft (a set-apart ground), brand (the brand color) or dark.',\n '- cols: relative column widths for a row: [1, 1] for halves, [7, 5] for a wide and a narrow column, [1, 1, 1]; at most 4. [] for one column.',\n '- align: start or center. Center only a short section: an opening, a closing call to action, a heading over a group.',\n '- blocks: what it shows, top to bottom. A block with col 0 or more goes in that column of the row; col -1 spans the section, above the row when it comes first and below it when it comes last.',\n 'Every field is always written: a block that does not use one writes \"\" (text, to, icon, ref), \"none\" (style), -1 (col) or [] (items); an item that does not use one writes \"\".',\n '',\n 'Block kinds:',\n '- eyebrow: a short label over a heading. heading: the first heading of the first section is the page title; the first heading of any other section is its heading. lede: the larger sentence under a heading. text: a paragraph. note: small print.',\n '- button: text is its label, to where it goes, style primary (filled), secondary (outlined) or quiet. Two in a row read as a pair.',\n '- cards, steps, faq: a group of items, each a title and a text. cards are services, features or reasons; steps are numbered and in order; faq items are a question and its answer. An item may carry an icon, a to, and ref naming a picture of the page, shown on the card: a picture the ledger lists with lines goes on the card written of those lines, so like cards each show their own.',\n '- list: short lines, title only.',\n '- image: text describes a picture the page should have where none of its own fits; the platform finds one, or leaves it out.',\n '- keep: ref names one thing of the ledger, drawn exactly as the owner has it, so write nothing for it: a picture, form, plan, table, quote, video, contact line, figures, logos, a gallery of photos (drawn as a grid of them), tabs, or a group. Place every thing the ledger marks must, exactly once, wherever it serves the page best, in a column if that helps.',\n '- A group:n of the ledger is a set of like items the old page shows (its cards, steps, questions or list). keep it to draw it whole as the owner has it, with the pictures and links it holds; or write its items again as a group of your own, every link and fact of it kept. A page too long to show whole has its groups folded: each is shown by its titles, marked must, and kept whole, and you write only what is around them.',\n 'icon (on a block or an item) is one of: ' + AI_ICON_WORDS.join(', ') + '.',\n '',\n 'Where a link goes (to): page:<id> for a page the ledger names, #<n> for section n of this page, form for the form on this page, phone or email for the number or address the page gives, or an https: address the ledger lists. Every link the ledger lists must go somewhere on the page, as a button or an item.',\n '',\n \"A designer's page is made of sections like these; choose and order the ones this page needs:\",\n '- Hero: the page title, a lede, a filled primary button and a quieter second one, beside a picture (cols [7, 5]: the words in col 0, the picture in col 1) or with the picture behind the words (one column, the picture first). Every opening places a picture: the page\\'s own by keep, else an image block.',\n '- Offer as a card grid: a heading, a lede, then cards, one item for each service or thing offered, each with an icon; three or four across.',\n '- Figures or badges: figures the ledger holds, kept (keep stats:n); plain facts the page states, such as how long the business has run or that it is licensed, as cards of two to four items with icons, each saying the fact exactly as the page does.',\n '- How it works: a heading and steps of three or four items, from first asking to done.',\n '- Why choose it: cards of three with icons, each a reason the site supports.',\n '- A quote drawn as a quote: its own section on a soft or dark ground, centered: a short heading and the kept quote alone.',\n '- Pictures in a row: cols [1, 1, 1] or [1, 1], one picture kept in each column with a one-line caption under it; a gallery kept whole is its own grid, under a short heading. Pictures are never stacked one under another.',\n '- Words beside a picture: cols [1, 1] or [5, 7]: a heading, a lede, a paragraph and a button in one column and a picture in the other, the side alternating down the page.',\n '- Questions: a heading and a faq of three to six questions a visitor of this kind of business asks, each answered only with what the site says.',\n '- Contact: the kept form on a framed ground (a soft band, cols [5, 7]): beside it a heading, a welcoming line, the kept contact line and a call or email button.',\n '- Closing band: the last section, on a brand or dark ground, centered: a heading that says what the visitor gets, one line, and a filled primary button.',\n '',\n 'Plan it as a designer would:',\n '- Give the page the sections its role asks for. The request names its role and how many new sections it needs: a new section is one the old page has nowhere, such as how it works, why choose it or the questions people ask, written from what the site says and what this kind of business generally does.',\n '- Draw like things as a group: three or more services, reasons or steps are cards or steps, never headings and paragraphs one under another; a set of questions is a faq; two or three pictures are a row.',\n '- Vary it: no two neighboring sections share a shape or a ground. Alternate plain and soft, and keep brand and dark to one or two sections a page, usually the closing band.',\n '- Each heading says what the visitor gets, in a few specific words; never \"Welcome\", \"Our services\" or \"Ready when you are\" alone.',\n '- Put the phone or email the page gives on a button (to phone, to email) where a visitor would call or write, beside the kept contact line.',\n '',\n \"Writing: plain, specific and in the owner's voice, each heading a clear promise, each paragraph leading with the benefit, nothing that does not earn its place. Headings and card titles are in sentence case, so a capital reads as a name. Say what the page says, in stronger words, keeping every fact it gives; and you may say what this kind of business generally does.\",\n 'Never write a name, number, price, date, testimonial, client, award, credential, address or guarantee the page or the site does not give. A fact you do not have is left out, never a gap or a placeholder. Say a figure, a price, a phone or a name exactly as the page does.',\n].join('\\n')\n\n/** The site's own digest, which every page of one import reads ahead of its ledger: cached once per site. */\nexport function aiSiteImportImproveDigest(input: {\n siteName: string | null\n /** What the home page says of the site, and the pages of the import. */\n scope: readonly string[]\n plan?: AiSiteImportPlan | null\n}): string {\n return [\n fenceUntrustedText(\"What the owner's site says of itself\", [clean(input.siteName), ...input.scope].filter(Boolean).join('\\n'), { maxChars: AI_SITE_IMPORT_IMPROVE_DIGEST_CHARS }),\n ...(input.plan ? [fenceUntrustedText('The plan every page of this site is drawn to', JSON.stringify(input.plan), { maxChars: 4_000 })] : []),\n ].join('\\n')\n}\n\n/** The most of a site's own words the digest holds. */\nexport const AI_SITE_IMPORT_IMPROVE_DIGEST_CHARS = 16_000\n\n/** A redesign's system blocks: the platform's text cached across sites, then this site's digest, cached once per site. The ledger rides the user turn. */\nexport function aiSiteImportImproveInstructions(digest: string): readonly AiSystemBlock[] {\n return [\n { text: AI_SITE_IMPORT_IMPROVE_TEXT, cacheBreakpoint: true },\n { text: UNTRUSTED_TEXT_RULE },\n { text: digest, cacheBreakpoint: true, site: true },\n ]\n}\n\n/*------------------------------------------\n * The ledger as the answer reads it\n *-----------------------------------------*/\n\n/** The most characters a page's ledger shows. */\nexport const AI_SITE_IMPORT_LEDGER_MAX_CHARS = 16_000\n\nconst textOf = (block: SiteImportBlock | undefined): string => (block && block.kind !== 'image' ? clean(block.text) : '')\n\nconst short = (text: string, most = 80) => (text.length > most ? `${text.slice(0, most - 1)}…` : text)\n\n/**\n * The lines each picture of a page stands with (AGL-4152): the words after it\n * in its section, up to the next picture, as a row of pictured services or a\n * photo over its caption lays them out. What the ledger tells a redesign a\n * picture goes with, and what a card written of those words is given it by.\n */\nexport function aiSiteImportPictureCaptions(ledger: Pick<SiteImportLedger, 'items' | 'lines'>): Map<string, SiteImportLedgerLine[]> {\n const pictures = ledger.items.filter((item) => item.kind === 'picture' && item.lines[0] !== undefined)\n const out = new Map<string, SiteImportLedgerLine[]>()\n for (const item of pictures) {\n const at = item.lines[0] as number\n const next = Math.min(...pictures.filter((other) => other.section === item.section && (other.lines[0] as number) > at).map((other) => other.lines[0] as number), Number.POSITIVE_INFINITY)\n const lines = ledger.lines.filter((line) => line.section === item.section && line.line > at && line.line < next && !line.group).slice(0, 2)\n if (lines.length) out.set(item.ref, lines)\n }\n return out\n}\n\n/** A ledger item, in a few words: what it is and what it shows. */\nfunction shownItem(item: SiteImportLedgerItem, doc: Pick<AiSiteImportDocument, 'blocks' | 'photos'>, captions?: ReadonlyMap<string, SiteImportLedgerLine[]>): string {\n const must = item.must ? ' must' : ''\n const words = item.lines.map((ref) => textOf(doc.blocks[ref])).filter(Boolean)\n switch (item.kind) {\n case 'picture': {\n const block = doc.blocks[item.lines[0] as number]\n const url = block?.kind === 'image' ? block.url : ''\n const photo = doc.photos.find((entry) => entry.from === url)\n const alt = block?.kind === 'image' ? clean(block.alt) : ''\n // The words it stands with, by their numbers: a card written of them takes it by its ref (AGL-4152).\n const with_ = captions?.get(item.ref)?.map((line) => `[${line.line}]`).join(', ')\n return `${item.ref}${must} (${photo?.width && photo.height ? `${photo.width}×${photo.height}, ` : ''}\"${short(alt, 60)}\"${with_ ? `, with ${with_}` : ''})`\n }\n case 'form':\n return `${item.ref}${must} (a form)`\n case 'video':\n return `${item.ref}${must} (a film)`\n case 'plan':\n return `${item.ref}${must} (${item.node?.kind === 'group' ? item.node.items.length : 0} plans: ${short(words.slice(0, 6).join(', '), 120)})`\n case 'table':\n return `${item.ref}${must} (${item.node?.kind === 'table' ? item.node.rows.length : 0} rows: ${short(words.slice(0, 6).join(', '), 120)})`\n case 'stats':\n return `${item.ref}${must} (figures: ${short(words.join(', '), 120)})`\n case 'logos':\n return `${item.ref}${must} (a strip of logos)`\n case 'gallery': {\n const node = item.node?.kind === 'group' ? item.node : null\n const alts = item.lines.flatMap((ref) => {\n const entry = doc.blocks[ref]\n return entry?.kind === 'image' && clean(entry.alt) ? [`\"${short(clean(entry.alt), 40)}\"`] : []\n })\n return `${item.ref}${must} (a gallery of ${node?.items.length ?? 0} photos, drawn as a grid${node?.columns ? ` ${node.columns} across` : ''}${alts.length ? `: ${alts.slice(0, 4).join(', ')}${alts.length > 4 ? ', …' : ''}` : ''})`\n }\n case 'tabs':\n return `${item.ref}${must} (tabs: ${short(words.slice(0, 4).join(', '), 120)})`\n case 'group': {\n const node = item.node?.kind === 'group' ? item.node : null\n // Each item by its first line that says something in words: a step's number is no title.\n const titles = (node?.items ?? []).map((entry) => textOf(doc.blocks[entry.lines.find((ref) => /\\p{L}/u.test(textOf(doc.blocks[ref]))) as number])).filter(Boolean)\n const linked = (node?.items ?? []).filter((entry) => entry.to || entry.lines.some((ref) => doc.blocks[ref]?.kind === 'link')).length\n const kind = node?.group === 'text' || !node ? 'like items' : node.group\n const shown = titles.slice(0, item.folded ? 16 : 6).map((title) => `\"${short(title, 40)}\"`).join(', ')\n return `${item.ref}${must} (${node?.items.length ?? 0} ${kind}${linked ? `, ${linked} linked` : ''}: ${shown}${titles.length > (item.folded ? 16 : 6) ? ', …' : ''}${item.holds?.length ? `; holds ${item.holds.join(', ')}` : ''})`\n }\n default:\n return `${item.ref}${must} (${short(words.join(' '), 160)})`\n }\n}\n\n/**\n * A page's ledger as its answer reads it (AGL-4152): what it may place, where\n * each link goes, and every line it rewrites, numbered. Uncached, per page, and\n * fenced by the prompt: every word of it is the owner's.\n */\nexport function aiSiteImportLedgerText(ledger: SiteImportLedger, doc: Pick<AiSiteImportDocument, 'blocks' | 'photos'>, destinations: ReadonlyMap<string, string>): string {\n // A link a folded group holds goes where it went by its keep: it is not listed again.\n const folded = new Set(ledger.items.flatMap((item) => (item.folded ? item.lines : [])))\n const links = ledger.links.flatMap((link) => {\n const to = destinations.get(link.ref)\n return to && !folded.has(link.line) ? [`${link.ref} → ${to} (\"${short(link.text, 60)}\")`] : []\n })\n // A long page shows each group by its titles alone, kept whole: what is around them is written (AGL-4152).\n const lines = ledger.folded ? ledger.lines.filter((line) => !line.group) : ledger.lines\n const captions = aiSiteImportPictureCaptions(ledger)\n return [\n ...(ledger.folded ? ['This page is long: its groups are folded, each shown by its titles and kept whole with keep.'] : []),\n 'Things to place with keep, each once; \"must\" may not be left out:',\n ...(ledger.items.length ? ledger.items.map((item) => shownItem(item, doc, captions)) : ['(none)']),\n '',\n 'Links that must go somewhere on the page:',\n ...(links.length ? links : ['(none)']),\n '',\n 'The lines of the old page, by section, which you rewrite as the page needs:',\n ...lines.map((line) => `[${line.line}] section ${line.section + 1}, ${line.kind}${line.group && !ledger.folded ? ` in ${line.group}` : ''}: ${line.text}`),\n ].join('\\n')\n}\n\n/** Everywhere a link may go on this page, as an answer writes it, each with the destination it means. */\nexport function aiSiteImportImproveDestinations(doc: AiSiteImportDocument, ledger: SiteImportLedger, input: { sections?: number; formSection?: number | null } = {}): Map<string, string> {\n const scope = { doc, pathTo: new Map(doc.links.map((link) => [link.path.replace(/\\/+$/, '') || '/', link.id])) }\n const out = new Map<string, string>()\n for (const link of ledger.links) {\n const to = aiSiteImportLinkTo(scope, link.href)\n if (to) {\n out.set(link.ref, to)\n out.set(to, to)\n }\n }\n for (const page of doc.links) out.set(`page:${page.id}`, `page:${page.id}`)\n // A new page has no contact line of its own: it may send a visitor to what the site gives (AGL-4152).\n const text = [...doc.blocks.map((block) => (block.kind === 'image' ? '' : block.text)), ...(doc.proposed ? (doc.siteLines ?? []) : [])].join(' \\n ')\n const phone = /(?:\\+\\d{1,3}[\\s.-]?)?(?:\\(\\d{2,4}\\)[\\s.-]?)?\\d{2,4}[\\s.-]\\d{3,4}(?:[\\s.-]\\d{2,4})?/.exec(text)?.[0]\n if (phone && phone.replace(/\\D/g, '').length >= 7) out.set('phone', `tel:${phone.replace(/[^\\d+]/g, '')}`)\n const email = /[\\p{L}\\p{N}._%+-]+@[\\p{L}\\p{N}-]+(?:\\.[\\p{L}\\p{N}-]+)+/u.exec(text)?.[0]\n if (email) out.set('email', `mailto:${email}`)\n for (const [key, to] of [...out]) if (key === 'phone' || key === 'email') out.set(to, to)\n if (input.formSection !== null && input.formSection !== undefined) out.set('form', `#${input.formSection + 1}`)\n else {\n // A page with no form of its own sends `form` to the site's page that holds one, as a link to that page goes (AGL-4152).\n const formPage = aiSiteImportFormPageOf(doc)\n if (formPage) out.set('form', formPage)\n }\n for (let n = 1; n <= (input.sections ?? 0); n += 1) out.set(`#${n}`, `#${n}`)\n return out\n}\n\n/**\n * The site's page that holds its form (AGL-4152), as `page:<id>`: the one the\n * plan's header button sends `form` to, else the one the import read a form\n * on. `null` where no page of the site holds one, where that page is not one a\n * link may go to, or where it is the page itself, which holds its form in place.\n */\nexport function aiSiteImportFormPageOf(doc: Pick<AiSiteImportDocument, 'plan' | 'formPage' | 'links' | 'url'>): string | null {\n const cta = doc.plan?.nav.primaryCta\n const id = (cta?.target === 'form' ? cta.page : undefined) ?? doc.formPage\n if (!id || !doc.links.some((page) => page.id === id)) return null\n const to = `page:${id}`\n return to === aiSiteImportOwnPage(doc) ? null : to\n}\n\n/**\n * The page's own `page:<id>` on the new site (AGL-4152), by its address: a\n * link to it from itself goes nowhere a visitor is not already. `null` where\n * the import plans it under no id, as the home page.\n */\nexport function aiSiteImportOwnPage(doc: Pick<AiSiteImportDocument, 'url' | 'links'>): string | null {\n let path: string\n try {\n path = new URL(doc.url).pathname.replace(/\\/+$/, '') || '/'\n } catch {\n return null\n }\n const own = doc.links.find((link) => link.path === path)\n return own ? `page:${own.id}` : null\n}\n\n/** A redesign's user turn: the page, its kind of site, how its opening is drawn, and its ledger, fenced as the owner's data. */\nexport function aiSiteImportImprovePrompt(input: {\n screen: { title: string; slug: string }\n doc: Pick<AiSiteImportDocument, 'url' | 'blocks' | 'photos' | 'proposed'>\n ledger: SiteImportLedger\n destinations: ReadonlyMap<string, string>\n kindLines: readonly string[]\n seed: string\n /** What the page is for and what it needs (`aiSiteImportImproveRoleLines`). */\n roleLines?: readonly string[]\n /** How much page its answer has room for, and whether it is thin (`aiSiteImportImproveSizeLines`). */\n sizeLines?: readonly string[]\n}): string {\n return [\n `Page: \"${input.screen.title}\" at ${input.screen.slug}`,\n // A page the site's plan proposed: there is no old page to keep, so it is written whole from what the site says.\n ...(input.doc.proposed ? ['This page is new: the site has no such page yet. Its one line says what it tells a visitor. Write it from what the site says of itself and what this kind of business generally does, inventing no fact.'] : []),\n ...(input.roleLines ?? []),\n ...(input.sizeLines ?? []),\n ...input.kindLines,\n \"The page's ledger, what it holds and where it links:\",\n fenceUntrustedText(`The owner's page ${input.doc.url}`, aiSiteImportLedgerText(input.ledger, input.doc, input.destinations), { maxChars: AI_SITE_IMPORT_LEDGER_MAX_CHARS }),\n `Design seed: ${input.seed}.`,\n ].join('\\n')\n}\n\n/*------------------------------------------\n * What the page is for, and what it needs\n *-----------------------------------------*/\n\n/**\n * How many new sections a page of each role is asked for (AGL-4152): a home\n * or a main service page two, a contact page none, its form framed instead,\n * and a gallery none: its pictures are what it is for, and a section added\n * to a page of photos only stands between a visitor and them.\n */\nexport const AI_SITE_IMPORT_NEW_SECTIONS: Readonly<Record<AiSiteImportPageRole, number>> = {\n home: 2,\n service: 2,\n about: 1,\n gallery: 0,\n pricing: 1,\n other: 1,\n contact: 0,\n faq: 0,\n}\n\n/**\n * The share of the old page's words a redesign keeps, by role (AGL-4152),\n * where it is not `SITE_IMPORT_IMPROVED_MEANING`. A contact page is asked for\n * a short, welcoming opening over its form: what it must keep is its form,\n * its contact lines and its facts, each held whole on their own lines, and its\n * intent, so its prose is held only at the floor a rewritten line is.\n */\nexport const AI_SITE_IMPORT_ROLE_MEANING: Readonly<Partial<Record<AiSiteImportPageRole, number>>> = { contact: SITE_IMPORT_MEANING_FLOOR }\n\n/** The share of its old words a page of a role keeps. */\nexport function aiSiteImportMeaningShare(role: AiSiteImportPageRole): number {\n return AI_SITE_IMPORT_ROLE_MEANING[role] ?? SITE_IMPORT_IMPROVED_MEANING\n}\n\n/** The fewest content words an old section says for a new one to be its rework (AGL-4152): fewer is a label, which any section may echo. */\nexport const AI_SITE_IMPORT_REWORK_LEAST_WORDS = 4\n\n/** The most sections a redesigned page runs to: a page the source already fills has no room for more. */\nexport const AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS = 10\n\n/** What a page is for, as its plan says, else from its address and what it holds. */\nexport function aiSiteImportPageRoleOf(doc: Pick<AiSiteImportDocument, 'role' | 'proposed' | 'url' | 'title' | 'blocks' | 'forms' | 'layout'>, slug: string): AiSiteImportPageRole {\n if (doc.role) return doc.role\n if (slug === '/' || slug === '') return 'home'\n const words = `${slug} ${doc.title}`.toLowerCase()\n if (/\\b(?:faq|faqs|questions)\\b/.test(words)) return 'faq'\n if (/\\b(?:contact|visit|find-us|location|book|booking|estimate|quote)\\b/.test(words)) return 'contact'\n if (/\\b(?:about|story|team|people)\\b/.test(words)) return 'about'\n if (/\\b(?:pricing|prices|rates|plans)\\b/.test(words)) return 'pricing'\n if (/\\b(?:gallery|portfolio|projects|work)\\b/.test(words)) return 'gallery'\n if (doc.proposed) return 'other'\n return 'service'\n}\n\n/** How many new sections a page is asked for: its role's, where the page has room, and none on a long page, whose groups fold. */\nexport function aiSiteImportNewSectionsWanted(role: AiSiteImportPageRole, ledger: Pick<SiteImportLedger, 'folded' | 'lines' | 'items'>, proposed = false): number {\n if (proposed || ledger.folded) return 0\n const sections = new Set([...ledger.lines.map((line) => line.section), ...ledger.items.map((item) => item.section)]).size\n return Math.max(0, Math.min(AI_SITE_IMPORT_NEW_SECTIONS[role], AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS - 1 - sections))\n}\n\n/** What each role's page tells, in the order a designer would tell it. */\nconst ROLE_PLAN: Readonly<Record<AiSiteImportPageRole, string>> = {\n home: 'the front door of the site: the hero, what the business offers, why choose it, how it works, the questions people ask, and the closing band',\n service: 'what the service is: the hero, what is included as cards, how it works as steps, why choose it, the questions people ask about it, and the closing band',\n about: 'the story and the people: the hero, the story beside a picture, what the business values or why choose it as cards, a kept quote where the ledger has one, and the closing band',\n contact: 'how to reach the business: a short, welcoming opening, the form on a framed ground beside how to reach it, what happens after a visitor writes where the site says so, and no closing band',\n gallery: 'the work in pictures: the hero, the pictures in rows with short captions, what the work is, and the closing band',\n pricing: 'the prices, exactly as kept: the hero, the plans or table kept whole, what is included, the questions people ask about paying, and the closing band',\n faq: 'the questions: a short opening, the questions as a faq, and the closing band',\n other: 'what the page is for: the hero, its content drawn as groups and pictures, and the closing band',\n}\n\n/** The lines a redesign's request says of its page's role and what it needs (AGL-4152). */\nexport function aiSiteImportImproveRoleLines(input: { role: AiSiteImportPageRole; wanted: number; folded: boolean; kind?: string | null; seed: number }): string[] {\n const { role, wanted } = input\n // A home tells its story as a site start's does (`ai-site-home-arcs.ts`), one of its kind's arcs by the job's seed.\n const arc = role === 'home' ? aiSiteHomeArc({ kind: input.kind ?? null, seed: input.seed }) : null\n return [\n `This page's role: ${role}, ${ROLE_PLAN[role]}.`,\n ...(arc ? [`This home tells its story in this order, after the hero: ${arc.sections.map((section) => section.words).join('; ')}. Where it says the brief, read what the site says. Fold the old page's sections into these, and keep the order.`] : []),\n wanted ? `It needs at least ${wanted} new ${wanted === 1 ? 'section' : 'sections'}: ${wanted === 1 ? 'one' : 'sections'} the old page has nowhere, for this role.` : input.folded ? 'It is long: plan its order and its grounds, keep its groups whole, and add nothing it does not need.' : 'It needs no new section; organize and draw what it has.',\n ]\n}\n\n/**\n * The sections a redesign added (AGL-4152), by index: neither the opening nor\n * a closing band, holding nothing kept but a picture, saying something of\n * its own, and the rework of no section of the old page. Each section of the\n * old page past its opening is reworked by the one section that says most\n * of it; another section drawing on its words, such as a why-us of the\n * opening's facts, is new. An old section of a few words, a heading over a\n * band or a label over a kept group, reworks nothing: any new section that\n * happens to say its two or three words would otherwise read as its rework.\n */\nexport function aiSiteImportImproveNewSections(answer: readonly AiSiteImportImprovedSection[], ledger: Pick<SiteImportLedger, 'lines' | 'items'>): number[] {\n const kinds = new Map(ledger.items.map((item) => [item.ref, item.kind]))\n const sources = new Map<number, string[]>()\n for (const line of ledger.lines) sources.set(line.section, [...(sources.get(line.section) ?? []), line.text])\n const said = answer.map((section) =>\n section.blocks\n .flatMap((block) => (block.kind === 'keep' ? [] : [block.kind === 'image' ? '' : (block.text ?? ''), ...(block.items ?? []).flatMap((item) => [item.title, item.text])]))\n .join(' '),\n )\n const reworked = new Set<number>()\n // The old page's opening is the new page's: a section drawing on its facts, such as a why-us, is new.\n for (const [at, lines] of sources) {\n if (at === 0) continue\n const text = lines.join(' ')\n if (siteImportContentWords(text) < AI_SITE_IMPORT_REWORK_LEAST_WORDS) continue\n let best = -1\n let most = 0.5\n said.forEach((words, index) => {\n const kept = siteImportContentKept(text, words)\n if (kept >= most) {\n most = kept\n best = index\n }\n })\n if (best >= 0) reworked.add(best)\n }\n const last = answer.length - 1\n return answer.flatMap((section, index) => {\n if (index === 0 || reworked.has(index)) return []\n if (section.blocks.some((block) => block.kind === 'keep' && kinds.get(block.ref) !== 'picture')) return []\n const groups = section.blocks.filter((block) => block.kind !== 'keep' && (block.items?.length ?? 0) >= 2)\n const words = section.blocks.filter((block) => block.kind === 'text' || block.kind === 'lede')\n // A closing band: a heading, a line at most and a button, last.\n if (index === last && !groups.length && words.length <= 1 && section.blocks.some((block) => block.kind === 'button')) return []\n return groups.length || words.length ? [index] : []\n })\n}\n\n/** A section's shape, as a designer tells sections apart: what the variety of a page is counted in. */\nfunction shapeOf(section: AiSiteImportImprovedSection, kinds: ReadonlyMap<string, string>): string {\n const kept = section.blocks.flatMap((block) => (block.kind === 'keep' ? [kinds.get(block.ref) ?? ''] : []))\n const pictures = kept.filter((kind) => kind === 'picture').length + section.blocks.filter((block) => block.kind === 'image').length\n const group = section.blocks.find((block) => block.kind !== 'keep' && (block.items?.length ?? 0) >= 2)\n if (kept.includes('form')) return 'form'\n if (kept.includes('quote')) return 'quote'\n if (group) return group.kind\n const whole = kept.find((kind) => kind !== 'picture' && kind !== 'contact')\n if (whole) return whole\n if (pictures >= 2) return 'pictures'\n if (pictures && section.cols) return 'split'\n return section.blocks.some((block) => block.kind === 'button') && !section.blocks.some((block) => block.kind === 'text') ? 'band' : 'words'\n}\n\n/** What a redesign is asked to be, by its role (AGL-4152). */\nexport interface AiSiteImportImproveNeeds {\n role: AiSiteImportPageRole\n /** New sections it needs (`aiSiteImportNewSectionsWanted`). */\n wanted: number\n}\n\n/** The fewest shapes a page of four sections or more is drawn in. */\nexport const AI_SITE_IMPORT_IMPROVE_LEAST_SHAPES = 3\n\n/** Roles whose opening holds a picture. */\nconst PICTURED_OPENINGS: ReadonlySet<AiSiteImportPageRole> = new Set(['home', 'service', 'about', 'gallery', 'other'])\n\n/**\n * Whether a redesign is planned as a designer's page (AGL-4152), answer by\n * answer: the new sections its role asks for, a picture in its opening, and\n * sections drawn in more than one or two shapes. Each miss is named for the\n * one re-ask.\n */\nexport function aiSiteImportImprovePlanMisses(answer: readonly AiSiteImportImprovedSection[], input: { ledger: Pick<SiteImportLedger, 'lines' | 'items' | 'folded'>; needs: AiSiteImportImproveNeeds }): AiDoctrineViolation[] {\n const out: AiDoctrineViolation[] = []\n const added = aiSiteImportImproveNewSections(answer, input.ledger)\n if (added.length < input.needs.wanted) {\n out.push({\n rule: null,\n code: 'improve-new-sections',\n message: `The page adds ${added.length} new ${added.length === 1 ? 'section' : 'sections'}; as a ${input.needs.role} page it needs at least ${input.needs.wanted}: sections the old page has nowhere, such as how it works as steps, why choose it as cards, or the questions people ask as a faq, written from what the site says.`,\n })\n }\n const opening = answer[0]?.blocks ?? []\n if (PICTURED_OPENINGS.has(input.needs.role) && !opening.some((block) => block.kind === 'image' || (block.kind === 'keep' && block.ref.startsWith('picture:')))) {\n out.push({ rule: null, code: 'improve-opening', message: \"The opening has no picture. Place the page's own picture there with keep, or an image block, beside the words or behind them.\" })\n }\n const kinds = new Map(input.ledger.items.map((item) => [item.ref, item.kind as string]))\n const shapes = new Set(answer.slice(1).map((section) => shapeOf(section, kinds)))\n if (answer.length >= 4 && shapes.size < AI_SITE_IMPORT_IMPROVE_LEAST_SHAPES) {\n out.push({ rule: null, code: 'improve-shapes', message: `The sections after the opening are drawn in ${shapes.size === 1 ? 'one shape' : `${shapes.size} shapes`}. Vary them: a card grid, steps, words beside a picture, a row of pictures, a faq, a quote on its own ground, a closing band.` })\n }\n return out\n}\n\n/*------------------------------------------\n * The answer read\n *-----------------------------------------*/\n\n/** A redesign's answer, read by position: `null` where it gave no section it can draw. */\nexport function aiReadImprovedPage(raw: unknown, settled: AiLayoutSettlement[] = []): AiSiteImportImprovedSection[] | null {\n const given = raw && typeof raw === 'object' && Array.isArray((raw as Record<string, unknown>)['sections']) ? ((raw as Record<string, unknown>)['sections'] as unknown[]) : null\n if (!given) return null\n const sections: AiSiteImportImprovedSection[] = []\n given.forEach((entry, index) => {\n const section = entry && typeof entry === 'object' ? (entry as Record<string, unknown>) : null\n if (!section) return\n const cols = Array.isArray(section['cols']) ? section['cols'].filter((value): value is number => typeof value === 'number' && Number.isFinite(value) && value > 0).slice(0, AI_LAYOUT_MAX_COLS).map((value) => Math.min(12, Math.max(1, Math.round(value)))) : []\n const blocks: AiSiteImportImprovedBlock[] = []\n ;(Array.isArray(section['blocks']) ? section['blocks'] : []).forEach((raw: unknown, position: number) => {\n const entry = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null\n if (!entry) return\n const col = typeof entry['col'] === 'number' && Number.isInteger(entry['col']) && entry['col'] >= 0 && cols.length >= 2 ? Math.min(entry['col'], cols.length - 1) : undefined\n if (entry['kind'] === 'keep') {\n const ref = clean(entry['ref'])\n if (ref) blocks.push({ kind: 'keep', ref, ...(col !== undefined ? { col } : {}) })\n return\n }\n const block = aiReadLayoutBlock(entry, `sections[${index}].blocks[${position}]`, settled, { mostItems: AI_SITE_IMPORT_IMPROVE_MAX_ITEMS })\n if (!block) return\n const { col: _col, ...rest } = block\n blocks.push({ ...rest, ...(col !== undefined ? { col } : {}) })\n })\n if (!blocks.length) return\n const band = AI_LAYOUT_BANDS.find((value) => value === section['band'])\n const align = AI_LAYOUT_ALIGNS.find((value) => value === section['align'])\n sections.push({ ...(band ? { band } : {}), ...(cols.length >= 2 ? { cols } : {}), ...(align ? { align } : {}), blocks })\n })\n return sections.length ? sections : null\n}\n\n/*------------------------------------------\n * The answer in the compiler's language\n *-----------------------------------------*/\n\n/** The least width over height of an opening photo a redesign lays its words over (AGL-4152): a landscape, not a square or a portrait. */\nexport const AI_SITE_IMPORT_COVER_LEAST_RATIO = 1.3\n\n/** The heroes that box their photo under the words: a masthead's and an editorial's. */\nconst BOXED_HEROES: ReadonlySet<AiLayoutHeroVariant> = new Set(['column', 'editorial'])\n\n/** The heroes that lay their photo edge to edge behind the words, which a square or a portrait cannot fill. */\nconst COVERING_HEROES: ReadonlySet<AiLayoutHeroVariant> = new Set(['cover', 'poster', 'panel'])\n\n/**\n * The site's hero as a page brought in draws it: a collage or a portrait holds\n * what a page brought in does not. A redesign whose opening holds the page's\n * own landscape photo lays its words over it (AGL-4152): a hero that boxes a\n * wide photo under centered words reads as a picture pasted below a heading,\n * the way an old page looks, never as a brand's opening.\n */\nexport function aiSiteImportImproveHero(design: AiLayoutDesign, plan?: AiSiteImportPlan | null, opening?: { ratio?: number } | null): AiLayoutImportHero {\n const chosen = (plan?.design.hero as AiLayoutHeroVariant | undefined) ?? aiLayoutDesignChoices(design).hero\n const ratio = opening?.ratio ?? 0\n if (BOXED_HEROES.has(chosen) && ratio >= AI_SITE_IMPORT_COVER_LEAST_RATIO) return 'cover'\n // A square or a portrait is never stretched behind the words (AGL-4152): it sits beside them.\n if (COVERING_HEROES.has(chosen) && ratio > 0 && ratio < AI_SITE_IMPORT_COVER_LEAST_RATIO) return 'split'\n return chosen === 'collage' || chosen === 'portrait' ? 'split' : chosen\n}\n\n/** How many of a group's items sit across: planned for how much each says. */\nexport function aiSiteImportImproveColumns(items: readonly AiLayoutItem[]): number {\n const count = items.length\n if (count <= 3) return count\n const longest = Math.max(...items.map((item) => item.text.length))\n if (count === 4) return longest > 110 ? 2 : 4\n return 3\n}\n\nconst WORD_KINDS = new Set(['eyebrow', 'heading', 'lede', 'text', 'note', 'button'])\n\n/** The longest quote a kept set of quotes sets side by side. */\nconst QUOTE_ACROSS_CHARS = 220\n\n/**\n * The height a source's picture is cropped to where a redesign places it on\n * its own, in px (AGL-4152): wide across the page, closer in a column. A\n * height, not a shape: the Image takes it as its own height field, so a page\n * of pictures kept one by one repeats one style key on each (its rounding),\n * never two, which rule 16 refuses as a repeated inline style. Pictures side\n * by side in a row are cropped alike, whatever shapes they came in.\n */\nexport const AI_SITE_IMPORT_IMPROVE_FRAME_PX: Readonly<Record<'wide' | 'column', number>> = { wide: 420, column: 300 }\n\n/** The shape a picture on a card is cropped to (AGL-4152): every card of a row alike. */\nconst CARD_FRAME = '4 / 3'\n\nexport interface AiSiteImportImproveCompileInput {\n doc: AiSiteImportDocument\n ledger: SiteImportLedger\n design: AiLayoutDesign\n destinations: ReadonlyMap<string, string>\n formId: string | null\n plan?: AiSiteImportPlan | null\n /** The theme the page is drawn in, where it is known: a brand band only where the brand itself fills. */\n theme?: SiteImportFidelityTheme | null\n}\n\n/** The least share of a picture's own words a card says for the card to take that picture (AGL-4152). */\nconst CARD_PICTURE_KEPT = 0.5\n\n/**\n * The source's own pictures each set of written cards takes (AGL-4152), by\n * block: where an answer wrote like services as cards and gave none of them a\n * picture, while the page's photos of those same services sit unplaced, each\n * card takes the photo whose words it says. Every card must find one, or the\n * set takes none: a grid of cards half of which show a photo reads as broken.\n * Where no card says a photo's words but the one section's unplaced photos\n * number exactly the cards, they are taken in order, as the source laid them.\n */\nexport function aiSiteImportCardPictures(answer: readonly AiSiteImportImprovedSection[], ledger: Pick<SiteImportLedger, 'items' | 'lines'>): Map<AiSiteImportImprovedBlock, string[]> {\n const placed = new Set(aiSiteImportImprovedPlaced(answer, ledger))\n const captions = aiSiteImportPictureCaptions(ledger)\n const taken = new Set<string>()\n const out = new Map<AiSiteImportImprovedBlock, string[]>()\n for (const section of answer) {\n for (const block of section.blocks) {\n if (block.kind !== 'cards') continue\n const items = block.items ?? []\n if (items.length < 2 || items.some((item) => item.ref)) continue\n const pool = ledger.items.filter((item) => item.kind === 'picture' && !placed.has(item.ref) && !taken.has(item.ref))\n if (pool.length < items.length) continue\n const said = (ref: string) => (captions.get(ref) ?? []).map((line) => line.text)\n const chosen: string[] = []\n for (const item of items) {\n const words = `${item.title} ${item.text}`\n let best: string | null = null\n let most = CARD_PICTURE_KEPT\n for (const picture of pool) {\n if (chosen.includes(picture.ref)) continue\n const lines = said(picture.ref)\n if (!lines.length) continue\n const kept = Math.max(siteImportContentKept(lines[0] as string, words), siteImportContentKept(lines.join(' '), words))\n if (kept >= most) {\n most = kept\n best = picture.ref\n }\n }\n if (!best) break\n chosen.push(best)\n }\n const sections = new Set(pool.map((picture) => picture.section))\n const refs = chosen.length === items.length ? chosen : !chosen.length && sections.size === 1 && pool.length === items.length ? pool.map((picture) => picture.ref) : null\n if (!refs) continue\n for (const ref of refs) taken.add(ref)\n out.set(block, refs)\n }\n }\n return out\n}\n\n/** What a redesign compiles into, and what its row and its check say of it. */\nexport interface AiSiteImportImprovedPage {\n given: AiSiteImportDesigned\n names: string[]\n written: string[]\n added: AiSiteImportAddedSection[]\n pictures: AiSiteImportPagePictures\n}\n\n/** The sections' names: each heading's words, as a label, told apart. */\nfunction sectionNames(sections: readonly AiLayoutSection[], title: string): string[] {\n const taken = new Set<string>()\n return sections.map((section, index) => {\n const heading = section.blocks.find((block) => block.kind === 'heading' && block.text)?.text\n const base = siteImportLabel(heading ?? '') || (index === 0 ? siteImportLabel(title) : '') || `Section ${index + 1}`\n let name = base\n for (let at = 2; taken.has(name.toLowerCase()); at += 1) name = `${base.slice(0, 50)} (${at})`\n taken.add(name.toLowerCase())\n return name\n })\n}\n\n/**\n * The opening of a redesign without a brand's mark for its photo (AGL-4152):\n * a picture the source names a logo, a badge or an icon, or whose pixels make\n * it a graphic (`aiSiteImportIsBrandMark`),\n * that the answer keeps in its first section takes the page's widest photo no\n * section placed instead, or, where it has none, is left out, and a row it\n * leaves a column empty in is drawn as one column. A client's logo the source\n * showed beside its words read, as a cover, as the page's own work.\n */\nexport function aiSiteImportOpeningPhoto(answer: readonly AiSiteImportImprovedSection[], input: { doc: Pick<AiSiteImportDocument, 'blocks' | 'photos'>; ledger: Pick<SiteImportLedger, 'items'> }): AiSiteImportImprovedSection[] {\n const [first, ...rest] = answer\n if (!first) return [...answer]\n const { doc, ledger } = input\n const items = new Map(ledger.items.map((item) => [item.ref, item]))\n const imageOf = (ref: string) => {\n const item = items.get(ref)\n const block = item?.kind === 'picture' ? doc.blocks[item.lines[0] as number] : undefined\n return block?.kind === 'image' ? block : null\n }\n const markAt = (ref: string) => {\n const image = imageOf(ref)\n return !!image && aiSiteImportImageIsMark(image, doc.photos)\n }\n const marks = new Set(first.blocks.filter((block) => block.kind === 'keep' && markAt(block.ref)))\n if (!marks.size) return [...answer]\n const placed = new Set(aiSiteImportImprovedPlaced(answer, ledger))\n const ratioOf = (ref: string) => {\n const url = imageOf(ref)?.url\n const photo = url ? doc.photos.find((entry) => entry.from === url) : undefined\n return photo?.width && photo.height ? photo.width / photo.height : 0\n }\n const spare = ledger.items.filter((item) => item.kind === 'picture' && !placed.has(item.ref) && !markAt(item.ref)).sort((a, b) => ratioOf(b.ref) - ratioOf(a.ref))\n let next = 0\n const blocks = first.blocks.flatMap((block) => {\n if (!marks.has(block) || block.kind !== 'keep') return [block]\n const instead = spare[next++]\n return instead ? [{ ...block, ref: instead.ref }] : []\n })\n // A row with a column left empty is no row.\n const cols = first.cols\n const emptied = !!cols && cols.some((_, col) => !blocks.some((block) => block.col === col))\n const opening: AiSiteImportImprovedSection = emptied\n ? { ...(first.band ? { band: first.band } : {}), ...(first.align ? { align: first.align } : {}), blocks: blocks.map(({ col: _col, ...block }) => block as AiSiteImportImprovedBlock) }\n : { ...first, blocks }\n return [opening, ...rest]\n}\n\n/** The sections a redesign holds, in the compiler's language: every `keep` expanded to the source's own blocks, every link resolved. */\nexport function aiSiteImportImprovedPage(given: readonly AiSiteImportImprovedSection[], input: AiSiteImportImproveCompileInput): AiSiteImportImprovedPage {\n const { doc, ledger, design, destinations } = input\n // A brand's mark is never the opening's photo (AGL-4152).\n const answer = aiSiteImportOpeningPhoto(given, { doc, ledger })\n const scope = aiSiteImportMapScope(doc, { formId: input.formId, finish: 'improve' })\n const items = new Map(ledger.items.map((item) => [item.ref, item]))\n const choices = aiLayoutDesignChoices(design)\n const written: string[] = []\n // A brand band in a brand the theme had to deepen would read as neither: dark holds its place.\n const deepened = !!input.theme && !!input.theme.button.fill && input.theme.button.fill !== input.theme.light.brand\n // A link to the page it is on, or to the section it sits in, goes nowhere (AGL-4152): to the page's form where it\n // keeps one, which is what a contact page's \"Request a quote\" means, else it is left out.\n const own = aiSiteImportOwnPage(doc)\n const resolve = (to: string | undefined, at: number): string | undefined => {\n if (!to) return undefined\n const resolved = destinations.get(to) ?? undefined\n if (!resolved || (resolved !== own && resolved !== `#${at + 1}`)) return resolved\n const form = destinations.get('form')\n return form && form !== `#${at + 1}` ? form : undefined\n }\n const say = (text: string | undefined) => {\n if (text?.trim()) written.push(clean(text))\n }\n const pictureOf = (ref: string, frame: { ratio: string } | { height: number }) => {\n const item = items.get(ref)\n if (item?.kind !== 'picture') return null\n const picture = aiSiteImportTakePicture(scope, item.lines[0])\n return picture ? { ...picture, fit: { ...frame, cropped: true as const, objectFit: 'cover' as const, rounded: true as const } } : null\n }\n // A few short quotes kept whole sit side by side, as a designer sets them, wherever the old page stacked them; in a column, one under another.\n const across = (block: AiLayoutBlock, inColumn: boolean): Partial<AiLayoutBlock> => {\n const items = block.items ?? []\n if (block.kind !== 'quotes' || inColumn || items.length < 2 || items.length > 4 || items.some((entry) => entry.title.length > QUOTE_ACROSS_CHARS)) return {}\n return { columns: Math.min(3, items.length) }\n }\n const keepOf = (ref: string, col: number | undefined): AiLayoutBlock[] => {\n const item = items.get(ref)\n if (!item) return []\n const placed = col !== undefined ? { col } : {}\n if (item.kind === 'picture') {\n const picture = pictureOf(ref, { height: col !== undefined ? AI_SITE_IMPORT_IMPROVE_FRAME_PX.column : AI_SITE_IMPORT_IMPROVE_FRAME_PX.wide })\n return picture ? [{ kind: 'image', picture, ...placed }] : []\n }\n if (!item.node) return []\n scope.answer = null\n scope.groupAt = 0\n return aiSiteImportNodeBlocks(scope, [item.node], { cols: null, allowed: false }).map((block) => ({ ...block, ...placed, ...across(block, col !== undefined) }))\n }\n // The source's pictures a written set of cards stands for, where the answer gave them none (AGL-4152).\n const carded = aiSiteImportCardPictures(answer, ledger)\n // The page's own photo an opening that asks for a picture takes (AGL-4152), and which of its things it was.\n const asked = new Set([...aiSiteImportImprovedPlaced(answer, ledger), ...[...carded.values()].flat()])\n const ownOpening = { ref: null as string | null, taken: false }\n const openingPicture = (): AiLayoutPicture | null => {\n if (ownOpening.taken) return null\n const ratioOf = (line: SiteImportLineRef | undefined) => {\n const image = line === undefined || scope.used.has(line) ? undefined : doc.blocks[line]\n if (image?.kind !== 'image' || aiSiteImportImageIsMark(image, scope.photos)) return 0\n const photo = scope.photos.get(image.url)\n return photo?.width && photo.height ? photo.width / photo.height : 0\n }\n const widest = (found: Array<{ ref: string | null; line: SiteImportLineRef | undefined }>) => found.filter((entry) => ratioOf(entry.line) > 0).sort((a, b) => ratioOf(b.line) - ratioOf(a.line))[0]\n // Its photo no section places; else one of a gallery it keeps, which shows the rest.\n const pick =\n widest(ledger.items.filter((item) => item.kind === 'picture' && !asked.has(item.ref)).map((item) => ({ ref: item.ref, line: item.lines[0] }))) ??\n widest(ledger.items.filter((item) => item.kind === 'gallery' && asked.has(item.ref)).flatMap((item) => item.lines.map((line) => ({ ref: null, line }))))\n const picture = pick ? aiSiteImportTakePicture(scope, pick.line) : null\n if (!picture) return null\n ownOpening.taken = true\n ownOpening.ref = pick?.ref ?? null\n return picture\n }\n const sections = answer.map((section, index): AiLayoutSection => {\n scope.at = `sections[${index}]`\n const words = section.blocks.flatMap((block) => (block.kind === 'heading' || block.kind === 'eyebrow' ? [block.text ?? ''] : [])).join(' ')\n const drawn = section.blocks.flatMap((raw): AiLayoutBlock[] => {\n if (raw.kind === 'keep') return keepOf(raw.ref, raw.col)\n const block = raw\n const placed = block.col !== undefined ? { col: block.col } : {}\n if (block.kind === 'image') {\n const { col: _col, ...rest } = block\n // An opening that asks for a picture shows the page's own where it has one (AGL-4152): a slot the\n // library fills is searched by words alone, and put a stranger's desk on a builder's gallery.\n const own = index === 0 && !block.picture?.src ? openingPicture() : null\n return [{ ...rest, ...(own ? { picture: own } : {}), ...placed }]\n }\n if (block.kind === 'text' || block.kind === 'lede' || block.kind === 'note') {\n say(block.text)\n return aiSiteImportTextParts(block.text ?? '').map((part) => ({ ...block, text: part }))\n }\n if (block.kind === 'heading' || block.kind === 'eyebrow') {\n say(block.text)\n return [block]\n }\n if (block.kind === 'button') {\n const to = resolve(block.to, index)\n // A button that goes nowhere a visitor is not already is no call to action: it is left out.\n if (block.to && !to) return []\n say(block.text)\n const { to: _asked, ...rest } = block\n return [{ ...rest, ...(to ? { to } : {}) }]\n }\n const groupItems = (block.items ?? []).map((item, at): AiLayoutItem => {\n say(item.title)\n say(item.text)\n const given = item.ref || carded.get(block)?.[at]\n const picture = given ? pictureOf(given, { ratio: CARD_FRAME }) : null\n const to = resolve(item.to, index)\n const { ref: _ref, to: _to, ...rest } = item\n return { ...rest, ...(block.kind === 'steps' ? { figure: String(at + 1) } : {}), ...(picture ? { picture } : {}), ...(to ? { to } : {}) }\n })\n if (block.kind === 'list') return [{ ...block, items: groupItems, columns: groupItems.length >= 6 ? 2 : 1 }]\n if (block.kind === 'faq') return [{ ...block, items: groupItems, columns: 1 }]\n const pictured = groupItems.every((item) => item.picture)\n const iconed = groupItems.every((item) => item.icon)\n const wanted = aiLayoutGroupVariant(design, choices, words)\n const variant = pictured ? (choices.group === 'cards' ? 'articles' : 'pictures') : wanted === 'icons' && !iconed ? 'cards' : wanted === 'menu' || wanted === 'pictures' || wanted === 'articles' ? 'cards' : wanted\n return [{ ...block, items: groupItems, columns: aiSiteImportImproveColumns(groupItems), variant }]\n })\n // Each call to action once, in its place (AGL-4152).\n const tidy = aiSiteImportSectionActions({ cols: section.cols, blocks: drawn }, input.plan?.nav.primaryCta?.label)\n const blocks = tidy.blocks\n const pictures = blocks.filter((block) => block.kind === 'image' || block.kind === 'video')\n const opens = index === 0 && pictures.length === 1 && blocks.every((block) => block.kind === 'image' || block.kind === 'video' || WORD_KINDS.has(block.kind))\n const opening = pictures[0]?.kind === 'image' ? (pictures[0].picture ?? null) : null\n const hero = opens ? aiSiteImportImproveHero(design, input.plan, opening) : null\n const band = section.band === 'brand' && deepened ? 'dark' : section.band\n return {\n ...(band ? { band } : {}),\n ...(section.align ? { align: section.align } : {}),\n // A hero draws its own columns, and frames its own picture.\n ...(tidy.cols && !hero ? { cols: tidy.cols } : {}),\n ...(hero ? { hero, blocks: blocks.map((block) => (block.kind === 'image' && block.picture ? { ...block, picture: { ...block.picture, fit: undefined } } : block)) } : { blocks }),\n }\n })\n const names = sectionNames(sections, doc.title)\n const added: AiSiteImportAddedSection[] = aiSiteImportImproveNewSections(answer, ledger).map((index) => {\n const group = sections[index]?.blocks.find((block) => block.items?.length)\n return { heading: names[index] as string, ...(group?.items?.length ? { items: group.items.length } : {}) }\n })\n const placed = new Set([...asked, ...(ownOpening.ref ? [ownOpening.ref] : [])])\n const allPictures = ledger.items.filter((item) => item.kind === 'picture')\n const unplaced = allPictures.filter((item) => !placed.has(item.ref)).flatMap((item) => {\n const block = doc.blocks[item.lines[0] as number]\n return block?.kind === 'image' ? [block.url] : []\n })\n return {\n given: { sections, used: scope.used, missing: scope.missing, settled: scope.settled },\n names,\n written,\n added,\n pictures: {\n // A gallery's photo the opening shows is the source's too.\n source: allPictures.length - unplaced.length + (ownOpening.taken && !ownOpening.ref ? 1 : 0),\n stock: 0,\n generated: 0,\n slots: sections.reduce((total, section) => total + section.blocks.filter((block) => block.kind === 'image' && !block.picture).length, 0),\n unplaced,\n },\n }\n}\n\n/*------------------------------------------\n * The check\n *-----------------------------------------*/\n\n/** The most an answer may ask for, whatever the page and the model: a whole page's design and words, with its thinking. */\nexport const AI_SITE_IMPORT_IMPROVE_MOST_TOKENS = 8_000\n\n/**\n * Room a page's ceiling keeps for its listing pass (AGL-4152): its p90 is 1,\n * and it runs a model only where the source left the listing empty.\n */\nexport const AI_SITE_IMPORT_LISTING_ROOM_CREDITS = 10\n\n/**\n * What a page's redesign may spend, its answer and its re-ask together\n * (AGL-4152): the page's ceiling, less its listing pass's room. Held in code\n * (`aiSiteImportImproveTokensWithin`): an answer asks no more than the\n * ceiling buys, and a re-ask it cannot pay for is not asked.\n */\nexport const AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS = AI_SITE_IMPORT_PAGE_CEILING_CREDITS - AI_SITE_IMPORT_LISTING_ROOM_CREDITS\n\n/**\n * Characters a token is counted at before a request is sent (AGL-4152). No\n * truthful count exists before sending: the adapter has no count call, and\n * nothing tells a page whether the platform's prefix is still in the cache.\n * So the request is priced at worst from its own bytes, every byte it sends\n * counted. Three is about what the provider counted on a real run: a\n * contractor's home was billed about 29 credits of input where this guess,\n * over every byte at the cache write's rate, says 29, and the same guess over\n * the instructions alone, at the five-minute rate, had said 16.\n */\nconst CHARS_PER_TOKEN = 3\n\n/**\n * The provider's own words that ride every request offering a tool, ahead of\n * the tools, in the cached prefix: its published count for the tool-use\n * prompt of recent models is under 350 tokens.\n */\nexport const AI_TOOL_USE_PROMPT_TOKENS = 350\n\nconst ZERO: AiUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }\n\nconst plus = (a: AiUsage, b: AiUsage): AiUsage => ({\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,\n cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,\n ...(a.cacheWriteHourTokens !== undefined || b.cacheWriteHourTokens !== undefined ? { cacheWriteHourTokens: (a.cacheWriteHourTokens ?? 0) + (b.cacheWriteHourTokens ?? 0) } : {}),\n})\n\nconst tokensOf = (chars: number) => Math.ceil(Math.max(0, chars) / CHARS_PER_TOKEN)\n\n/**\n * What a request reads before it is sent, at worst (AGL-4152): every byte of\n * it, as the provider bills it on a cold cache. The tools and the platform's\n * blocks up to its last shared marker are written to the cache at the\n * route's lifetime (at the hour, twice the input rate); the site's block\n * after them at five minutes; anything after the last marker, and the turn,\n * as input. `system` is the blocks as sent, the doctrine's own first\n * (`aiDoctrineSystemBlocks`), and `toolChars` the tool's definition.\n */\nexport function aiSiteImportImproveInputUsage(input: { system: readonly AiSystemBlock[]; toolChars: number; promptChars: number; hour?: boolean }): AiUsage {\n const shared = input.system.reduce((last, block, index) => (block.cacheBreakpoint && !block.site ? index : last), -1)\n const cached = input.system.reduce((last, block, index) => (block.cacheBreakpoint ? index : last), -1)\n let sharedChars = input.toolChars\n let siteChars = 0\n let uncachedChars = input.promptChars\n input.system.forEach((block, index) => {\n if (index <= shared) sharedChars += block.text.length\n else if (index <= cached) siteChars += block.text.length\n else uncachedChars += block.text.length\n })\n const sharedTokens = tokensOf(sharedChars) + AI_TOOL_USE_PROMPT_TOKENS\n return {\n ...ZERO,\n inputTokens: tokensOf(uncachedChars),\n cacheWriteTokens: sharedTokens + tokensOf(siteChars),\n ...(input.hour ? { cacheWriteHourTokens: sharedTokens } : {}),\n }\n}\n\n/** What a usage is billed in credits on a model, an hour-long cache write at its own rate, as the meter bills it. */\nexport function aiSiteImportImproveCredits(usage: AiUsage, model: string): number {\n return assistCreditsFromUsd(estimateAiBilledUsd(usage, model) + aiCacheWriteHourSurchargeUsd(usage, aiBilledRatesForModel(model)))\n}\n\n/**\n * The most output tokens a request may write (AGL-4152) with `spent` already\n * spent and `input` still to read, and stay inside `ceiling` credits; at\n * most `most`, and 0 where its reading alone would pass the ceiling.\n */\nexport function aiSiteImportImproveTokensWithin(input: { model: string; spent: AiUsage; input: AiUsage; ceiling?: number; most: number }): number {\n const ceiling = input.ceiling ?? AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS\n const before = plus(input.spent, input.input)\n const fits = (tokens: number) => aiSiteImportImproveCredits({ ...before, outputTokens: before.outputTokens + tokens }, input.model) <= ceiling\n if (!fits(0)) return 0\n let low = 0\n let high = Math.max(0, Math.floor(input.most))\n while (low < high) {\n const mid = Math.ceil((low + high) / 2)\n if (fits(mid)) low = mid\n else high = mid - 1\n }\n return low\n}\n\n/** The least share of the last answer's length a re-ask must have room for: less, and it would be cut off. */\nexport const AI_SITE_IMPORT_REASK_ROOM = 0.9\n\n/**\n * The least share of a cut-off answer's length its re-ask must have room for\n * (AGL-4152): the re-ask asks for a page about half as long\n * (`AI_SITE_IMPORT_IMPROVE_CUT_OFF_SMALLER`), so it needs room for that page,\n * not for the one that was cut off.\n */\nexport const AI_SITE_IMPORT_CUT_OFF_REASK_ROOM = 0.6\n\n/** The least room the re-ask of a page cut off is asked in: an opening, a group and a closing, with their words. */\nexport const AI_SITE_IMPORT_IMPROVE_LEAST_TOKENS = 1_200\n\n/** What the re-ask of a cut-off page is told makes it smaller (AGL-4152), in one sentence. */\nexport const AI_SITE_IMPORT_IMPROVE_CUT_OFF_SMALLER = \"Write a page about half as long as the one cut off: fewer sections, shorter copy, and each long group of the ledger kept whole with keep rather than written again.\"\n\n/** What a re-ask reads beyond its first request: the re-ask's own words naming what missed. */\nconst REASK_TOKENS = 600\n\n/**\n * What a re-ask reads (AGL-4152), from what its first request was billed:\n * its turn again with the re-ask's words, and everything the first request\n * read from the cache or wrote to it, now read from it. The re-ask is sent\n * seconds after its first request, inside the five minutes the shortest\n * entry lives, so its prefix is a read: pricing it as a second write starved\n * the re-ask of a long home whose first request wrote the cache of about 13\n * credits, some 900 tokens.\n */\nexport function aiSiteImportImproveReaskInput(spent: AiUsage): AiUsage {\n return { ...ZERO, inputTokens: spent.inputTokens + REASK_TOKENS, cacheReadTokens: spent.cacheReadTokens + spent.cacheWriteTokens }\n}\n\n/**\n * Whether a redesign's re-ask fits its page's ceiling (AGL-4152): the most\n * tokens it may ask, given what the first answer spent, or 0 where the room\n * left is under what the re-ask must write, and the page falls back with no\n * re-ask rather than pass its ceiling. A re-ask for a miss writes the page\n * again, at about its first length; a re-ask for a page cut off asks for one\n * about half as long, so it needs room for that.\n */\nexport function aiSiteImportImproveReaskTokens(input: { model: string; spent: AiUsage; lastOutput: number; cutOff?: boolean; most: number; ceiling?: number }): number {\n const room = aiSiteImportImproveTokensWithin({ model: input.model, spent: input.spent, input: aiSiteImportImproveReaskInput(input.spent), most: input.most, ...(input.ceiling !== undefined ? { ceiling: input.ceiling } : {}) })\n return room >= aiSiteImportImproveReaskNeeds(input.lastOutput, input.cutOff) ? room : 0\n}\n\n/** The least room a re-ask after an answer of `lastOutput` tokens must have (AGL-4152). */\nexport function aiSiteImportImproveReaskNeeds(lastOutput: number, cutOff = false): number {\n return cutOff ? Math.max(AI_SITE_IMPORT_IMPROVE_LEAST_TOKENS, Math.ceil(lastOutput * AI_SITE_IMPORT_CUT_OFF_REASK_ROOM)) : Math.ceil(lastOutput * AI_SITE_IMPORT_REASK_ROOM)\n}\n\n/*------------------------------------------\n * The room an answer is told it has\n *-----------------------------------------*/\n\n/**\n * The share of its room a page is planned to (AGL-4152): a model sizes its\n * answer in words and sections, not in tokens, so a quarter of the room is\n * held back for what it writes past them.\n */\nexport const AI_SITE_IMPORT_ROOM_SHARE = 0.75\n\n/** Tokens a section costs in the tool's shape before its words: its fields, three or four blocks', and a few items'. */\nexport const AI_SITE_IMPORT_SECTION_TOKENS = 160\n\n/** Tokens a word of copy costs, inside the answer's strings. */\nexport const AI_SITE_IMPORT_WORD_TOKENS = 1.4\n\n/** The words a section of a designed page usually says: what a section's share of a page's room is reckoned with. */\nconst SECTION_WORDS = 60\n\n/** The fewest sections a page is told it has room for: an opening, what it offers, a closing. */\nexport const AI_SITE_IMPORT_LEAST_SECTIONS = 3\n\n/** The least a page is planned to, where its room holds it (AGL-4152): six sections and about 450 words. */\nexport const AI_SITE_IMPORT_LEAST_PAGE_TOKENS = 1_600\n\n/** A page whose old lines say fewer words than this is thin (AGL-4152): it stays short, and pads nothing. */\nexport const AI_SITE_IMPORT_THIN_PAGE_WORDS = 150\n\n/** The most sections a thin page is planned to. */\nexport const AI_SITE_IMPORT_THIN_MOST_SECTIONS = 6\n\n/**\n * The share of the old page's own words, outside its groups, a page is told\n * it has room for at the least (AGL-4152): a redesign keeps\n * `SITE_IMPORT_IMPROVED_MEANING` of what the owner says, and a rewrite says\n * less than all of a line it keeps. A group is kept whole by keep, its words\n * with it, so it asks for none.\n */\nexport const AI_SITE_IMPORT_MEANING_WORDS_SHARE = 0.8\n\n/** How many words the old page says, over its lines. */\nexport function aiSiteImportLedgerWords(ledger: Pick<SiteImportLedger, 'lines'>): number {\n return ledger.lines.reduce((total, line) => total + (line.text.match(/[\\p{L}\\p{N}]+/gu)?.length ?? 0), 0)\n}\n\n/** What a page's first answer may write, and what it is planned to. */\nexport interface AiSiteImportImproveRoom {\n /** The most output tokens the first answer is asked at (`max_tokens`). */\n first: number\n /** What its input was priced at, before it is sent. */\n estimated: AiUsage\n /**\n * The size the page is planned to, in tokens: where the room holds it, one\n * whose answer and a full re-ask of it both fit the ceiling, so a miss can\n * still be mended; never under `AI_SITE_IMPORT_LEAST_PAGE_TOKENS`, or what\n * it must say to keep the owner's meaning, where the room holds that; and\n * never over `AI_SITE_IMPORT_ROOM_SHARE` of the room.\n */\n target: number\n /** The most sections, and about how many words, the page is told it has room for. */\n sections: number\n words: number\n /** The old page's words, where it is thin. */\n thin: number | null\n}\n\nconst fifty = (value: number) => Math.max(0, Math.floor(value / 50) * 50)\n\n/**\n * The room a page's redesign has (AGL-4152): its first answer's ceiling from\n * what the page's credit ceiling buys after its input, and the page it is\n * planned to inside it, in sections and words a model can plan by.\n */\nexport function aiSiteImportImproveRoom(input: {\n model: string\n spent: AiUsage\n system: readonly AiSystemBlock[]\n toolChars: number\n promptChars: number\n hour?: boolean\n most: number\n ledger: Pick<SiteImportLedger, 'lines'>\n /** A page the site's plan proposed: it has no old lines, and is never thin. */\n proposed?: boolean\n ceiling?: number\n}): AiSiteImportImproveRoom {\n const ceiling = input.ceiling ?? AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS\n const estimated = aiSiteImportImproveInputUsage({ system: input.system, toolChars: input.toolChars, promptChars: input.promptChars, ...(input.hour ? { hour: true } : {}) })\n const first = aiSiteImportImproveTokensWithin({ model: input.model, spent: input.spent, input: estimated, most: input.most, ceiling })\n // An answer and a re-ask of it at nine tenths of its length, both inside the ceiling.\n const both = aiSiteImportImproveTokensWithin({ model: input.model, spent: plus(input.spent, estimated), input: aiSiteImportImproveReaskInput(estimated), most: input.most * 2, ceiling })\n const mendable = Math.floor(both / (1 + AI_SITE_IMPORT_REASK_ROOM))\n const words = aiSiteImportLedgerWords(input.ledger)\n const thin = !input.proposed && words < AI_SITE_IMPORT_THIN_PAGE_WORDS ? words : null\n // What it must say to keep the owner's meaning, which no re-ask is worth falling short of (AGL-4152).\n const meaning = fifty(aiSiteImportLedgerWords({ lines: input.ledger.lines.filter((line) => !line.group) }) * AI_SITE_IMPORT_MEANING_WORDS_SHARE)\n const least = Math.max(AI_SITE_IMPORT_LEAST_PAGE_TOKENS, AI_SITE_IMPORT_THIN_MOST_SECTIONS * AI_SITE_IMPORT_SECTION_TOKENS + meaning * AI_SITE_IMPORT_WORD_TOKENS)\n const share = Math.floor(first * AI_SITE_IMPORT_ROOM_SHARE)\n const target = Math.min(share, Math.max(mendable, least))\n const most = thin === null ? AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS : AI_SITE_IMPORT_THIN_MOST_SECTIONS\n // As many sections as the room holds at a section's usual words, and fewer where the owner's meaning needs the words.\n const shaped = Math.floor(target / (AI_SITE_IMPORT_SECTION_TOKENS + SECTION_WORDS * AI_SITE_IMPORT_WORD_TOKENS))\n const meant = Math.floor((target - meaning * AI_SITE_IMPORT_WORD_TOKENS) / AI_SITE_IMPORT_SECTION_TOKENS)\n const sections = Math.min(most, Math.max(AI_SITE_IMPORT_LEAST_SECTIONS, Math.min(shaped, meant)))\n const room = fifty((target - sections * AI_SITE_IMPORT_SECTION_TOKENS) / AI_SITE_IMPORT_WORD_TOKENS)\n // A thin page says about four times what its owner did, with a line of its own for each new section.\n const said = thin === null ? room : Math.min(room, Math.max(200, fifty(thin * 4 + 150)))\n return { first, estimated, target, sections, words: Math.max(150, said), thin }\n}\n\n/**\n * The lines a page's request says of its size (AGL-4152), in plain words:\n * where its room is under the most an answer may ask, the sections and words\n * it has room for, so it plans a page that fits rather than being cut off;\n * and on a thin page, that it stays short and says no figure the site does\n * not. Never the platform's vocabulary: its numbers are no one's fact.\n */\nexport function aiSiteImportImproveSizeLines(room: AiSiteImportImproveRoom, input: { most: number; groups: boolean }): string[] {\n return [\n ...(room.first < input.most\n ? [\n `Length: write this page in at most ${room.sections} sections and about ${room.words} words in all, counting every heading, line, button and card; a longer answer is cut off and not used.${input.groups ? ' Keep a long group of the ledger whole with keep rather than writing its items again.' : ''}`,\n ]\n : []),\n ...(room.thin !== null\n ? ['This page says little, so it stays short: write what it says and what this kind of business generally does, and give a count, size, year or quantity only where the site states it, never one such work usually has.']\n : []),\n ]\n}\n\n/** What a redesign settled: the page built, what it added and what it shows. */\nexport interface AiSiteImportImproved<T> {\n built: T\n page: AiSiteImportImprovedPage\n /** The design lines it was taken with still missed, by code (`AI_SITE_IMPORT_IMPROVE_SOFT_CODES`): only where no re-ask was left. */\n missed?: string[]\n}\n\n/**\n * What a redesign may still miss when no re-ask is left and be taken all the\n * same (AGL-4152): how it is planned and drawn, never what it says or holds.\n * Each is asked for in the one re-ask where it can be paid for; past it, the\n * old layout redrawn is no better on any of them than the redesign, and worse\n * on every other, so a miss here is noted on the page's row, not fallen back\n * on. What it says, holds, links and reads as (facts, invented, held, links,\n * meaning, contrast, a phone's width) stays a fallback.\n */\nexport const AI_SITE_IMPORT_IMPROVE_SOFT_CODES: ReadonlySet<string> = new Set([\n 'improve-new-sections',\n 'improve-opening',\n 'improve-shapes',\n 'improve-cta',\n 'improve-rhythm',\n 'improve-columns',\n 'improve-framing',\n])\n\n/** The most reasons a page's record keeps of why its redesign missed (AGL-4152). */\nexport const AI_SITE_IMPORT_REDESIGN_WHY_MOST = 8\n\n/** The most characters one reason keeps: the line it names and what it says of it. */\nexport const AI_SITE_IMPORT_REDESIGN_WHY_CHARS = 300\n\n/**\n * Why a redesign missed, line by line (AGL-4152): each violation's code, its\n * message (which names the line it found, `section 1, block 2, \"…\"`) and its\n * detail, cut short, at most `AI_SITE_IMPORT_REDESIGN_WHY_MOST`. What the\n * page's log and its record say, so a miss can be read after the job, when\n * the answer itself is gone. For the job's record, never the owner's row.\n */\nexport function aiSiteImportRedesignWhy(violations: readonly AiDoctrineViolation[]): string[] {\n const out: string[] = []\n for (const violation of violations) {\n const said = clean(`${violation.code}: ${violation.message}${violation.detail ? ` ${violation.detail}` : ''}`)\n const line = said.length > AI_SITE_IMPORT_REDESIGN_WHY_CHARS ? `${said.slice(0, AI_SITE_IMPORT_REDESIGN_WHY_CHARS - 1)}…` : said\n if (!out.includes(line)) out.push(line)\n if (out.length >= AI_SITE_IMPORT_REDESIGN_WHY_MOST) break\n }\n return out\n}\n\n/** Whether every miss of an answer is one it may be taken with past its last re-ask. */\nexport function aiSiteImportImproveOnlySoft(violations: readonly AiDoctrineViolation[]): boolean {\n return violations.length > 0 && violations.every((violation) => AI_SITE_IMPORT_IMPROVE_SOFT_CODES.has(violation.code))\n}\n\n/**\n * The words of a site's plan (AGL-4152): what it says the site is and who it\n * is for, its menu's and footer's labels, its call to action and its proposed\n * page. A redesign is told the plan as its digest, and the plan's own words\n * were held to what the site says when it was made, so a redesign that\n * repeats them invents nothing.\n */\nexport function aiSiteImportPlanLines(plan: AiSiteImportPlan | null | undefined): string[] {\n if (!plan) return []\n return [\n plan.site.what,\n plan.site.audience,\n ...plan.nav.groups.map((group) => group.label),\n ...plan.nav.footer.map((group) => group.label),\n ...(plan.nav.primaryCta ? [plan.nav.primaryCta.label] : []),\n ...(plan.proposed ? [plan.proposed.title, plan.proposed.purpose] : []),\n ].filter((line): line is string => typeof line === 'string' && !!line.trim())\n}\n\n/** A web address's top-level part, which says nothing of a name. */\nconst TLD = /\\.(?:com|org|net|io|co|ai|app|dev|us|uk|ca|au|de|fr|info|biz|me|shop|store|site|online)(?:\\.[a-z]{2})?$/i\n\n/**\n * The ways a site's name is said (AGL-4152), where it is written as one run\n * of letters: a web address (\"RidgelineBuilders.com\") or a name run together.\n * Its address part dropped, its capitals and digits split (\"Ridgeline\n * Builders\"), a run of capitals on its own (\"ABC\" of \"ABCroofing\"), and a run\n * of small letters split into the words the site says elsewhere (\"roofing\n * site\" of \"roofingsite\"). A redesign that names the business as a visitor\n * would invents nothing.\n */\nexport function aiSiteImportNameVariants(name: string, said: ReadonlySet<string>): string[] {\n const text = clean(name)\n if (!text || /\\s/.test(text) || text.length < 4) return []\n const bare = text.replace(/^https?:\\/\\//i, '').replace(/^www\\./i, '').replace(/\\/.*$/, '').replace(TLD, '')\n // A run of small letters as the words the site says, longest first; itself where they do not make it up.\n const segment = (run: string): string[] => {\n if (run.length < 6 || said.has(run.toLowerCase())) return [run]\n const out: string[] = []\n let rest = run.toLowerCase()\n while (rest) {\n let found = ''\n for (let end = rest.length; end >= 3 && !found; end -= 1) if (said.has(rest.slice(0, end))) found = rest.slice(0, end)\n if (!found) return [run]\n out.push(found)\n rest = rest.slice(found.length)\n }\n return out\n }\n const words = bare\n .split(/[-_.]+|(?<=[a-z])(?=[A-Z])|(?<=[A-Za-z])(?=\\d)|(?<=\\d)(?=[A-Za-z])/)\n .filter(Boolean)\n .flatMap((part) => {\n // A run of capitals before small letters: \"ABCroofing\" is \"ABC\" and \"roofing\", \"ABCRoofing\" \"ABC\" and \"Roofing\".\n const lead = /^([A-Z]{2,})([a-z]+)$/.exec(part)\n if (!lead) return segment(part)\n const caps = lead[1] as string\n const tail = `${caps.slice(-1)}${lead[2] as string}`\n return said.has(tail.toLowerCase()) ? [caps.slice(0, -1), tail] : [caps, ...segment(lead[2] as string)]\n })\n const titled = words.map((word) => (/^[a-z]/.test(word) ? `${word[0]?.toUpperCase()}${word.slice(1)}` : word)).join(' ')\n return [...new Set([bare, titled])].filter((variant) => variant && variant !== text)\n}\n\n/** Every line a redesign's facts may come from: its page, what the site says of itself, its wave's other pages, its plan, its name. */\nexport function aiSiteImportImproveScope(doc: Pick<AiSiteImportDocument, 'blocks' | 'siteLines' | 'scope' | 'title'> & { plan?: AiSiteImportPlan | null }, siteName: string | null): string[] {\n const own = doc.blocks.flatMap((block) => (block.kind === 'image' ? (block.alt ? [block.alt] : []) : block.text ? [block.text] : []))\n const lines = [...own, ...(doc.siteLines ?? []), ...(doc.scope ?? []), ...aiSiteImportPlanLines(doc.plan), doc.title, ...(siteName ? [siteName] : [])].map(clean).filter(Boolean)\n // The site's name as a visitor says it, where it is written as an address or run together (AGL-4152).\n const said = new Set(lines.flatMap((line) => line.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? []))\n const names = [...new Set([...(siteName ? [siteName] : []), ...(doc.siteLines ?? []).slice(0, 6)])]\n const variants = names.flatMap((name) => aiSiteImportNameVariants(name, said)).filter((variant) => !lines.includes(variant))\n return [...lines, ...variants]\n}\n\n/** What each line that missed says to the one re-ask. */\nconst MISS: Readonly<Record<string, string>> = {\n facts: 'The page leaves out a fact the owner gives. Say every name, number, price, date, phone and address the ledger shows.',\n invented: 'The page says something nothing on the site supports. Leave it out, or say only what the site states.',\n held: 'Something the ledger marks must is not on the page. Place it with a keep block.',\n links: 'A link the ledger lists goes nowhere on the page. Link to it from a button or an item.',\n meaning: \"The page has drifted from what the owner says. Keep more of the old page's substance in the new words.\",\n cta: 'The opening needs a filled primary button with a real destination, and the last section a button or the form: close on a call to action.',\n rhythm: 'Neighboring sections sit on one ground. Alternate plain and soft, or set one on a strong band.',\n columns: 'Sections stack like things in one column, or the page draws no group at all. Set a picture beside its words, and three or more like items as cards, steps or a faq.',\n framing: 'A picture is drawn taller than a screen holds. Set it in a column, or on a card.',\n contrast: 'A section is drawn on a ground its words do not read on. Choose another band.',\n phone: 'A section does not hold on a phone. Use the language’s rows and groups, which stack.',\n}\n\n/** A scored redesign's misses, each as the re-ask names it: what is red on its ledger and its design lines. */\nexport function aiSiteImportImprovedMisses(report: Pick<SiteImportPageFidelity, 'improved'>): AiDoctrineViolation[] {\n const improved = report.improved\n if (!improved) return []\n return improved.red.flatMap((name) => {\n if (name === 'frame') return []\n const ledger = improved.ledger as unknown as Record<string, { missing?: string[]; found?: string[]; at?: string[] } | undefined>\n const shown = [...(ledger[name]?.missing ?? []), ...(ledger[name]?.found ?? [])].map((token) => token.replace(/^[a-z]+:/, ''))\n // The line each invented value sat in (AGL-4152), so the re-ask can mend that sentence and a later read can see it.\n const at = ledger[name]?.at ?? []\n const message = MISS[name] ?? `The page falls short on ${name}.`\n const detail = [...(shown.length ? [`Named: ${shown.join(', ')}.`] : []), ...(at.length ? [`In: ${at.map((line) => `\"${line}\"`).join('; ')}.`] : [])].join(' ')\n return [{ rule: null, code: `improve-${name}`, message, ...(detail ? { detail } : {}) }]\n })\n}\n\n/** A redesign's read for a page: its ledger, and everywhere a link may go. */\nexport function aiSiteImportImproveLedger(doc: AiSiteImportDocument): SiteImportLedger {\n return siteImportLedger({ layout: aiSiteImportLayoutOf(doc), blocks: doc.blocks, photos: doc.photos })\n}\n\n/**\n * A redesign's check (AGL-4152), answer by answer: its words and refs held to\n * what the import read, its page compiled and held to the doctrine as a page\n * written (`build`), and scored (`score`). Any miss is named for the one\n * re-ask; a second miss is the caller's fallback.\n */\nexport function aiSiteImportImproveCheck<T>(input: {\n doc: AiSiteImportDocument\n ledger: SiteImportLedger\n design: AiLayoutDesign\n scope: readonly string[]\n formId: string | null\n framing?: AiCopyFraming | null\n plan?: AiSiteImportPlan | null\n theme?: SiteImportFidelityTheme | null\n /** What the page is for and the new sections it needs; absent, nothing is asked of its plan. */\n needs?: AiSiteImportImproveNeeds | null\n /** Words the platform's own request put to the answer (its role's lines), no one's name or fact. */\n vocabulary?: readonly string[]\n build: (page: AiSiteImportImprovedPage) => { value: T | null; violations: AiDoctrineViolation[] }\n score: (built: T, destinations: readonly string[]) => AiDoctrineViolation[]\n /**\n * The last answer read again once no re-ask is left (AGL-4152): its soft\n * misses (`AI_SITE_IMPORT_IMPROVE_SOFT_CODES`) are noted, not refused.\n * Every other line holds exactly as on the first read.\n */\n lenient?: boolean\n}): AiGenerationCheck<AiSiteImportImproved<T>> {\n return (answer) => {\n const read = aiReadImprovedPage(answer)\n if (!read) return { value: null, violations: [{ rule: null, code: 'improve-unreadable', message: `The answer gave no section that can be drawn. Answer with ${AI_SITE_IMPORT_IMPROVE_TOOL.name}.` }] }\n const formAt = read.findIndex((section) => section.blocks.some((block) => block.kind === 'keep' && block.ref.startsWith('form:')))\n const destinations = aiSiteImportImproveDestinations(input.doc, input.ledger, { sections: read.length, formSection: formAt === -1 ? null : formAt })\n const own = aiSiteImportOwnPage(input.doc)\n const honesty = aiSiteImportHonesty(read, { ledger: input.ledger, scope: input.scope, destinations, framing: input.framing ?? null, vocabulary: input.vocabulary ?? [], own })\n // What it lost and how it is planned, named together, so the one re-ask mends both.\n const planned = input.needs ? aiSiteImportImprovePlanMisses(read, { ledger: input.ledger, needs: input.needs }) : []\n const missed: string[] = input.lenient ? planned.map((violation) => violation.code) : []\n if (honesty.length || (planned.length && !input.lenient)) return { value: null, violations: [...honesty, ...planned] }\n const page = aiSiteImportImprovedPage(read, { doc: input.doc, ledger: input.ledger, design: input.design, destinations, formId: input.formId, plan: input.plan ?? null, theme: input.theme ?? null })\n const built = input.build(page)\n if (!built.value) return { value: null, violations: built.violations }\n // A link the source makes to the page it is on asks nothing of the page (AGL-4152).\n const wanted = input.ledger.links.flatMap((link) => {\n const to = destinations.get(link.ref)\n return to && to !== own ? [to] : []\n })\n const scored = input.score(built.value, [...new Set(wanted)])\n const refused = input.lenient ? scored.filter((violation) => !AI_SITE_IMPORT_IMPROVE_SOFT_CODES.has(violation.code)) : scored\n if (refused.length) return { value: null, violations: refused }\n missed.push(...scored.map((violation) => violation.code))\n return { value: { built: built.value, page, ...(missed.length ? { missed: [...new Set(missed)] } : {}) }, violations: [] }\n }\n}\n"],"names":["fenceUntrustedText","UNTRUSTED_TEXT_RULE","aiLayoutDesignChoices","aiLayoutGroupVariant","AI_LAYOUT_ALIGNS","AI_LAYOUT_BANDS","AI_LAYOUT_MAX_COLS","AI_LAYOUT_STYLES","aiReadLayoutBlock","AI_ICON_WORDS","aiSiteHomeArc","SITE_IMPORT_IMPROVED_MEANING","SITE_IMPORT_MEANING_FLOOR","siteImportContentKept","siteImportContentWords","aiSiteImportImageIsMark","siteImportLedger","AI_SITE_IMPORT_PAGE_CEILING_CREDITS","aiCacheWriteHourSurchargeUsd","aiBilledRatesForModel","estimateAiBilledUsd","assistCreditsFromUsd","siteImportLabel","aiSiteImportHonesty","aiSiteImportImprovedPlaced","aiSiteImportSectionActions","aiSiteImportLayoutOf","aiSiteImportLinkTo","aiSiteImportMapScope","aiSiteImportNodeBlocks","aiSiteImportTakePicture","aiSiteImportTextParts","clean","text","replace","trim","AI_SITE_IMPORT_IMPROVE_KIND","AI_SITE_IMPORT_IMPROVE_MAX_ITEMS","AI_SITE_IMPORT_IMPROVE_BLOCK_KINDS","ITEM_SCHEMA","type","additionalProperties","required","properties","title","to","icon","ref","BLOCK_SCHEMA","kind","enum","col","style","items","AI_SITE_IMPORT_IMPROVE_TOOL","name","description","strict","inputSchema","sections","band","cols","align","blocks","AI_SITE_IMPORT_IMPROVE_TEXT","join","aiSiteImportImproveDigest","input","siteName","scope","filter","Boolean","maxChars","AI_SITE_IMPORT_IMPROVE_DIGEST_CHARS","plan","JSON","stringify","aiSiteImportImproveInstructions","digest","cacheBreakpoint","site","AI_SITE_IMPORT_LEDGER_MAX_CHARS","textOf","block","short","most","length","slice","aiSiteImportPictureCaptions","ledger","pictures","item","lines","undefined","out","Map","at","next","Math","min","other","section","map","Number","POSITIVE_INFINITY","line","group","set","shownItem","doc","captions","must","words","url","photo","photos","find","entry","from","alt","with_","get","width","height","node","rows","alts","flatMap","columns","titles","test","linked","some","shown","folded","holds","aiSiteImportLedgerText","destinations","Set","links","link","has","aiSiteImportImproveDestinations","pathTo","path","id","href","page","proposed","siteLines","phone","exec","email","key","formSection","formPage","aiSiteImportFormPageOf","n","cta","nav","primaryCta","target","aiSiteImportOwnPage","URL","pathname","own","aiSiteImportImprovePrompt","screen","slug","roleLines","sizeLines","kindLines","seed","AI_SITE_IMPORT_NEW_SECTIONS","home","service","about","gallery","pricing","contact","faq","AI_SITE_IMPORT_ROLE_MEANING","aiSiteImportMeaningShare","role","AI_SITE_IMPORT_REWORK_LEAST_WORDS","AI_SITE_IMPORT_IMPROVE_MOST_SECTIONS","aiSiteImportPageRoleOf","toLowerCase","aiSiteImportNewSectionsWanted","size","max","ROLE_PLAN","aiSiteImportImproveRoleLines","wanted","arc","aiSiteImportImproveNewSections","answer","sources","kinds","said","reworked","best","forEach","index","kept","add","last","groups","shapeOf","includes","whole","AI_SITE_IMPORT_IMPROVE_LEAST_SHAPES","PICTURED_OPENINGS","aiSiteImportImprovePlanMisses","added","needs","push","rule","code","message","opening","startsWith","shapes","aiReadImprovedPage","raw","settled","given","Array","isArray","value","isFinite","round","position","isInteger","mostItems","_col","rest","AI_SITE_IMPORT_COVER_LEAST_RATIO","BOXED_HEROES","COVERING_HEROES","aiSiteImportImproveHero","design","chosen","hero","ratio","aiSiteImportImproveColumns","count","longest","WORD_KINDS","QUOTE_ACROSS_CHARS","AI_SITE_IMPORT_IMPROVE_FRAME_PX","wide","column","CARD_FRAME","CARD_PICTURE_KEPT","aiSiteImportCardPictures","placed","taken","pool","picture","refs","sectionNames","heading","base","aiSiteImportOpeningPhoto","first","imageOf","markAt","image","marks","ratioOf","spare","sort","a","b","instead","emptied","_","aiSiteImportImprovedPage","formId","finish","choices","written","deepened","theme","button","fill","light","brand","resolve","resolved","form","say","pictureOf","frame","fit","cropped","objectFit","rounded","across","inColumn","keepOf","groupAt","allowed","carded","asked","values","flat","ownOpening","openingPicture","widest","used","found","pick","drawn","src","part","_asked","groupItems","_ref","_to","figure","String","pictured","every","iconed","variant","tidy","label","opens","names","allPictures","unplaced","missing","source","stock","generated","slots","reduce","total","AI_SITE_IMPORT_IMPROVE_MOST_TOKENS","AI_SITE_IMPORT_LISTING_ROOM_CREDITS","AI_SITE_IMPORT_IMPROVE_CEILING_CREDITS","CHARS_PER_TOKEN","AI_TOOL_USE_PROMPT_TOKENS","ZERO","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","plus","cacheWriteHourTokens","tokensOf","chars","ceil","aiSiteImportImproveInputUsage","shared","system","cached","sharedChars","toolChars","siteChars","uncachedChars","promptChars","sharedTokens","hour","aiSiteImportImproveCredits","usage","model","aiSiteImportImproveTokensWithin","ceiling","before","spent","fits","tokens","low","high","floor","mid","AI_SITE_IMPORT_REASK_ROOM","AI_SITE_IMPORT_CUT_OFF_REASK_ROOM","AI_SITE_IMPORT_IMPROVE_LEAST_TOKENS","AI_SITE_IMPORT_IMPROVE_CUT_OFF_SMALLER","REASK_TOKENS","aiSiteImportImproveReaskInput","aiSiteImportImproveReaskTokens","room","aiSiteImportImproveReaskNeeds","lastOutput","cutOff","AI_SITE_IMPORT_ROOM_SHARE","AI_SITE_IMPORT_SECTION_TOKENS","AI_SITE_IMPORT_WORD_TOKENS","SECTION_WORDS","AI_SITE_IMPORT_LEAST_SECTIONS","AI_SITE_IMPORT_LEAST_PAGE_TOKENS","AI_SITE_IMPORT_THIN_PAGE_WORDS","AI_SITE_IMPORT_THIN_MOST_SECTIONS","AI_SITE_IMPORT_MEANING_WORDS_SHARE","aiSiteImportLedgerWords","match","fifty","aiSiteImportImproveRoom","estimated","both","mendable","thin","meaning","least","share","shaped","meant","aiSiteImportImproveSizeLines","AI_SITE_IMPORT_IMPROVE_SOFT_CODES","AI_SITE_IMPORT_REDESIGN_WHY_MOST","AI_SITE_IMPORT_REDESIGN_WHY_CHARS","aiSiteImportRedesignWhy","violations","violation","detail","aiSiteImportImproveOnlySoft","aiSiteImportPlanLines","what","audience","footer","purpose","TLD","aiSiteImportNameVariants","bare","segment","run","end","split","lead","caps","tail","titled","word","toUpperCase","aiSiteImportImproveScope","variants","MISS","facts","invented","held","rhythm","framing","contrast","aiSiteImportImprovedMisses","report","improved","red","token","aiSiteImportImproveLedger","layout","aiSiteImportImproveCheck","read","formAt","findIndex","honesty","vocabulary","planned","missed","lenient","built","build","scored","score","refused"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;2CAsB2C,GAE3C,SAASA,kBAAkB,EAAEC,mBAAmB,QAAQ,0CAAyC;AAEjG,SAASC,qBAAqB,EAAEC,oBAAoB,QAAQ,yCAAqC;AACjG,SACEC,gBAAgB,EAChBC,eAAe,EACfC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,QAO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