@aglyn/plugins-ai 1.0.0-beta.257 → 1.0.0-beta.258

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.
Files changed (84) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/assist-panel.component.js +21 -8
  3. package/src/lib/components/assist-panel.component.js.map +1 -1
  4. package/src/lib/insights/ai-figure-readers.js +15 -8
  5. package/src/lib/insights/ai-figure-readers.js.map +1 -1
  6. package/src/lib/jobs/ai-job-build-step.d.ts +9 -0
  7. package/src/lib/jobs/ai-job-build-step.js +19 -3
  8. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  9. package/src/lib/jobs/ai-job-insight-step.js +1 -1
  10. package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
  11. package/src/lib/jobs/ai-job-page-language.d.ts +19 -0
  12. package/src/lib/jobs/ai-job-page-language.js +24 -4
  13. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  14. package/src/lib/jobs/ai-job-page-sections.js +12 -1
  15. package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
  16. package/src/lib/jobs/ai-job-page-step.d.ts +14 -0
  17. package/src/lib/jobs/ai-job-page-step.js +69 -20
  18. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  19. package/src/lib/jobs/ai-job-seo-step.js +3 -2
  20. package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
  21. package/src/lib/jobs/ai-layout-stock-photos.d.ts +10 -5
  22. package/src/lib/jobs/ai-layout-stock-photos.js +89 -7
  23. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  24. package/src/lib/jobs/fixtures/ai-stock-photo-copper-kettle-recordings.d.ts +21 -0
  25. package/src/lib/jobs/fixtures/ai-stock-photo-copper-kettle-recordings.js +126 -0
  26. package/src/lib/jobs/fixtures/ai-stock-photo-copper-kettle-recordings.js.map +1 -0
  27. package/src/lib/layout-language/ai-layout-compiler.js +52 -52
  28. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  29. package/src/lib/layout-language/ai-layout-copy.d.ts +9 -5
  30. package/src/lib/layout-language/ai-layout-copy.js +22 -14
  31. package/src/lib/layout-language/ai-layout-copy.js.map +1 -1
  32. package/src/lib/layout-language/ai-layout-frame.js +4 -4
  33. package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
  34. package/src/lib/layout-language/ai-layout-pictures.d.ts +44 -15
  35. package/src/lib/layout-language/ai-layout-pictures.js +29 -8
  36. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
  37. package/src/lib/model/ai-build-job.js +14 -0
  38. package/src/lib/model/ai-build-job.js.map +1 -1
  39. package/src/lib/model/ai-host-publish-context.d.ts +6 -0
  40. package/src/lib/model/ai-host-publish-context.js +15 -2
  41. package/src/lib/model/ai-host-publish-context.js.map +1 -1
  42. package/src/lib/model/assist-follow-up.d.ts +35 -0
  43. package/src/lib/model/assist-follow-up.js +44 -4
  44. package/src/lib/model/assist-follow-up.js.map +1 -1
  45. package/src/lib/providers/anthropic.js +17 -4
  46. package/src/lib/providers/anthropic.js.map +1 -1
  47. package/src/lib/providers/cache-write-hour.d.ts +37 -0
  48. package/src/lib/providers/cache-write-hour.js +46 -0
  49. package/src/lib/providers/cache-write-hour.js.map +1 -0
  50. package/src/lib/providers/contract.d.ts +16 -3
  51. package/src/lib/providers/contract.js.map +1 -1
  52. package/src/lib/providers/routing.d.ts +13 -0
  53. package/src/lib/providers/routing.js +27 -11
  54. package/src/lib/providers/routing.js.map +1 -1
  55. package/src/lib/runtime/ai-dev-env.d.ts +13 -3
  56. package/src/lib/runtime/ai-dev-env.js +17 -3
  57. package/src/lib/runtime/ai-dev-env.js.map +1 -1
  58. package/src/lib/runtime/ai-dev-replay.js +4 -2
  59. package/src/lib/runtime/ai-dev-replay.js.map +1 -1
  60. package/src/lib/runtime/ai-doctrine-validators.d.ts +41 -1
  61. package/src/lib/runtime/ai-doctrine-validators.js +263 -2
  62. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  63. package/src/lib/runtime/ai-doctrine.js +7 -1
  64. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  65. package/src/lib/runtime/ai-eval-live.js +1 -1
  66. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  67. package/src/lib/runtime/ai-eval.d.ts +1 -1
  68. package/src/lib/runtime/ai-eval.js +18 -1
  69. package/src/lib/runtime/ai-eval.js.map +1 -1
  70. package/src/lib/runtime/ai-placeholder-tokens.d.ts +70 -0
  71. package/src/lib/runtime/ai-placeholder-tokens.js +169 -0
  72. package/src/lib/runtime/ai-placeholder-tokens.js.map +1 -0
  73. package/src/lib/runtime/ai-repeated-items.js +5 -2
  74. package/src/lib/runtime/ai-repeated-items.js.map +1 -1
  75. package/src/lib/runtime/ai-runtime.js +2 -3
  76. package/src/lib/runtime/ai-runtime.js.map +1 -1
  77. package/src/lib/server/assist-chat.js +8 -3
  78. package/src/lib/server/assist-chat.js.map +1 -1
  79. package/src/lib/server/assist-view-context.d.ts +5 -1
  80. package/src/lib/server/assist-view-context.js +8 -3
  81. package/src/lib/server/assist-view-context.js.map +1 -1
  82. package/src/lib/usage/assist-usage.d.ts +2 -0
  83. package/src/lib/usage/assist-usage.js +8 -3
  84. package/src/lib/usage/assist-usage.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-sections.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\nimport { REUSABLE_INSTANCE_COMPONENT_ID } from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport {\n aiPlanCreateFor,\n type AiBuildPlanRecord,\n type AiBuildPlanScreen,\n type AiBuildPlanSection,\n} from '../model/ai-build-plan'\nimport { aiPageTypeDefinition, parseAiPageJobInputs } from '../model/ai-page-job'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport { aiHomeScreenIds, aiHomeScreenNames, type AiSiteInventory } from '../model/ai-site-inventory'\nimport type { AiTool } from '../providers/contract'\nimport {\n AI_REASK_OFFENDING_MAX_CHARS,\n aiAnswerTree,\n aiNodeTreeContextFromInventory,\n type AiGenerationCheck,\n} from '../runtime/ai-doctrine'\nimport {\n aiSettleCutHeadings,\n aiSettleDisagreeingNodes,\n aiSettleGridItems,\n aiSettleMechanicalRules,\n detectCutLines,\n detectDisagreeingNodes,\n isAiLinkElement,\n validateAiDoctrineTree,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTreeContext,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { AI_INSTANCE_REF_PROP, validateAiNodeTree } from '../runtime/ai-node-tree'\nimport { aiPageLinkTarget, aiPageScrollInteraction } from '../runtime/ai-page-links'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE_CATALOG } from '../runtime/ai-palette.generated'\nimport { AI_REPEAT_KEY, expandAiRepeatedItems } from '../runtime/ai-repeated-items'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobBriefLine, aiPlanReferenceLines } from './ai-job-generation'\nimport { aiPlanItemCountViolations } from './ai-job-plan-conformance'\n\n/**\n * A page built one section at a time (AGL-2907): what one section pass asks\n * for, how its answer is held to the building rules as part of the page, and\n * how it joins the page.\n *\n * Pure: no Firestore and no provider, so the page step, its specs and the\n * evals read one definition of a section.\n *\n * ── Held as part of the page ─────────────────────────────────────────────\n *\n * A section is checked twice over, by validators the doctrine already has:\n * the palette validator on the section as the model wrote it, then the\n * doctrine's whole page check on the page built so far with the section\n * added. So the page's one main, its one h1 and its heading outline, repeats\n * across sections, and its weight against the page budget are held on every\n * pass, not only on the last. The violations name the section's own nodes,\n * by the ids the model wrote, so a re-ask quotes this section and nothing\n * else — the page is never sent back.\n *\n * ── A repeated item written once (AGL-3053) ──────────────────────────────\n *\n * Where the workspace keeps no reusable components, an answer writes a\n * repeated item once and lists its copies' values, and the check draws the\n * copies before either validator reads the section (`ai-repeated-items.ts`).\n * Both then read the section as the page stores it, so the page's rules hold\n * on every copy exactly as on an item written out in full, and a finding on a\n * copy names the node the model wrote. Where the workspace keeps components\n * the same shape is written around an instance (AGL-3024), so a section of\n * many cards costs its structure once on every plan; an item that places no\n * instance is still refused there.\n */\n\n/** The section root id a pass writes, from the job and the plan section's index. */\nexport function aiPageSectionNodeId(jobId: string, index: number): string {\n return `ai-${jobId.slice(0, 12)}-section-${index + 1}`\n}\n\n/** The strict tool a section arrives through. The node map rides as JSON text, as a page's does. */\nexport const AI_PAGE_SECTION_TOOL: AiTool = {\n name: 'submit_section',\n description: 'Submit one section of the page as one flat node map.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree'],\n properties: {\n tree: {\n type: 'string',\n description:\n 'The section as JSON: {\"rootId\": \"<id>\", \"nodes\": {\"<id>\": {\"componentId\": \"...\", \"props\": {...}, \"sx\": {...}, \"nodes\": [\"<child id>\", ...]}}}. The root is the document wrapper (componentId \"div\") holding one Section.',\n },\n },\n },\n}\n\n/** The page step's own instructions, cached after the doctrine, with the screen palette after them. */\nexport const AI_JOB_PAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build a web page one section at a time, in the order a confirmed plan gives. Each answer is ONE section: call submit_section with a flat node map whose root is the document wrapper (componentId \"div\") holding exactly one Section (section).',\n 'The first section is the top of the page and holds the page’s one h1, its title. Every later section opens with an h2, and headings below it step down one level at a time.',\n 'Place what the section’s plan line names. A component the site has is placed as an instance, never drawn again: componentId \"reusableInstance\", props {\"refId\": \"<component id>\", \"propValues\": {…}} filling the props the inventory lists. A form the site has is a Form (form) whose formId is that form’s id. Another page of the site is linked by its page id, with a Page Link (muiScreenLink) or a Button (muiButton) whose screenId is that id.',\n 'Where the request says the site keeps no reusable components, draw a repeated item in the section instead, written once. A form is only ever a saved one placed by its formId: where the plan line names no form, the section draws no form and no field of one.',\n 'Lay the section out with a Container, a Stack or a Grid (\"container\": true, \"spacing\": 3) of Grid items sized like \"xs:12 md:4\", and size nothing with a fixed width. Colors come from the theme’s palette tokens such as primary.main, spacing from the spacing scale, and type from the text variants.',\n 'The page renders inside the site’s layout, so a section is never a header, navigation or footer.',\n 'A picture is an Image (image) with alt text that says what it should show and no src, for the site owner to fill from the media library.',\n 'Write plain, specific copy in the site’s voice, with no filler. Where the brief leaves out a fact, such as a price, a phone number or an address, write the gap in square brackets instead of inventing it.',\n ].join('\\n'),\n },\n { text: AI_PALETTE_CATALOG.screen, cacheBreakpoint: true },\n]\n\n/** A plan reference as the request names it: the id with the name it was planned under. */\nfunction referenceOf(plan: AiJobPlan, ref: string): string {\n const label = plan.labels?.[ref]\n return label ? `${ref} (\"${label}\")` : ref\n}\n\n/**\n * A record template as a page pass reads it (AGL-3475): the dataset by name,\n * its base, and the fields its copy binds, as `{{item.<id>}}` with the name a\n * member gave each. A dataset the plan creates has no ids yet, so its tokens\n * are the field names it was planned with.\n */\nexport interface AiPageRecordTemplate {\n /** The dataset: an inventory id, or the plan's `new:<name>`. */\n dataset: string\n name: string\n base: string\n fields: Array<{ id: string; name: string }>\n /** The field holding each record's photo, where the dataset has one (AGL-3616). */\n imageField?: string\n}\n\n/** The record template a plan screen is, read against the site's datasets; null for a page that is one page. */\nexport function aiPageRecordTemplate(\n record: AiBuildPlanRecord | null | undefined,\n inventory: AiSiteInventory | null,\n plan: AiJobPlan,\n): AiPageRecordTemplate | null {\n if (!record) return null\n const row = inventory?.datasets.find((entry) => entry.id === record.dataset)\n if (row) {\n return {\n dataset: record.dataset,\n name: row.name,\n base: record.base,\n fields: row.fields.map((name, index) => ({ id: row.fieldIds?.[index] || name, name })),\n ...(row.imageField ? { imageField: row.imageField } : {}),\n }\n }\n const created = aiPlanCreateFor(plan, record.dataset)\n return {\n dataset: record.dataset,\n name: created?.name ?? plan.labels?.[record.dataset] ?? record.dataset,\n base: record.base,\n fields: (created?.fields ?? []).map((name) => ({ id: name, name })),\n }\n}\n\n/** Every token a record template's page may bind: each field, and `{{item.url}}`. */\nexport function aiPageRecordTokens(template: AiPageRecordTemplate | null): string[] {\n if (!template) return []\n return [...template.fields.map((field) => `{{item.${field.id}}}`), '{{item.url}}']\n}\n\n/** What a section request says on a record template's page. */\nexport function aiPageRecordLine(template: AiPageRecordTemplate): string {\n const fields = template.fields.length\n ? ` Its fields: ${template.fields\n .map((field) => (field.name === field.id ? `{{item.${field.id}}}` : `{{item.${field.id}}} (${field.name})`))\n .join(', ')}.`\n : ''\n // A record's photo is a picture's address, never its words (AGL-3616).\n const photo = template.imageField ? ` Each record's photo is {{item.${template.imageField}}}: the src of the page's main Image.` : ''\n return `This page is the record template of the dataset \"${template.name}\": it is served once per record, at /${template.base}/<record address>. Write what differs from one record to the next as {{item.<field>}}, never one record's copy, and write out what every record page shares.${fields}${photo}`\n}\n\n/**\n * A record template's section with the record's own photo (AGL-3616): where\n * the dataset keeps one and the page shows it nowhere yet, the section's\n * first Image that names no record's photo shows `{{item.<photo field>}}`,\n * so each record's page leads with its piece, its dish, its person, as its\n * card on the list does. Any other section, and a page already showing it,\n * is returned as it came. Pure.\n */\nexport function aiPageSectionWithRecordImage(\n section: AiPageSection,\n page: NodesMap,\n template: AiPageRecordTemplate | null,\n): AiPageSection {\n const field = template?.imageField\n if (!field) return section\n const token = `{{item.${field}}}`\n const showsIt = (nodes: NodesMap) =>\n Object.values(nodes as unknown as Record<string, { componentId?: unknown; props?: Record<string, unknown> }>).some(\n (node) => node?.componentId === 'image' && node.props?.['src'] === token,\n )\n if (showsIt(page) || showsIt(section.nodes)) return section\n const first = walkTree({ rootId: section.rootId, nodes: section.nodes as unknown as Record<string, AiDoctrineNode> }).find(\n ({ node }) => node.componentId === 'image',\n )\n if (!first) return section\n const node = (section.nodes as unknown as Record<string, Record<string, unknown>>)[first.id]\n const props = isRecord(node['props']) ? node['props'] : {}\n return {\n ...section,\n nodes: { ...section.nodes, [first.id]: { ...node, props: { ...props, src: token } } } as unknown as NodesMap,\n }\n}\n\n/**\n * What a record template's draft tells the member to do next. The binding is\n * a route, so the job never writes it (rule 13): the member saves it where\n * every record template is set up.\n */\nexport function aiPageRecordNote(template: AiPageRecordTemplate): string {\n return `This page is drafted as the record template of \"${template.name}\". To serve a page per record at /${template.base}/…, open Page Properties → Record pages and save its dataset, address and fields: the cards that list its records link those pages.`\n}\n\nexport interface AiPageSectionPromptInput {\n job: Pick<AiJob, 'brief' | 'inputs'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n index: number\n /** The most elements the section may carry at this pass's answer ceiling. */\n maxElements: number\n /**\n * Whether the workspace keeps reusable components (AGL-3030); `false`\n * asks for a repeated item drawn in the section. Absent is `true`. A form\n * is never drawn inline, whatever this says (AGL-3596).\n */\n reusableComponents?: boolean\n /** The dataset this page is the record template of; absent for a page that is one page. */\n record?: AiPageRecordTemplate | null\n /**\n * The site's other pages a link may go to by id (AGL-3596): a guided\n * start's pages are minted on its plan before any is built, so the Home\n * page is built before the Contact page its buttons go to exists.\n */\n linkablePages?: readonly AiLinkablePage[]\n}\n\n/** A page of the site a section may link by its id, built or still to come. */\nexport interface AiLinkablePage {\n id: string\n label: string\n slug: string\n}\n\n/**\n * The pages a section may link by id beyond the ones the site has built, and\n * the one page a link that names no destination can only mean (AGL-3596).\n * `planned` are a guided start's pages, minted on its plan (the input the\n * layout reads them from); `own` are this page's ids, which neither counts.\n * The link target is the site's one page that is neither its home nor this\n * page, where it has exactly one, built or planned: a two-page guided start's\n * Contact page, which its Home hero's \"Book an appointment\" goes to.\n */\nexport function aiPageLinkablePages(\n inventory: AiSiteInventory | null,\n planned: readonly AiLinkablePage[],\n own: ReadonlyArray<string | null | undefined>,\n): { linkablePages: AiLinkablePage[]; linkTarget: string | null } {\n const mine = new Set(own.filter((id): id is string => Boolean(id)))\n const home = new Set(aiHomeScreenIds(inventory))\n const isHome = (slug: string): boolean => slug.replace(/^\\/+|\\/+$/g, '') === ''\n const linkablePages = planned.filter((page) => !mine.has(page.id))\n const targets = new Set([\n ...(inventory?.screens ?? [])\n .filter((row) => !row.template && !home.has(row.id) && !isHome(row.slug))\n .map((row) => row.id),\n ...linkablePages.filter((page) => !isHome(page.slug)).map((page) => page.id),\n ])\n for (const id of mine) targets.delete(id)\n return { linkablePages, linkTarget: targets.size === 1 ? [...targets][0] : null }\n}\n\n/** The line a section request names the site's other pages in. */\nexport function aiPageSectionLinkablePagesLine(pages: readonly AiLinkablePage[]): string | null {\n if (!pages.length) return null\n const listed = pages.map((page) => `${page.label} (${page.slug || '/'}, id \"${page.id}\")`).join(', ')\n return `Other pages of this site: ${listed}. A button or link that goes to one sets its \"screenId\" to that id.`\n}\n\n/** What a section request says where the workspace keeps no reusable components. */\nexport const AI_PAGE_SECTION_INLINE_LINE =\n 'This site keeps no reusable components: write a repeated item once.'\n\n/** How a repeated item is written once, in the words a request and a re-ask share. */\nconst AI_PAGE_SECTION_REPEAT_SHAPE = `put {{1}}, {{2}}… where its copies differ, and give its outermost node \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]]`\n\n/**\n * How a repeated item is written once (AGL-3053): the item's subtree once,\n * with placeholders where its copies differ and their values listed, which\n * the section check draws into its copies (`ai-repeated-items.ts`). It rides\n * the request of a section whose plan line shows items on a workspace that\n * keeps no reusable components, and no other: a section with nothing to repeat\n * pays nothing for it, and the cached prefix every workspace shares says only\n * that a repeated item is written once.\n */\nexport const AI_PAGE_SECTION_REPEAT_LINE = `Write a repeated item once: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n\n/**\n * How a workspace that keeps reusable components writes a repeated item\n * (AGL-3143 §10): the shape a Free section writes, around an instance of a\n * component the section already places — the instance ONCE, `{{n}}` through\n * the values it fills, and one list of values a copy — rather than the item's\n * subtree drawn once per copy, or one instance node written per copy.\n *\n * Six cards written as six instance nodes spend their structure six times;\n * written once they spend it once, which is the difference between a section\n * that fits its ceiling and one that is cut off. A section stays ONE section\n * either way: splitting it would give the page a second h2 for the same idea,\n * which is not what the member asked for and not what its outline should say.\n *\n * ⛔ The repeated item is the GRID ITEM, not the instance. Measured live on\n * 2026-09-22: told only to \"place ONE instance … and give its outermost node\n * repeat\", the model made the instance itself the repeated node and hung it\n * straight off the Grid container. The section fitted — the ceiling failure\n * was gone — and the page was then refused by rule 12, which requires every\n * child of a Grid container to be a sized Grid item (AGL-3055). The line has\n * to name the wrapper, because \"outermost node\" reads as the instance when\n * the instance is all the request mentions.\n *\n * It rides the request of a section whose plan line shows items AND names a\n * record to place, on the same terms the repeat line rides a Free one: a\n * section with nothing to repeat, or nothing to repeat it FROM, pays nothing\n * for it.\n *\n * ## Why a paid section could not be built without it (AGL-3024)\n *\n * The Free path is reconciled at both ends — its plan is held to the sections\n * its wall pays for (AGL-3070) and its request is shown the repeat shape\n * (AGL-3053). The paid path was reconciled at neither: `AI_BUILD_PLAN_LIMITS`\n * lets a plan promise up to `items: 500` in one section, the pass that builds\n * it fits `aiJobPageSectionMaxElements` — fifteen at the balanced tier — and\n * the request said only how many elements to keep under, never how to get\n * there. A six-card grid measured live on 2026-09-21 was drawn inline, ran\n * past its ceiling, and was cut off; the re-ask then said to place an instance\n * \"of a component the site has\" without naming one, so it was cut off too, and\n * `AI_GENERATION_MAX_ATTEMPTS` ended the job with no page. A four-card grid on\n * the same site had fitted, which is why this went unseen. Naming the shape\n * was not enough on its own: `ai-repeated-items.ts` refused `repeat` outright\n * on such a workspace, so the only shape the request could ask for was the\n * expensive one.\n *\n * ⛔ This does NOT make the plan and the pass agree about what fits — a plan\n * may still promise more items than any ceiling can carry, and this line only\n * gives the pass its cheapest way to try. That bound belongs on the plan step\n * and is deliberately not taken here.\n */\nexport const AI_PAGE_SECTION_INSTANCE_LINE = `Write a repeated item once: put ONE instance of the component this section places inside ONE Grid item sized like \"xs:12 sm:6 md:4\", and repeat THAT GRID ITEM rather than the instance — every child of a Grid container is itself a Grid item. Put {{1}}, {{2}}… where the copies differ, and give the Grid item \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]].`\n\n/**\n * What a pass whose answer ran past its ceiling is told makes a section\n * smaller (AGL-3042): fewer elements, down to the budget the request gave,\n * shorter copy, and a repeated item drawn no more than once — placed as an\n * instance where the workspace keeps reusable components, and written once\n * where it keeps none (AGL-3053), with the shape spelled out, since a section\n * whose plan line showed no items was never told it. It rides the re-ask,\n * never the first request, so a pass that fits sends no byte more.\n */\nexport function aiPageSectionSmaller(input: Pick<AiPageSectionPromptInput, 'maxElements' | 'reusableComponents'>): string {\n return input.reusableComponents === false\n ? `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n : `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: put ONE instance of a component the site has inside ONE Grid item sized like \"xs:12 sm:6 md:4\", and repeat that Grid item — ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n}\n\n/** One pass's user turn: the page, the brief, the plan, this section and what is built above it. */\nexport function aiPageSectionPrompt(input: AiPageSectionPromptInput): string {\n const { job, plan, screen, index } = input\n const inputs = parseAiPageJobInputs(job.inputs)\n const type = typeof inputs === 'string' ? null : aiPageTypeDefinition(inputs.pageType)\n const section = screen.sections[index] as AiBuildPlanSection\n const places = section.uses.length\n ? ` It places ${section.uses.map((ref) => referenceOf(plan, ref)).join(', ')}.`\n : ''\n const items = section.items ? ` It shows ${section.items} items.` : ''\n const built = screen.sections.slice(0, index).map((entry, position) => `${position + 1}. ${entry.name}`)\n return [\n `Page: \"${screen.title}\" at ${screen.slug}`,\n ...(type ? [`Page type: ${type.purpose}`] : []),\n ...(input.record ? [aiPageRecordLine(input.record)] : []),\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n `Build section ${index + 1} of ${screen.sections.length}: \"${section.name}\".${places}${items}`,\n built.length\n ? `Already built, above it: ${built.join('; ')}. The page’s h1 is in section 1.`\n : 'Nothing is built yet: this section holds the page’s h1.',\n ...(input.reusableComponents === false\n ? [AI_PAGE_SECTION_INLINE_LINE, ...(section.items ? [AI_PAGE_SECTION_REPEAT_LINE] : [])]\n : section.items && section.uses.length\n ? [AI_PAGE_SECTION_INSTANCE_LINE]\n : []),\n ...(input.linkablePages?.length ? [aiPageSectionLinkablePagesLine(input.linkablePages) as string] : []),\n `Keep this section to at most ${input.maxElements} elements.`,\n ].join('\\n')\n}\n\n/** A validated section: its nodes keyed as the page stores them, its root under the page root. */\nexport interface AiPageSection {\n rootId: string\n nodes: NodesMap\n /** The page's weight with the section added, as the doctrine measured it. */\n load: AiLoadEstimate | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A page with nothing on it yet: the document wrapper. */\nexport function aiEmptyPage(): NodesMap {\n return {\n [CANVAS_ROOT_ELEMENT_ID]: {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n parentId: null,\n nodes: [],\n },\n } as unknown as NodesMap\n}\n\n/**\n * The page with a section in its plan position: after every section with a\n * lower index and before every one with a higher, the page's other children\n * — whatever a member placed — kept where they are. A section already on the\n * page is replaced, never doubled.\n */\nexport function aiPageWithSection(\n page: NodesMap,\n section: AiPageSection,\n sectionIds: readonly string[],\n): NodesMap {\n const nodes: Record<string, Record<string, unknown>> = {}\n const previous = (page as unknown as Record<string, Record<string, unknown>>)[section.rootId]\n const replaced = new Set<string>()\n if (previous) {\n for (const { id } of walkTree({\n rootId: section.rootId,\n nodes: page as unknown as Record<string, AiDoctrineNode>,\n })) {\n replaced.add(id)\n }\n }\n for (const [id, node] of Object.entries(page)) {\n if (!replaced.has(id)) nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n const root = nodes[CANVAS_ROOT_ELEMENT_ID] ?? (aiEmptyPage()[CANVAS_ROOT_ELEMENT_ID] as unknown as Record<string, unknown>)\n const children = (Array.isArray(root['nodes']) ? (root['nodes'] as string[]) : []).filter(\n (id) => id !== section.rootId,\n )\n const order = new Map(sectionIds.map((id, position) => [id, position]))\n const at = order.get(section.rootId) ?? sectionIds.length\n const before = children.findIndex((id) => (order.get(id) ?? -1) > at)\n children.splice(before === -1 ? children.length : before, 0, section.rootId)\n nodes[CANVAS_ROOT_ELEMENT_ID] = { ...root, nodes: children }\n for (const [id, node] of Object.entries(section.nodes)) {\n nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n return nodes as unknown as NodesMap\n}\n\n/**\n * What a tree generated against this inventory may reference, the brand it is\n * held to, where the workspace keeps no reusable components\n * (AGL-3030) that the page is built inline, the sections its plan names,\n * which a link may take a visitor to (AGL-3097), and the players its plan\n * lists for this page, the only ones it may embed (AGL-3433).\n */\nexport function aiPageCheckContext(\n inventory: AiSiteInventory | null,\n options: {\n reusableComponents?: boolean\n sections?: readonly string[]\n embeds?: AiDoctrineTreeContext['plannedEmbeds']\n /** A record template's tokens, which its links and images may name (AGL-3475). */\n recordTokens?: readonly string[]\n /** The site's pages still to be built that a link may go to by id (AGL-3596). */\n linkablePages?: readonly AiLinkablePage[]\n } = {},\n): AiDoctrineTreeContext {\n const tree = aiNodeTreeContextFromInventory(inventory)\n const screenIds = [...new Set([...(tree.screenIds ?? []), ...(options.linkablePages ?? []).map((page) => page.id)])]\n return {\n brand: inventory?.theme ? { colors: inventory.theme.colors, fonts: inventory.theme.fonts } : null,\n ...tree,\n ...(tree.screenIds || options.linkablePages?.length ? { screenIds } : {}),\n homeScreenIds: aiHomeScreenIds(inventory),\n homeLabels: aiHomeScreenNames(inventory),\n ...(options.reusableComponents === false ? { reusableComponents: false } : {}),\n ...(options.sections?.length ? { pageSections: options.sections } : {}),\n ...(options.embeds?.length ? { plannedEmbeds: options.embeds } : {}),\n ...(options.recordTokens?.length ? { bindingTokens: options.recordTokens } : {}),\n }\n}\n\nexport interface AiPageSectionCheckInput {\n /** The page as stored so far; an empty page on the first pass. */\n page: NodesMap\n /** Every section root id of the plan, in order. */\n sectionIds: readonly string[]\n index: number\n context: AiDoctrineTreeContext\n /**\n * The plan line this pass answers for: what it places by inventory id, and\n * how many items it promised, which the answer is held to (AGL-3024).\n */\n section: Pick<AiBuildPlanSection, 'name' | 'uses' | 'items'>\n inventory: AiSiteInventory | null\n /**\n * The one page a link that goes nowhere can only mean, where the site has\n * exactly one page besides its home and this one (AGL-3596): a guided\n * start's Contact page. Absent or `null`, such a link is re-asked.\n */\n linkTarget?: string | null\n}\n\n/** The parts of an answer the violations name, as the model wrote them, capped as the doctrine caps a re-ask. */\nfunction offendingOf(raw: unknown, violations: readonly AiDoctrineViolation[]): { offending?: Record<string, unknown> } {\n const rawNodes = isRecord(raw) && isRecord(raw['nodes']) ? raw['nodes'] : {}\n const offending: Record<string, unknown> = {}\n let used = 2\n for (const id of new Set(violations.flatMap((violation) => violation.nodeIds ?? []))) {\n if (rawNodes[id] === undefined) continue\n const size = JSON.stringify(rawNodes[id]).length + id.length + 4\n if (used + size > AI_REASK_OFFENDING_MAX_CHARS) break\n offending[id] = rawNodes[id]\n used += size\n }\n return Object.keys(offending).length ? { offending } : {}\n}\n\n/**\n * The check a section's answer is held to: a repeated item written once drawn\n * into its copies (AGL-3053), then the palette validator on the section, with\n * any line it cut at its ceiling refused (AGL-3076), a Grid container's items\n * sized where rule 12 has one answer (AGL-3596), the doctrine's page check\n * on the page with the section added, and the plan line — every component it\n * names placed as an instance, every form bound by its id (rule 7), and as\n * many items as it promised (AGL-3024). Violations\n * name the section's own nodes by the ids the MODEL wrote, and a copy's nodes\n * by the item's; one that names only nodes an earlier pass stored belongs to\n * the page rather than to this answer, and is left to the last pass (AGL-3078).\n */\nexport function aiPageSectionCheck(input: AiPageSectionCheckInput): AiGenerationCheck<AiPageSection> {\n const sectionId = input.sectionIds[input.index]\n const components = new Set((input.inventory?.components ?? []).map((row) => row.id))\n const forms = new Set((input.inventory?.forms ?? []).map((row) => row.id))\n return (answer) => {\n // A child named and never written, an element written and held by\n // nothing, and a heading whose first clause fits its ceiling are settled\n // where each has one reading (AGL-3596).\n const raw = aiSettleCutHeadings(aiSettleDisagreeingNodes(aiAnswerTree(answer)))\n // Before anything is drawn or dropped: a repeated item written and never\n // placed is content the section loses silently, and a child named and\n // never written ends the pass with nothing to answer (AGL-3143).\n const disagreeing = detectDisagreeingNodes(raw)\n if (disagreeing.length) {\n return { value: null, violations: disagreeing, ...offendingOf(raw, disagreeing) }\n }\n // A repeated item is drawn inline where the workspace keeps no reusable\n // components, and where this section's plan line places none (AGL-3596):\n // there is then no component it could be drawing by hand, and a paid\n // guided start's \"Why choose us\" was refused for rule 1 with nothing to place.\n const inline = input.context.reusableComponents === false || !input.section.uses.some((ref) => components.has(ref))\n const drawn = expandAiRepeatedItems(raw, { inline, noun: 'section' })\n if (drawn.ok === false) {\n return { value: null, violations: drawn.violations, ...offendingOf(raw, drawn.violations) }\n }\n // Every id below is the drawn tree's; a copy's leads back to the node the model wrote.\n const written = (id: string): string => drawn.sourceIds[id] ?? id\n const validated = validateAiNodeTree(drawn.tree, 'screen', input.context)\n if (validated.ok === false) {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: `tree-${validated.code}`,\n message: 'The answer could not be used as a section.',\n detail: validated.error,\n },\n ],\n }\n }\n const drawnNodes = isRecord(drawn.tree) && isRecord(drawn.tree['nodes']) ? drawn.tree['nodes'] : {}\n // A Grid container's items are sized, and an element straight in one is\n // put in an item, before the page check reads them: that rule has one\n // answer, the size its re-ask would name (AGL-3596). Read off the section\n // as the palette validator stored it, with what the model wrote beside it.\n const { nodes: settled } = aiSettleGridItems(\n { rootId: validated.rootId, nodes: validated.nodes as unknown as Record<string, AiDoctrineNode> },\n { written: (id) => drawnNodes[validated.sourceIds[id] ?? id] },\n )\n const wrapper = settled[validated.rootId] as AiDoctrineNode | undefined\n const top = (wrapper?.nodes ?? []).filter((id) => settled[id])\n const sectionNode = top.length === 1 ? settled[top[0]] : null\n if (!sectionNode || sectionNode.componentId !== 'section') {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'section-shape',\n message: 'Answer with exactly one Section element inside the document wrapper.',\n },\n ],\n }\n }\n\n // The section's root takes its plan id, so a pass run again finds it, and\n // hangs under the page root; every other minted id stays as minted.\n const minted = top[0]\n const modelIds: Record<string, string> = Object.fromEntries(\n Object.entries(validated.sourceIds).map(([id, source]) => [id, written(source)]),\n )\n modelIds[sectionId] = written(validated.sourceIds[minted] ?? minted)\n const sectionNodes: Record<string, Record<string, unknown>> = {}\n for (const { id, node } of walkTree({ rootId: minted, nodes: settled })) {\n const stored = { ...(node as unknown as Record<string, unknown>) }\n if (id === minted) {\n stored['$id'] = sectionId\n stored['parentId'] = CANVAS_ROOT_ELEMENT_ID\n } else if (stored['parentId'] === minted) {\n stored['parentId'] = sectionId\n }\n sectionNodes[id === minted ? sectionId : id] = stored\n }\n // What the model wrote of one of the section's nodes, by the id the page stores it under.\n const drawnIdOf = (stored: string): string =>\n validated.sourceIds[stored === sectionId ? minted : stored] ?? stored\n // A link that names a section of this page carries the platform's Scroll to\n // element interaction to that section's root, whose id is minted from the\n // plan before the section is built (AGL-3097).\n const sections = input.context.pageSections ?? []\n // A link that names no destination at all, on a site with one page it can\n // only mean, goes to that page (AGL-3596); one inside a form is the form's\n // own button, which rule 10 asks to take out.\n const inForm = (id: string): boolean => {\n for (let at = sectionNodes[id]?.['parentId']; typeof at === 'string'; at = sectionNodes[at]?.['parentId']) {\n if (sectionNodes[at]?.['componentId'] === 'form') return true\n }\n return false\n }\n for (const [id, node] of Object.entries(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (!isAiLinkElement(node['componentId']) || props['screenId'] || props['href']) continue\n const target = aiPageLinkTarget(drawnNodes[drawnIdOf(id)], sections)\n if (target?.kind === 'section') {\n node['interactions'] = [aiPageScrollInteraction(input.sectionIds[target.section], sections[target.section])]\n } else if (!target && input.linkTarget && !inForm(id)) {\n node['props'] = { ...props, screenId: input.linkTarget }\n }\n }\n const section: AiPageSection = { rootId: sectionId, nodes: sectionNodes as unknown as NodesMap, load: null }\n\n // An attribute a rule has one answer for is applied on the page with the\n // section added, since the first image and the one h1 are the page's\n // (AGL-3660). The section keeps what that settled of its own nodes; what\n // it settled of an earlier pass's is the last pass's to store.\n const settledPage = aiSettleMechanicalRules(\n {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n nodes: aiPageWithSection(input.page, section, input.sectionIds) as unknown as Record<string, AiDoctrineNode>,\n },\n 'page',\n )\n for (const id of Object.keys(sectionNodes)) {\n sectionNodes[id] = settledPage.nodes[id] as unknown as Record<string, unknown>\n }\n const page = settledPage.nodes as unknown as NodesMap\n const own = new Set(Object.keys(sectionNodes))\n // The page check reads the section as the page stores it, where the palette\n // validator has already dropped what it could not read, such as a\n // `container` written as text or a link's `scrollTo`; what the model wrote\n // of each of the section's nodes is read from the section as it was drawn\n // (AGL-3078). A link the page already carries to one of its section roots\n // goes there, whichever pass wrote it (AGL-3097).\n const report = validateAiDoctrineTree({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page }, 'page', {\n ...input.context,\n writtenNode: (id) => (own.has(id) ? drawnNodes[drawnIdOf(id)] : undefined),\n scrollTargetIds: input.sectionIds,\n })\n // The page check mints its ids afresh: its map leads back to the page's\n // ids, and the section's own lead back to the model's.\n const pageIds = report.tree?.sourceIds ?? {}\n const toModel = (id: string): string | null => {\n const stored = pageIds[id] ?? id\n return own.has(stored) ? (modelIds[stored] ?? stored) : null\n }\n // The page check reads the section as it is stored, where a line the\n // palette validator cut is already cut, so the cut is read from the\n // section's own validation, first (AGL-3076). Copies of one item name one\n // node the model wrote, once.\n //\n // A PASS ANSWERS ONLY FOR THE SECTION IT WROTE (AGL-3078). The page check\n // reads the whole page, so it also names nodes an earlier pass stored; the\n // model is not shown those and cannot mend them, so a finding that names\n // none of this section's nodes is not held against this answer. Dropping\n // it neither hides nor forgives it: the last pass runs the same check on\n // the finished page, where every node is the page's and the review names\n // each one and outlines it. Kept, such a finding would re-ask the model\n // for a node it never saw, refuse the same answer twice, and stop the page\n // with findings whose ids all filtered away — no node ids, and so no\n // outline either.\n const violations: AiDoctrineViolation[] = [\n ...detectCutLines(validated.repairs, drawnNodes, written),\n ...report.violations.flatMap((violation) => {\n if (!violation.nodeIds?.length) return [violation]\n const named = [...new Set(violation.nodeIds.map(toModel).filter((id): id is string => id !== null))]\n return named.length ? [{ ...violation, nodeIds: named }] : []\n }),\n ]\n\n const placed = new Set<string>()\n const bound = new Set<string>()\n for (const node of Object.values(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (node['componentId'] === REUSABLE_INSTANCE_COMPONENT_ID && typeof props[AI_INSTANCE_REF_PROP] === 'string') {\n placed.add(props[AI_INSTANCE_REF_PROP] as string)\n }\n if (node['componentId'] === 'form' && typeof props['formId'] === 'string') bound.add(props['formId'])\n }\n const missing = input.section.uses.filter(\n (ref) => (components.has(ref) && !placed.has(ref)) || (forms.has(ref) && !bound.has(ref)),\n )\n if (missing.length) {\n violations.push({\n rule: 7,\n code: 'plan-reuse-not-placed',\n message: `The confirmed plan places ${missing.join(', ')} in this section, and the section does not. Place each one by its id.`,\n })\n }\n // The count the plan promised, against the section as the page stores it\n // (AGL-3024): the prompt states it, and until now nothing read it back.\n violations.push(\n ...aiPlanItemCountViolations(input.section, {\n rootId: sectionId,\n nodes: sectionNodes as unknown as Record<string, AiDoctrineNode>,\n }),\n )\n\n return {\n value: { ...section, load: report.load },\n violations,\n ...offendingOf(raw, violations),\n }\n }\n}\n"],"names":["REUSABLE_INSTANCE_COMPONENT_ID","CANVAS_ROOT_ELEMENT_ID","aiPlanCreateFor","aiPageTypeDefinition","parseAiPageJobInputs","aiHomeScreenIds","aiHomeScreenNames","AI_REASK_OFFENDING_MAX_CHARS","aiAnswerTree","aiNodeTreeContextFromInventory","aiSettleCutHeadings","aiSettleDisagreeingNodes","aiSettleGridItems","aiSettleMechanicalRules","detectCutLines","detectDisagreeingNodes","isAiLinkElement","validateAiDoctrineTree","walkTree","AI_INSTANCE_REF_PROP","validateAiNodeTree","aiPageLinkTarget","aiPageScrollInteraction","AI_PALETTE_CATALOG","AI_REPEAT_KEY","expandAiRepeatedItems","aiJobBriefLine","aiPlanReferenceLines","aiPlanItemCountViolations","aiPageSectionNodeId","jobId","index","slice","AI_PAGE_SECTION_TOOL","name","description","strict","inputSchema","type","additionalProperties","required","properties","tree","AI_JOB_PAGE_INSTRUCTIONS","text","join","screen","cacheBreakpoint","referenceOf","plan","ref","label","labels","aiPageRecordTemplate","record","inventory","created","row","datasets","find","entry","id","dataset","base","fields","map","fieldIds","imageField","aiPageRecordTokens","template","field","aiPageRecordLine","length","photo","aiPageSectionWithRecordImage","section","page","token","showsIt","nodes","Object","values","some","node","componentId","props","first","rootId","isRecord","src","aiPageRecordNote","aiPageLinkablePages","planned","own","mine","Set","filter","Boolean","home","isHome","slug","replace","linkablePages","has","targets","screens","delete","linkTarget","size","aiPageSectionLinkablePagesLine","pages","listed","AI_PAGE_SECTION_INLINE_LINE","AI_PAGE_SECTION_REPEAT_SHAPE","AI_PAGE_SECTION_REPEAT_LINE","AI_PAGE_SECTION_INSTANCE_LINE","aiPageSectionSmaller","input","reusableComponents","maxElements","aiPageSectionPrompt","job","inputs","pageType","sections","places","uses","items","built","position","title","purpose","value","Array","isArray","aiEmptyPage","$id","parentId","aiPageWithSection","sectionIds","order","previous","replaced","add","entries","root","children","Map","at","get","before","findIndex","splice","aiPageCheckContext","options","screenIds","brand","theme","colors","fonts","homeScreenIds","homeLabels","pageSections","embeds","plannedEmbeds","recordTokens","bindingTokens","offendingOf","raw","violations","rawNodes","offending","used","flatMap","violation","nodeIds","undefined","JSON","stringify","keys","aiPageSectionCheck","sectionId","components","forms","answer","validated","report","disagreeing","inline","context","drawn","noun","ok","written","sourceIds","rule","code","message","detail","error","drawnNodes","settled","wrapper","top","sectionNode","minted","modelIds","fromEntries","source","sectionNodes","stored","drawnIdOf","inForm","target","kind","screenId","load","settledPage","writtenNode","scrollTargetIds","pageIds","toModel","repairs","named","placed","bound","missing","push"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,8BAA8B,QAAQ,iDAAgD;AAC/F,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SACEC,eAAe,QAIV,4BAAwB;AAC/B,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,0BAAsB;AAEjF,SAASC,eAAe,EAAEC,iBAAiB,QAA8B,gCAA4B;AAErG,SACEC,4BAA4B,EAC5BC,YAAY,EACZC,8BAA8B,QAEzB,4BAAwB;AAC/B,SACEC,mBAAmB,EACnBC,wBAAwB,EACxBC,iBAAiB,EACjBC,uBAAuB,EACvBC,cAAc,EACdC,sBAAsB,EACtBC,eAAe,EACfC,sBAAsB,EACtBC,QAAQ,QAIH,uCAAmC;AAC1C,SAASC,oBAAoB,EAAEC,kBAAkB,QAAQ,6BAAyB;AAClF,SAASC,gBAAgB,EAAEC,uBAAuB,QAAQ,8BAA0B;AAEpF,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SAASC,aAAa,EAAEC,qBAAqB,QAAQ,kCAA8B;AAEnF,SAASC,cAAc,EAAEC,oBAAoB,QAAQ,yBAAqB;AAC1E,SAASC,yBAAyB,QAAQ,+BAA2B;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,kFAAkF,GAClF,OAAO,SAASC,oBAAoBC,KAAa,EAAEC,KAAa;IAC9D,OAAO,CAAC,GAAG,EAAED,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../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-sections.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\nimport { REUSABLE_INSTANCE_COMPONENT_ID } from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport {\n aiPlanCreateFor,\n type AiBuildPlanRecord,\n type AiBuildPlanScreen,\n type AiBuildPlanSection,\n} from '../model/ai-build-plan'\nimport { aiPageTypeDefinition, parseAiPageJobInputs } from '../model/ai-page-job'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport { aiHomeScreenIds, aiHomeScreenNames, type AiSiteInventory } from '../model/ai-site-inventory'\nimport type { AiTool } from '../providers/contract'\nimport {\n AI_REASK_OFFENDING_MAX_CHARS,\n aiAnswerTree,\n aiNodeTreeContextFromInventory,\n type AiGenerationCheck,\n} from '../runtime/ai-doctrine'\nimport {\n aiSettleCutHeadings,\n aiSettleDisagreeingNodes,\n aiSettleGridItems,\n aiSettleMechanicalRules,\n aiSettlePlaceholderItems,\n detectCutLines,\n detectDisagreeingNodes,\n isAiLinkElement,\n validateAiDoctrineTree,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTreeContext,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { AI_INSTANCE_REF_PROP, validateAiNodeTree } from '../runtime/ai-node-tree'\nimport { aiPageLinkTarget, aiPageScrollInteraction } from '../runtime/ai-page-links'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE_CATALOG } from '../runtime/ai-palette.generated'\nimport { AI_REPEAT_KEY, expandAiRepeatedItems } from '../runtime/ai-repeated-items'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobBriefLine, aiPlanReferenceLines } from './ai-job-generation'\nimport { aiPlanItemCountViolations } from './ai-job-plan-conformance'\n\n/**\n * A page built one section at a time (AGL-2907): what one section pass asks\n * for, how its answer is held to the building rules as part of the page, and\n * how it joins the page.\n *\n * Pure: no Firestore and no provider, so the page step, its specs and the\n * evals read one definition of a section.\n *\n * ── Held as part of the page ─────────────────────────────────────────────\n *\n * A section is checked twice over, by validators the doctrine already has:\n * the palette validator on the section as the model wrote it, then the\n * doctrine's whole page check on the page built so far with the section\n * added. So the page's one main, its one h1 and its heading outline, repeats\n * across sections, and its weight against the page budget are held on every\n * pass, not only on the last. The violations name the section's own nodes,\n * by the ids the model wrote, so a re-ask quotes this section and nothing\n * else — the page is never sent back.\n *\n * ── A repeated item written once (AGL-3053) ──────────────────────────────\n *\n * Where the workspace keeps no reusable components, an answer writes a\n * repeated item once and lists its copies' values, and the check draws the\n * copies before either validator reads the section (`ai-repeated-items.ts`).\n * Both then read the section as the page stores it, so the page's rules hold\n * on every copy exactly as on an item written out in full, and a finding on a\n * copy names the node the model wrote. Where the workspace keeps components\n * the same shape is written around an instance (AGL-3024), so a section of\n * many cards costs its structure once on every plan; an item that places no\n * instance is still refused there.\n */\n\n/** The section root id a pass writes, from the job and the plan section's index. */\nexport function aiPageSectionNodeId(jobId: string, index: number): string {\n return `ai-${jobId.slice(0, 12)}-section-${index + 1}`\n}\n\n/** The strict tool a section arrives through. The node map rides as JSON text, as a page's does. */\nexport const AI_PAGE_SECTION_TOOL: AiTool = {\n name: 'submit_section',\n description: 'Submit one section of the page as one flat node map.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree'],\n properties: {\n tree: {\n type: 'string',\n description:\n 'The section as JSON: {\"rootId\": \"<id>\", \"nodes\": {\"<id>\": {\"componentId\": \"...\", \"props\": {...}, \"sx\": {...}, \"nodes\": [\"<child id>\", ...]}}}. The root is the document wrapper (componentId \"div\") holding one Section.',\n },\n },\n },\n}\n\n/** The page step's own instructions, cached after the doctrine, with the screen palette after them. */\nexport const AI_JOB_PAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build a web page one section at a time, in the order a confirmed plan gives. Each answer is ONE section: call submit_section with a flat node map whose root is the document wrapper (componentId \"div\") holding exactly one Section (section).',\n 'The first section is the top of the page and holds the page’s one h1, its title. Every later section opens with an h2, and headings below it step down one level at a time.',\n 'Place what the section’s plan line names. A component the site has is placed as an instance, never drawn again: componentId \"reusableInstance\", props {\"refId\": \"<component id>\", \"propValues\": {…}} filling the props the inventory lists. A form the site has is a Form (form) whose formId is that form’s id. Another page of the site is linked by its page id, with a Page Link (muiScreenLink) or a Button (muiButton) whose screenId is that id.',\n 'Where the request says the site keeps no reusable components, draw a repeated item in the section instead, written once. A form is only ever a saved one placed by its formId: where the plan line names no form, the section draws no form and no field of one.',\n 'Lay the section out with a Container, a Stack or a Grid (\"container\": true, \"spacing\": 3) of Grid items sized like \"xs:12 md:4\", and size nothing with a fixed width. Colors come from the theme’s palette tokens such as primary.main, spacing from the spacing scale, and type from the text variants.',\n 'The page renders inside the site’s layout, so a section is never a header, navigation or footer.',\n 'A picture is an Image (image) with alt text that says what it should show and no src, for the site owner to fill from the media library.',\n 'Write plain, specific copy in the site’s voice, with no filler. Where the brief leaves out a fact, such as a price, a phone number or an address, write the gap in square brackets instead of inventing it.',\n ].join('\\n'),\n },\n { text: AI_PALETTE_CATALOG.screen, cacheBreakpoint: true },\n]\n\n/** A plan reference as the request names it: the id with the name it was planned under. */\nfunction referenceOf(plan: AiJobPlan, ref: string): string {\n const label = plan.labels?.[ref]\n return label ? `${ref} (\"${label}\")` : ref\n}\n\n/**\n * A record template as a page pass reads it (AGL-3475): the dataset by name,\n * its base, and the fields its copy binds, as `{{item.<id>}}` with the name a\n * member gave each. A dataset the plan creates has no ids yet, so its tokens\n * are the field names it was planned with.\n */\nexport interface AiPageRecordTemplate {\n /** The dataset: an inventory id, or the plan's `new:<name>`. */\n dataset: string\n name: string\n base: string\n fields: Array<{ id: string; name: string }>\n /** The field holding each record's photo, where the dataset has one (AGL-3616). */\n imageField?: string\n}\n\n/** The record template a plan screen is, read against the site's datasets; null for a page that is one page. */\nexport function aiPageRecordTemplate(\n record: AiBuildPlanRecord | null | undefined,\n inventory: AiSiteInventory | null,\n plan: AiJobPlan,\n): AiPageRecordTemplate | null {\n if (!record) return null\n const row = inventory?.datasets.find((entry) => entry.id === record.dataset)\n if (row) {\n return {\n dataset: record.dataset,\n name: row.name,\n base: record.base,\n fields: row.fields.map((name, index) => ({ id: row.fieldIds?.[index] || name, name })),\n ...(row.imageField ? { imageField: row.imageField } : {}),\n }\n }\n const created = aiPlanCreateFor(plan, record.dataset)\n return {\n dataset: record.dataset,\n name: created?.name ?? plan.labels?.[record.dataset] ?? record.dataset,\n base: record.base,\n fields: (created?.fields ?? []).map((name) => ({ id: name, name })),\n }\n}\n\n/** Every token a record template's page may bind: each field, and `{{item.url}}`. */\nexport function aiPageRecordTokens(template: AiPageRecordTemplate | null): string[] {\n if (!template) return []\n return [...template.fields.map((field) => `{{item.${field.id}}}`), '{{item.url}}']\n}\n\n/** What a section request says on a record template's page. */\nexport function aiPageRecordLine(template: AiPageRecordTemplate): string {\n const fields = template.fields.length\n ? ` Its fields: ${template.fields\n .map((field) => (field.name === field.id ? `{{item.${field.id}}}` : `{{item.${field.id}}} (${field.name})`))\n .join(', ')}.`\n : ''\n // A record's photo is a picture's address, never its words (AGL-3616).\n const photo = template.imageField ? ` Each record's photo is {{item.${template.imageField}}}: the src of the page's main Image.` : ''\n return `This page is the record template of the dataset \"${template.name}\": it is served once per record, at /${template.base}/<record address>. Write what differs from one record to the next as {{item.<field>}}, never one record's copy, and write out what every record page shares.${fields}${photo}`\n}\n\n/**\n * A record template's section with the record's own photo (AGL-3616): where\n * the dataset keeps one and the page shows it nowhere yet, the section's\n * first Image that names no record's photo shows `{{item.<photo field>}}`,\n * so each record's page leads with its piece, its dish, its person, as its\n * card on the list does. Any other section, and a page already showing it,\n * is returned as it came. Pure.\n */\nexport function aiPageSectionWithRecordImage(\n section: AiPageSection,\n page: NodesMap,\n template: AiPageRecordTemplate | null,\n): AiPageSection {\n const field = template?.imageField\n if (!field) return section\n const token = `{{item.${field}}}`\n const showsIt = (nodes: NodesMap) =>\n Object.values(nodes as unknown as Record<string, { componentId?: unknown; props?: Record<string, unknown> }>).some(\n (node) => node?.componentId === 'image' && node.props?.['src'] === token,\n )\n if (showsIt(page) || showsIt(section.nodes)) return section\n const first = walkTree({ rootId: section.rootId, nodes: section.nodes as unknown as Record<string, AiDoctrineNode> }).find(\n ({ node }) => node.componentId === 'image',\n )\n if (!first) return section\n const node = (section.nodes as unknown as Record<string, Record<string, unknown>>)[first.id]\n const props = isRecord(node['props']) ? node['props'] : {}\n return {\n ...section,\n nodes: { ...section.nodes, [first.id]: { ...node, props: { ...props, src: token } } } as unknown as NodesMap,\n }\n}\n\n/**\n * What a record template's draft tells the member to do next. The binding is\n * a route, so the job never writes it (rule 13): the member saves it where\n * every record template is set up.\n */\nexport function aiPageRecordNote(template: AiPageRecordTemplate): string {\n return `This page is drafted as the record template of \"${template.name}\". To serve a page per record at /${template.base}/…, open Page Properties → Record pages and save its dataset, address and fields: the cards that list its records link those pages.`\n}\n\nexport interface AiPageSectionPromptInput {\n job: Pick<AiJob, 'brief' | 'inputs'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n index: number\n /** The most elements the section may carry at this pass's answer ceiling. */\n maxElements: number\n /**\n * Whether the workspace keeps reusable components (AGL-3030); `false`\n * asks for a repeated item drawn in the section. Absent is `true`. A form\n * is never drawn inline, whatever this says (AGL-3596).\n */\n reusableComponents?: boolean\n /** The dataset this page is the record template of; absent for a page that is one page. */\n record?: AiPageRecordTemplate | null\n /**\n * The site's other pages a link may go to by id (AGL-3596): a guided\n * start's pages are minted on its plan before any is built, so the Home\n * page is built before the Contact page its buttons go to exists.\n */\n linkablePages?: readonly AiLinkablePage[]\n}\n\n/** A page of the site a section may link by its id, built or still to come. */\nexport interface AiLinkablePage {\n id: string\n label: string\n slug: string\n}\n\n/**\n * The pages a section may link by id beyond the ones the site has built, and\n * the one page a link that names no destination can only mean (AGL-3596).\n * `planned` are a guided start's pages, minted on its plan (the input the\n * layout reads them from); `own` are this page's ids, which neither counts.\n * The link target is the site's one page that is neither its home nor this\n * page, where it has exactly one, built or planned: a two-page guided start's\n * Contact page, which its Home hero's \"Book an appointment\" goes to.\n */\nexport function aiPageLinkablePages(\n inventory: AiSiteInventory | null,\n planned: readonly AiLinkablePage[],\n own: ReadonlyArray<string | null | undefined>,\n): { linkablePages: AiLinkablePage[]; linkTarget: string | null } {\n const mine = new Set(own.filter((id): id is string => Boolean(id)))\n const home = new Set(aiHomeScreenIds(inventory))\n const isHome = (slug: string): boolean => slug.replace(/^\\/+|\\/+$/g, '') === ''\n const linkablePages = planned.filter((page) => !mine.has(page.id))\n const targets = new Set([\n ...(inventory?.screens ?? [])\n .filter((row) => !row.template && !home.has(row.id) && !isHome(row.slug))\n .map((row) => row.id),\n ...linkablePages.filter((page) => !isHome(page.slug)).map((page) => page.id),\n ])\n for (const id of mine) targets.delete(id)\n return { linkablePages, linkTarget: targets.size === 1 ? [...targets][0] : null }\n}\n\n/** The line a section request names the site's other pages in. */\nexport function aiPageSectionLinkablePagesLine(pages: readonly AiLinkablePage[]): string | null {\n if (!pages.length) return null\n const listed = pages.map((page) => `${page.label} (${page.slug || '/'}, id \"${page.id}\")`).join(', ')\n return `Other pages of this site: ${listed}. A button or link that goes to one sets its \"screenId\" to that id.`\n}\n\n/** What a section request says where the workspace keeps no reusable components. */\nexport const AI_PAGE_SECTION_INLINE_LINE =\n 'This site keeps no reusable components: write a repeated item once.'\n\n/** How a repeated item is written once, in the words a request and a re-ask share. */\nconst AI_PAGE_SECTION_REPEAT_SHAPE = `put {{1}}, {{2}}… where its copies differ, and give its outermost node \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]]`\n\n/**\n * How a repeated item is written once (AGL-3053): the item's subtree once,\n * with placeholders where its copies differ and their values listed, which\n * the section check draws into its copies (`ai-repeated-items.ts`). It rides\n * the request of a section whose plan line shows items on a workspace that\n * keeps no reusable components, and no other: a section with nothing to repeat\n * pays nothing for it, and the cached prefix every workspace shares says only\n * that a repeated item is written once.\n */\nexport const AI_PAGE_SECTION_REPEAT_LINE = `Write a repeated item once: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n\n/**\n * How a workspace that keeps reusable components writes a repeated item\n * (AGL-3143 §10): the shape a Free section writes, around an instance of a\n * component the section already places — the instance ONCE, `{{n}}` through\n * the values it fills, and one list of values a copy — rather than the item's\n * subtree drawn once per copy, or one instance node written per copy.\n *\n * Six cards written as six instance nodes spend their structure six times;\n * written once they spend it once, which is the difference between a section\n * that fits its ceiling and one that is cut off. A section stays ONE section\n * either way: splitting it would give the page a second h2 for the same idea,\n * which is not what the member asked for and not what its outline should say.\n *\n * ⛔ The repeated item is the GRID ITEM, not the instance. Measured live on\n * 2026-09-22: told only to \"place ONE instance … and give its outermost node\n * repeat\", the model made the instance itself the repeated node and hung it\n * straight off the Grid container. The section fitted — the ceiling failure\n * was gone — and the page was then refused by rule 12, which requires every\n * child of a Grid container to be a sized Grid item (AGL-3055). The line has\n * to name the wrapper, because \"outermost node\" reads as the instance when\n * the instance is all the request mentions.\n *\n * It rides the request of a section whose plan line shows items AND names a\n * record to place, on the same terms the repeat line rides a Free one: a\n * section with nothing to repeat, or nothing to repeat it FROM, pays nothing\n * for it.\n *\n * ## Why a paid section could not be built without it (AGL-3024)\n *\n * The Free path is reconciled at both ends — its plan is held to the sections\n * its wall pays for (AGL-3070) and its request is shown the repeat shape\n * (AGL-3053). The paid path was reconciled at neither: `AI_BUILD_PLAN_LIMITS`\n * lets a plan promise up to `items: 500` in one section, the pass that builds\n * it fits `aiJobPageSectionMaxElements` — fifteen at the balanced tier — and\n * the request said only how many elements to keep under, never how to get\n * there. A six-card grid measured live on 2026-09-21 was drawn inline, ran\n * past its ceiling, and was cut off; the re-ask then said to place an instance\n * \"of a component the site has\" without naming one, so it was cut off too, and\n * `AI_GENERATION_MAX_ATTEMPTS` ended the job with no page. A four-card grid on\n * the same site had fitted, which is why this went unseen. Naming the shape\n * was not enough on its own: `ai-repeated-items.ts` refused `repeat` outright\n * on such a workspace, so the only shape the request could ask for was the\n * expensive one.\n *\n * ⛔ This does NOT make the plan and the pass agree about what fits — a plan\n * may still promise more items than any ceiling can carry, and this line only\n * gives the pass its cheapest way to try. That bound belongs on the plan step\n * and is deliberately not taken here.\n */\nexport const AI_PAGE_SECTION_INSTANCE_LINE = `Write a repeated item once: put ONE instance of the component this section places inside ONE Grid item sized like \"xs:12 sm:6 md:4\", and repeat THAT GRID ITEM rather than the instance — every child of a Grid container is itself a Grid item. Put {{1}}, {{2}}… where the copies differ, and give the Grid item \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]].`\n\n/**\n * What a pass whose answer ran past its ceiling is told makes a section\n * smaller (AGL-3042): fewer elements, down to the budget the request gave,\n * shorter copy, and a repeated item drawn no more than once — placed as an\n * instance where the workspace keeps reusable components, and written once\n * where it keeps none (AGL-3053), with the shape spelled out, since a section\n * whose plan line showed no items was never told it. It rides the re-ask,\n * never the first request, so a pass that fits sends no byte more.\n */\nexport function aiPageSectionSmaller(input: Pick<AiPageSectionPromptInput, 'maxElements' | 'reusableComponents'>): string {\n return input.reusableComponents === false\n ? `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n : `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: put ONE instance of a component the site has inside ONE Grid item sized like \"xs:12 sm:6 md:4\", and repeat that Grid item — ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n}\n\n/** One pass's user turn: the page, the brief, the plan, this section and what is built above it. */\nexport function aiPageSectionPrompt(input: AiPageSectionPromptInput): string {\n const { job, plan, screen, index } = input\n const inputs = parseAiPageJobInputs(job.inputs)\n const type = typeof inputs === 'string' ? null : aiPageTypeDefinition(inputs.pageType)\n const section = screen.sections[index] as AiBuildPlanSection\n const places = section.uses.length\n ? ` It places ${section.uses.map((ref) => referenceOf(plan, ref)).join(', ')}.`\n : ''\n const items = section.items ? ` It shows ${section.items} items.` : ''\n const built = screen.sections.slice(0, index).map((entry, position) => `${position + 1}. ${entry.name}`)\n return [\n `Page: \"${screen.title}\" at ${screen.slug}`,\n ...(type ? [`Page type: ${type.purpose}`] : []),\n ...(input.record ? [aiPageRecordLine(input.record)] : []),\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n `Build section ${index + 1} of ${screen.sections.length}: \"${section.name}\".${places}${items}`,\n built.length\n ? `Already built, above it: ${built.join('; ')}. The page’s h1 is in section 1.`\n : 'Nothing is built yet: this section holds the page’s h1.',\n ...(input.reusableComponents === false\n ? [AI_PAGE_SECTION_INLINE_LINE, ...(section.items ? [AI_PAGE_SECTION_REPEAT_LINE] : [])]\n : section.items && section.uses.length\n ? [AI_PAGE_SECTION_INSTANCE_LINE]\n : []),\n ...(input.linkablePages?.length ? [aiPageSectionLinkablePagesLine(input.linkablePages) as string] : []),\n `Keep this section to at most ${input.maxElements} elements.`,\n ].join('\\n')\n}\n\n/** A validated section: its nodes keyed as the page stores them, its root under the page root. */\nexport interface AiPageSection {\n rootId: string\n nodes: NodesMap\n /** The page's weight with the section added, as the doctrine measured it. */\n load: AiLoadEstimate | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A page with nothing on it yet: the document wrapper. */\nexport function aiEmptyPage(): NodesMap {\n return {\n [CANVAS_ROOT_ELEMENT_ID]: {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n parentId: null,\n nodes: [],\n },\n } as unknown as NodesMap\n}\n\n/**\n * The page with a section in its plan position: after every section with a\n * lower index and before every one with a higher, the page's other children\n * — whatever a member placed — kept where they are. A section already on the\n * page is replaced, never doubled.\n */\nexport function aiPageWithSection(\n page: NodesMap,\n section: AiPageSection,\n sectionIds: readonly string[],\n): NodesMap {\n const nodes: Record<string, Record<string, unknown>> = {}\n const previous = (page as unknown as Record<string, Record<string, unknown>>)[section.rootId]\n const replaced = new Set<string>()\n if (previous) {\n for (const { id } of walkTree({\n rootId: section.rootId,\n nodes: page as unknown as Record<string, AiDoctrineNode>,\n })) {\n replaced.add(id)\n }\n }\n for (const [id, node] of Object.entries(page)) {\n if (!replaced.has(id)) nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n const root = nodes[CANVAS_ROOT_ELEMENT_ID] ?? (aiEmptyPage()[CANVAS_ROOT_ELEMENT_ID] as unknown as Record<string, unknown>)\n const children = (Array.isArray(root['nodes']) ? (root['nodes'] as string[]) : []).filter(\n (id) => id !== section.rootId,\n )\n const order = new Map(sectionIds.map((id, position) => [id, position]))\n const at = order.get(section.rootId) ?? sectionIds.length\n const before = children.findIndex((id) => (order.get(id) ?? -1) > at)\n children.splice(before === -1 ? children.length : before, 0, section.rootId)\n nodes[CANVAS_ROOT_ELEMENT_ID] = { ...root, nodes: children }\n for (const [id, node] of Object.entries(section.nodes)) {\n nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n return nodes as unknown as NodesMap\n}\n\n/**\n * What a tree generated against this inventory may reference, the brand it is\n * held to, where the workspace keeps no reusable components\n * (AGL-3030) that the page is built inline, the sections its plan names,\n * which a link may take a visitor to (AGL-3097), and the players its plan\n * lists for this page, the only ones it may embed (AGL-3433).\n */\nexport function aiPageCheckContext(\n inventory: AiSiteInventory | null,\n options: {\n reusableComponents?: boolean\n sections?: readonly string[]\n embeds?: AiDoctrineTreeContext['plannedEmbeds']\n /** A record template's tokens, which its links and images may name (AGL-3475). */\n recordTokens?: readonly string[]\n /** The site's pages still to be built that a link may go to by id (AGL-3596). */\n linkablePages?: readonly AiLinkablePage[]\n } = {},\n): AiDoctrineTreeContext {\n const tree = aiNodeTreeContextFromInventory(inventory)\n const screenIds = [...new Set([...(tree.screenIds ?? []), ...(options.linkablePages ?? []).map((page) => page.id)])]\n return {\n brand: inventory?.theme ? { colors: inventory.theme.colors, fonts: inventory.theme.fonts } : null,\n ...tree,\n ...(tree.screenIds || options.linkablePages?.length ? { screenIds } : {}),\n homeScreenIds: aiHomeScreenIds(inventory),\n homeLabels: aiHomeScreenNames(inventory),\n ...(options.reusableComponents === false ? { reusableComponents: false } : {}),\n ...(options.sections?.length ? { pageSections: options.sections } : {}),\n ...(options.embeds?.length ? { plannedEmbeds: options.embeds } : {}),\n ...(options.recordTokens?.length ? { bindingTokens: options.recordTokens } : {}),\n }\n}\n\nexport interface AiPageSectionCheckInput {\n /** The page as stored so far; an empty page on the first pass. */\n page: NodesMap\n /** Every section root id of the plan, in order. */\n sectionIds: readonly string[]\n index: number\n context: AiDoctrineTreeContext\n /**\n * The plan line this pass answers for: what it places by inventory id, and\n * how many items it promised, which the answer is held to (AGL-3024).\n */\n section: Pick<AiBuildPlanSection, 'name' | 'uses' | 'items'>\n inventory: AiSiteInventory | null\n /**\n * The one page a link that goes nowhere can only mean, where the site has\n * exactly one page besides its home and this one (AGL-3596): a guided\n * start's Contact page. Absent or `null`, such a link is re-asked.\n */\n linkTarget?: string | null\n}\n\n/** The parts of an answer the violations name, as the model wrote them, capped as the doctrine caps a re-ask. */\nfunction offendingOf(raw: unknown, violations: readonly AiDoctrineViolation[]): { offending?: Record<string, unknown> } {\n const rawNodes = isRecord(raw) && isRecord(raw['nodes']) ? raw['nodes'] : {}\n const offending: Record<string, unknown> = {}\n let used = 2\n for (const id of new Set(violations.flatMap((violation) => violation.nodeIds ?? []))) {\n if (rawNodes[id] === undefined) continue\n const size = JSON.stringify(rawNodes[id]).length + id.length + 4\n if (used + size > AI_REASK_OFFENDING_MAX_CHARS) break\n offending[id] = rawNodes[id]\n used += size\n }\n return Object.keys(offending).length ? { offending } : {}\n}\n\n/**\n * The check a section's answer is held to: a repeated item written once drawn\n * into its copies (AGL-3053), then the palette validator on the section, with\n * any line it cut at its ceiling refused (AGL-3076), a Grid container's items\n * sized where rule 12 has one answer (AGL-3596), the doctrine's page check\n * on the page with the section added, and the plan line — every component it\n * names placed as an instance, every form bound by its id (rule 7), and as\n * many items as it promised (AGL-3024). Violations\n * name the section's own nodes by the ids the MODEL wrote, and a copy's nodes\n * by the item's; one that names only nodes an earlier pass stored belongs to\n * the page rather than to this answer, and is left to the last pass (AGL-3078).\n */\nexport function aiPageSectionCheck(input: AiPageSectionCheckInput): AiGenerationCheck<AiPageSection> {\n const sectionId = input.sectionIds[input.index]\n const components = new Set((input.inventory?.components ?? []).map((row) => row.id))\n const forms = new Set((input.inventory?.forms ?? []).map((row) => row.id))\n return (answer) => {\n // A child named and never written, an element written and held by\n // nothing, and a heading whose first clause fits its ceiling are settled\n // where each has one reading (AGL-3596).\n const raw = aiSettleCutHeadings(aiSettleDisagreeingNodes(aiAnswerTree(answer)))\n // Before anything is drawn or dropped: a repeated item written and never\n // placed is content the section loses silently, and a child named and\n // never written ends the pass with nothing to answer (AGL-3143).\n const disagreeing = detectDisagreeingNodes(raw)\n if (disagreeing.length) {\n return { value: null, violations: disagreeing, ...offendingOf(raw, disagreeing) }\n }\n // A repeated item is drawn inline where the workspace keeps no reusable\n // components, and where this section's plan line places none (AGL-3596):\n // there is then no component it could be drawing by hand, and a paid\n // guided start's \"Why choose us\" was refused for rule 1 with nothing to place.\n const inline = input.context.reusableComponents === false || !input.section.uses.some((ref) => components.has(ref))\n const drawn = expandAiRepeatedItems(raw, { inline, noun: 'section' })\n if (drawn.ok === false) {\n return { value: null, violations: drawn.violations, ...offendingOf(raw, drawn.violations) }\n }\n // Every id below is the drawn tree's; a copy's leads back to the node the model wrote.\n const written = (id: string): string => drawn.sourceIds[id] ?? id\n const validated = validateAiNodeTree(drawn.tree, 'screen', input.context)\n if (validated.ok === false) {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: `tree-${validated.code}`,\n message: 'The answer could not be used as a section.',\n detail: validated.error,\n },\n ],\n }\n }\n const drawnNodes = isRecord(drawn.tree) && isRecord(drawn.tree['nodes']) ? drawn.tree['nodes'] : {}\n // A Grid container's items are sized, and an element straight in one is\n // put in an item, before the page check reads them: that rule has one\n // answer, the size its re-ask would name (AGL-3596). Read off the section\n // as the palette validator stored it, with what the model wrote beside it.\n const { nodes: settled } = aiSettleGridItems(\n { rootId: validated.rootId, nodes: validated.nodes as unknown as Record<string, AiDoctrineNode> },\n { written: (id) => drawnNodes[validated.sourceIds[id] ?? id] },\n )\n const wrapper = settled[validated.rootId] as AiDoctrineNode | undefined\n const top = (wrapper?.nodes ?? []).filter((id) => settled[id])\n const sectionNode = top.length === 1 ? settled[top[0]] : null\n if (!sectionNode || sectionNode.componentId !== 'section') {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'section-shape',\n message: 'Answer with exactly one Section element inside the document wrapper.',\n },\n ],\n }\n }\n\n // The section's root takes its plan id, so a pass run again finds it, and\n // hangs under the page root; every other minted id stays as minted.\n const minted = top[0]\n const modelIds: Record<string, string> = Object.fromEntries(\n Object.entries(validated.sourceIds).map(([id, source]) => [id, written(source)]),\n )\n modelIds[sectionId] = written(validated.sourceIds[minted] ?? minted)\n const sectionNodes: Record<string, Record<string, unknown>> = {}\n for (const { id, node } of walkTree({ rootId: minted, nodes: settled })) {\n const stored = { ...(node as unknown as Record<string, unknown>) }\n if (id === minted) {\n stored['$id'] = sectionId\n stored['parentId'] = CANVAS_ROOT_ELEMENT_ID\n } else if (stored['parentId'] === minted) {\n stored['parentId'] = sectionId\n }\n sectionNodes[id === minted ? sectionId : id] = stored\n }\n // What the model wrote of one of the section's nodes, by the id the page stores it under.\n const drawnIdOf = (stored: string): string =>\n validated.sourceIds[stored === sectionId ? minted : stored] ?? stored\n // A link that names a section of this page carries the platform's Scroll to\n // element interaction to that section's root, whose id is minted from the\n // plan before the section is built (AGL-3097).\n const sections = input.context.pageSections ?? []\n // A link that names no destination at all, on a site with one page it can\n // only mean, goes to that page (AGL-3596); one inside a form is the form's\n // own button, which rule 10 asks to take out.\n const inForm = (id: string): boolean => {\n for (let at = sectionNodes[id]?.['parentId']; typeof at === 'string'; at = sectionNodes[at]?.['parentId']) {\n if (sectionNodes[at]?.['componentId'] === 'form') return true\n }\n return false\n }\n for (const [id, node] of Object.entries(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (!isAiLinkElement(node['componentId']) || props['screenId'] || props['href']) continue\n const target = aiPageLinkTarget(drawnNodes[drawnIdOf(id)], sections)\n if (target?.kind === 'section') {\n node['interactions'] = [aiPageScrollInteraction(input.sectionIds[target.section], sections[target.section])]\n } else if (!target && input.linkTarget && !inForm(id)) {\n node['props'] = { ...props, screenId: input.linkTarget }\n }\n }\n // An item of a list that shows only placeholders, such as a testimonial\n // whose quote is `{{1}}`, is taken out where the list keeps a real one\n // (AGL-3827); any other placeholder is the re-ask's.\n const filled = aiSettlePlaceholderItems(\n { rootId: sectionId, nodes: sectionNodes as unknown as Record<string, AiDoctrineNode> },\n 'page',\n input.context,\n )\n for (const id of Object.keys(sectionNodes)) {\n if (filled.nodes[id]) sectionNodes[id] = filled.nodes[id] as unknown as Record<string, unknown>\n else delete sectionNodes[id]\n }\n const section: AiPageSection = { rootId: sectionId, nodes: sectionNodes as unknown as NodesMap, load: null }\n\n // An attribute a rule has one answer for is applied on the page with the\n // section added, since the first image and the one h1 are the page's\n // (AGL-3660). The section keeps what that settled of its own nodes; what\n // it settled of an earlier pass's is the last pass's to store.\n const settledPage = aiSettleMechanicalRules(\n {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n nodes: aiPageWithSection(input.page, section, input.sectionIds) as unknown as Record<string, AiDoctrineNode>,\n },\n 'page',\n )\n for (const id of Object.keys(sectionNodes)) {\n sectionNodes[id] = settledPage.nodes[id] as unknown as Record<string, unknown>\n }\n const page = settledPage.nodes as unknown as NodesMap\n const own = new Set(Object.keys(sectionNodes))\n // The page check reads the section as the page stores it, where the palette\n // validator has already dropped what it could not read, such as a\n // `container` written as text or a link's `scrollTo`; what the model wrote\n // of each of the section's nodes is read from the section as it was drawn\n // (AGL-3078). A link the page already carries to one of its section roots\n // goes there, whichever pass wrote it (AGL-3097).\n const report = validateAiDoctrineTree({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page }, 'page', {\n ...input.context,\n writtenNode: (id) => (own.has(id) ? drawnNodes[drawnIdOf(id)] : undefined),\n scrollTargetIds: input.sectionIds,\n })\n // The page check mints its ids afresh: its map leads back to the page's\n // ids, and the section's own lead back to the model's.\n const pageIds = report.tree?.sourceIds ?? {}\n const toModel = (id: string): string | null => {\n const stored = pageIds[id] ?? id\n return own.has(stored) ? (modelIds[stored] ?? stored) : null\n }\n // The page check reads the section as it is stored, where a line the\n // palette validator cut is already cut, so the cut is read from the\n // section's own validation, first (AGL-3076). Copies of one item name one\n // node the model wrote, once.\n //\n // A PASS ANSWERS ONLY FOR THE SECTION IT WROTE (AGL-3078). The page check\n // reads the whole page, so it also names nodes an earlier pass stored; the\n // model is not shown those and cannot mend them, so a finding that names\n // none of this section's nodes is not held against this answer. Dropping\n // it neither hides nor forgives it: the last pass runs the same check on\n // the finished page, where every node is the page's and the review names\n // each one and outlines it. Kept, such a finding would re-ask the model\n // for a node it never saw, refuse the same answer twice, and stop the page\n // with findings whose ids all filtered away — no node ids, and so no\n // outline either.\n const violations: AiDoctrineViolation[] = [\n ...detectCutLines(validated.repairs, drawnNodes, written),\n ...report.violations.flatMap((violation) => {\n if (!violation.nodeIds?.length) return [violation]\n const named = [...new Set(violation.nodeIds.map(toModel).filter((id): id is string => id !== null))]\n return named.length ? [{ ...violation, nodeIds: named }] : []\n }),\n ]\n\n const placed = new Set<string>()\n const bound = new Set<string>()\n for (const node of Object.values(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (node['componentId'] === REUSABLE_INSTANCE_COMPONENT_ID && typeof props[AI_INSTANCE_REF_PROP] === 'string') {\n placed.add(props[AI_INSTANCE_REF_PROP] as string)\n }\n if (node['componentId'] === 'form' && typeof props['formId'] === 'string') bound.add(props['formId'])\n }\n const missing = input.section.uses.filter(\n (ref) => (components.has(ref) && !placed.has(ref)) || (forms.has(ref) && !bound.has(ref)),\n )\n if (missing.length) {\n violations.push({\n rule: 7,\n code: 'plan-reuse-not-placed',\n message: `The confirmed plan places ${missing.join(', ')} in this section, and the section does not. Place each one by its id.`,\n })\n }\n // The count the plan promised, against the section as the page stores it\n // (AGL-3024): the prompt states it, and until now nothing read it back.\n violations.push(\n ...aiPlanItemCountViolations(input.section, {\n rootId: sectionId,\n nodes: sectionNodes as unknown as Record<string, AiDoctrineNode>,\n }),\n )\n\n return {\n value: { ...section, load: report.load },\n violations,\n ...offendingOf(raw, violations),\n }\n }\n}\n"],"names":["REUSABLE_INSTANCE_COMPONENT_ID","CANVAS_ROOT_ELEMENT_ID","aiPlanCreateFor","aiPageTypeDefinition","parseAiPageJobInputs","aiHomeScreenIds","aiHomeScreenNames","AI_REASK_OFFENDING_MAX_CHARS","aiAnswerTree","aiNodeTreeContextFromInventory","aiSettleCutHeadings","aiSettleDisagreeingNodes","aiSettleGridItems","aiSettleMechanicalRules","aiSettlePlaceholderItems","detectCutLines","detectDisagreeingNodes","isAiLinkElement","validateAiDoctrineTree","walkTree","AI_INSTANCE_REF_PROP","validateAiNodeTree","aiPageLinkTarget","aiPageScrollInteraction","AI_PALETTE_CATALOG","AI_REPEAT_KEY","expandAiRepeatedItems","aiJobBriefLine","aiPlanReferenceLines","aiPlanItemCountViolations","aiPageSectionNodeId","jobId","index","slice","AI_PAGE_SECTION_TOOL","name","description","strict","inputSchema","type","additionalProperties","required","properties","tree","AI_JOB_PAGE_INSTRUCTIONS","text","join","screen","cacheBreakpoint","referenceOf","plan","ref","label","labels","aiPageRecordTemplate","record","inventory","created","row","datasets","find","entry","id","dataset","base","fields","map","fieldIds","imageField","aiPageRecordTokens","template","field","aiPageRecordLine","length","photo","aiPageSectionWithRecordImage","section","page","token","showsIt","nodes","Object","values","some","node","componentId","props","first","rootId","isRecord","src","aiPageRecordNote","aiPageLinkablePages","planned","own","mine","Set","filter","Boolean","home","isHome","slug","replace","linkablePages","has","targets","screens","delete","linkTarget","size","aiPageSectionLinkablePagesLine","pages","listed","AI_PAGE_SECTION_INLINE_LINE","AI_PAGE_SECTION_REPEAT_SHAPE","AI_PAGE_SECTION_REPEAT_LINE","AI_PAGE_SECTION_INSTANCE_LINE","aiPageSectionSmaller","input","reusableComponents","maxElements","aiPageSectionPrompt","job","inputs","pageType","sections","places","uses","items","built","position","title","purpose","value","Array","isArray","aiEmptyPage","$id","parentId","aiPageWithSection","sectionIds","order","previous","replaced","add","entries","root","children","Map","at","get","before","findIndex","splice","aiPageCheckContext","options","screenIds","brand","theme","colors","fonts","homeScreenIds","homeLabels","pageSections","embeds","plannedEmbeds","recordTokens","bindingTokens","offendingOf","raw","violations","rawNodes","offending","used","flatMap","violation","nodeIds","undefined","JSON","stringify","keys","aiPageSectionCheck","sectionId","components","forms","answer","validated","report","disagreeing","inline","context","drawn","noun","ok","written","sourceIds","rule","code","message","detail","error","drawnNodes","settled","wrapper","top","sectionNode","minted","modelIds","fromEntries","source","sectionNodes","stored","drawnIdOf","inForm","target","kind","screenId","filled","load","settledPage","writtenNode","scrollTargetIds","pageIds","toModel","repairs","named","placed","bound","missing","push"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,8BAA8B,QAAQ,iDAAgD;AAC/F,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SACEC,eAAe,QAIV,4BAAw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,MAAMmI,QAAQ,IAAInI;QAClB,KAAK,MAAMZ,QAAQH,OAAOC,MAAM,CAACgI,cAAe;YAC9C,MAAM5H,QAAQG,SAASL,IAAI,CAAC,QAAQ,IAAIA,IAAI,CAAC,QAAQ,GAAG,CAAC;YACzD,IAAIA,IAAI,CAAC,cAAc,KAAKpF,kCAAkC,OAAOsF,KAAK,CAAClE,qBAAqB,KAAK,UAAU;gBAC7G8M,OAAOlF,GAAG,CAAC1D,KAAK,CAAClE,qBAAqB;YACxC;YACA,IAAIgE,IAAI,CAAC,cAAc,KAAK,UAAU,OAAOE,KAAK,CAAC,SAAS,KAAK,UAAU6I,MAAMnF,GAAG,CAAC1D,KAAK,CAAC,SAAS;QACtG;QACA,MAAM8I,UAAU9G,MAAM1C,OAAO,CAACmD,IAAI,CAAC9B,MAAM,CACvC,CAAC9C,MAAQ,AAACoI,WAAW/E,GAAG,CAACrD,QAAQ,CAAC+K,OAAO1H,GAAG,CAACrD,QAAUqI,MAAMhF,GAAG,CAACrD,QAAQ,CAACgL,MAAM3H,GAAG,CAACrD;QAEtF,IAAIiL,QAAQ3J,MAAM,EAAE;YAClBiG,WAAW2D,IAAI,CAAC;gBACdjC,MAAM;gBACNC,MAAM;gBACNC,SAAS,CAAC,0BAA0B,EAAE8B,QAAQtL,IAAI,CAAC,MAAM,qEAAqE,CAAC;YACjI;QACF;QACA,yEAAyE;QACzE,wEAAwE;QACxE4H,WAAW2D,IAAI,IACVxM,0BAA0ByF,MAAM1C,OAAO,EAAE;YAC1CY,QAAQ8F;YACRtG,OAAOkI;QACT;QAGF,OAAO;YACL7E,OAAO,aAAKzD;gBAAS8I,MAAM/B,OAAO+B,IAAI;;YACtChD;WACGF,YAAYC,KAAKC;IAExB;AACF"}
@@ -24,6 +24,7 @@ import { type AiJobAdmission } from './ai-job-admission';
24
24
  import { readAiDraftNodes } from './ai-job-drafts';
25
25
  import { AI_JOB_PAGE_SECTION_MAX_TOKENS, AI_JOB_PAGE_SECTION_TOKENS, AI_JOB_PAGE_STEP_BUDGET, AI_JOB_PAGE_STEP_MINIMUM_MS, aiJobPageSectionMaxTokens } from './ai-job-page-budget';
26
26
  import { aiLayoutStockPhotoSource } from './ai-layout-stock-photos';
27
+ import { type AiLayoutStartPage } from './ai-job-page-language';
27
28
  import { type AiSiteUnit } from './ai-job-site-step';
28
29
  import type { AiJobStepRunner } from './ai-job-text-step';
29
30
  import { aiJobStepRunnerFor } from './ai-jobs';
@@ -198,6 +199,19 @@ export declare function aiCopiedPageReview(firestore: FirebaseFirestore.Firestor
198
199
  * a step for, and this workspace may still make on this site (AGL-3031).
199
200
  */
200
201
  export declare const aiPageJobAdmission: AiJobAdmission;
202
+ /**
203
+ * The site's page a page of a build or a site starts from (AGL-3832): the
204
+ * plan's `duplicateOf`, by its name and its words, for the page's prompt.
205
+ * Only a page the site has, and never its starter home page, which is a
206
+ * placeholder rather than words of the owner's (AGL-3596) — nor an entry
207
+ * template, whose words are its records'. `null` when there is no such page
208
+ * or its words cannot be read: the page is then built from its plan alone.
209
+ */
210
+ export declare function aiPageStartPage(firestore: Parameters<typeof readAiDraftNodes>[0], input: {
211
+ hostId: string;
212
+ screen: Pick<AiBuildPlanScreen, 'duplicateOf'>;
213
+ inventory: Pick<AiSiteInventory, 'screens'>;
214
+ }, readNodes?: typeof readAiDraftNodes): Promise<AiLayoutStartPage | null>;
201
215
  /**
202
216
  * The library photos the job's other pages already show (AGL-3660): read
203
217
  * from the screen drafts a site job names for its page unit
@@ -26,7 +26,8 @@ import { aiPlanCapabilitiesForJob, aiPlanUncreatable } from "../model/ai-plan-ca
26
26
  import { aiSiteWords } from "../model/ai-site-job.js";
27
27
  import { aiModelForStep } from "../providers/routing.js";
28
28
  import { aiDoctrineNeedsInputMessage, runValidatedGeneration } from "../runtime/ai-doctrine.js";
29
- import { aiDanglingWord, aiSettleMechanicalRules, aiSettleUnrelatedScreenLinks, validateAiDoctrineTree } from "../runtime/ai-doctrine-validators.js";
29
+ import { aiDanglingWord, aiSettleMechanicalRules, aiSettlePlaceholderItems, aiSettleUnrelatedScreenLinks, validateAiDoctrineTree } from "../runtime/ai-doctrine-validators.js";
30
+ import { aiHasPlaceholderToken } from "../runtime/ai-placeholder-tokens.js";
30
31
  import { AI_SEO_FIELDS_MAX_TOKENS, generateSeoFields } from "../runtime/seo-fields.js";
31
32
  import { readSiteInventory } from "../runtime/site-inventory.js";
32
33
  import { registerAiJobAdmission } from "./ai-job-admission.js";
@@ -220,15 +221,16 @@ export const AI_JOB_PAGE_DELETED_COPY = 'The draft page was deleted while it was
220
221
  * A plan's listing value held to the length the SEO editor guides it to, cut
221
222
  * at a word. A cut that leaves a joining word or mark at the end ("…Practice
222
223
  * Areas and", "…across Springfield,") takes it off too, so a search result
223
- * never shows a phrase that stops mid-thought (AGL-3813).
224
- */ function clip(value, max) {
224
+ * never shows a phrase that stops mid-thought (AGL-3813), in the plan's
225
+ * language (AGL-3828): a Spanish title cut to "Pan dulce y" reads "Pan dulce".
226
+ */ function clip(value, max, language) {
225
227
  const text = value.trim();
226
228
  if (text.length <= max) return text;
227
229
  const cut = text.slice(0, max + 1);
228
230
  const space = cut.lastIndexOf(' ');
229
231
  let clipped = (space > max / 2 ? cut.slice(0, space) : text.slice(0, max)).replace(LISTING_TRAILING_JOINERS, '').trim();
230
232
  for(let guard = 0; guard < 6; guard += 1){
231
- const word = aiDanglingWord(clipped);
233
+ const word = aiDanglingWord(clipped, language);
232
234
  if (!word) break;
233
235
  const shorter = clipped.slice(0, clipped.length - word.length).replace(LISTING_TRAILING_JOINERS, '').trim();
234
236
  if (!shorter) break;
@@ -329,6 +331,31 @@ export const AI_JOB_PAGE_DELETED_COPY = 'The draft page was deleted while it was
329
331
  }
330
332
  } : {}));
331
333
  };
334
+ /**
335
+ * The site's page a page of a build or a site starts from (AGL-3832): the
336
+ * plan's `duplicateOf`, by its name and its words, for the page's prompt.
337
+ * Only a page the site has, and never its starter home page, which is a
338
+ * placeholder rather than words of the owner's (AGL-3596) — nor an entry
339
+ * template, whose words are its records'. `null` when there is no such page
340
+ * or its words cannot be read: the page is then built from its plan alone.
341
+ */ export async function aiPageStartPage(firestore, input, readNodes = readAiDraftNodes) {
342
+ const id = input.screen.duplicateOf;
343
+ const row = id ? input.inventory.screens.find((one)=>one.id === id && !one.template && !one.replaceable) : undefined;
344
+ if (!row) return null;
345
+ const stored = await readNodes(firestore, {
346
+ kind: 'screen',
347
+ hostId: input.hostId,
348
+ id: row.id
349
+ }).catch(()=>null);
350
+ const text = stored ? buildPageMarkdown({
351
+ nodes: stored.nodes,
352
+ rootId: CANVAS_ROOT_ELEMENT_ID
353
+ }).trim() : '';
354
+ return text ? {
355
+ label: row.name,
356
+ text
357
+ } : null;
358
+ }
332
359
  /**
333
360
  * The library photos the job's other pages already show (AGL-3660): read
334
361
  * from the screen drafts a site job names for its page unit
@@ -457,8 +484,9 @@ export function createAiJobPageStep(deps = {}) {
457
484
  // where the member saves the binding (AGL-3475).
458
485
  const record = aiPageRecordTemplate(screen.record, inventory, plan);
459
486
  const recordNote = record ? aiPageRecordNote(record) : null;
460
- // The plan starts from a copy of a screen the site has (rule 15): the copy
461
- // is the draft — unrouted, as every copy is — and nothing is generated.
487
+ // A page job's plan starts from a copy of a screen the site has (rule
488
+ // 15): the copy is the draft — unrouted, as every copy is — and nothing
489
+ // is generated.
462
490
  // Only a page is a page's start: a collection entry template's copy stays
463
491
  // a template, so a plan naming one builds the page instead.
464
492
  // A copy shows what its SOURCE shows, and this branch generates nothing.
@@ -474,14 +502,22 @@ export function createAiJobPageStep(deps = {}) {
474
502
  // (AGL-3596): the site's own placeholder is replaced by a page generated
475
503
  // from the plan, so a plan that names it as a start builds instead.
476
504
  const copiesStarter = Boolean(screen.duplicateOf && inventory.screens.some((row)=>row.id === screen.duplicateOf && row.replaceable));
477
- const sourceReview = !written && screen.duplicateOf && !copiesStarter ? await aiCopiedPageReview(firestore, {
505
+ // A page a build or a site makes (every one designed in the layout
506
+ // language) counts as built only once its plan's sections are in it,
507
+ // under the ids this step writes them by (AGL-3596). A copy holds its
508
+ // source's sections under the source's ids, so it never counts: a build
509
+ // that copied "Our Story" for its About page failed the page and left the
510
+ // copy behind (AGL-3832). Such a page is generated from its plan, its
511
+ // prompt shown the words of the page it starts from (`aiPageStartPage`).
512
+ const generatedWhole = aiJobUsesLayoutLanguage(job);
513
+ const sourceReview = !written && screen.duplicateOf && !copiesStarter && !generatedWhole ? await aiCopiedPageReview(firestore, {
478
514
  hostId,
479
515
  id: screen.duplicateOf,
480
516
  name,
481
517
  screen
482
518
  }) : null;
483
519
  const sourceShort = Boolean(sourceReview == null ? void 0 : sourceReview.findings.length);
484
- if (!written && !sourceShort && !copiesStarter && screen.duplicateOf && inventory.screens.some((row)=>row.id === screen.duplicateOf && !row.template)) {
520
+ if (!written && !sourceShort && !copiesStarter && !generatedWhole && screen.duplicateOf && inventory.screens.some((row)=>row.id === screen.duplicateOf && !row.template)) {
485
521
  const copy = await duplicate('screen', {
486
522
  orgId: job.orgId,
487
523
  hostId,
@@ -590,8 +626,9 @@ export function createAiJobPageStep(deps = {}) {
590
626
  // and stored (AGL-3660): this pass asks no model, so a page refused
591
627
  // here for one would be refused the same way on every Try again. A
592
628
  // Portfolio page whose opening photos all loaded eagerly was (2026-10-10).
593
- // And a link sent home for nothing is sent to the site's form, or left out (AGL-3729).
594
- const settle = (tree)=>aiSettleUnrelatedScreenLinks(aiSettleMechanicalRules(tree, 'page'), 'page', _extends({}, context, {
629
+ // And a link sent home for nothing is sent to the site's form, or left out (AGL-3729),
630
+ // and an item of a list that shows only placeholders is taken out where the list keeps a real one (AGL-3827).
631
+ const settle = (tree)=>aiSettleUnrelatedScreenLinks(aiSettlePlaceholderItems(aiSettleMechanicalRules(tree, 'page'), 'page', context), 'page', _extends({}, context, {
595
632
  ownScreenIds: [
596
633
  screen.id,
597
634
  draftId
@@ -692,8 +729,8 @@ export function createAiJobPageStep(deps = {}) {
692
729
  // listing cannot be written inside this pass's time on the model the
693
730
  // job runs.
694
731
  let values = {
695
- title: clip(screen.seoTitle, SCREEN_SEO_TEXT_GUIDANCE.title),
696
- description: clip(screen.seoDescription, SCREEN_SEO_TEXT_GUIDANCE.description)
732
+ title: clip(screen.seoTitle, SCREEN_SEO_TEXT_GUIDANCE.title, plan.language),
733
+ description: clip(screen.seoDescription, SCREEN_SEO_TEXT_GUIDANCE.description, plan.language)
697
734
  };
698
735
  if (// A listing is written from the page's own text, with no inventory
699
736
  // and so no lookup round.
@@ -732,10 +769,12 @@ export function createAiJobPageStep(deps = {}) {
732
769
  } : {}));
733
770
  spent = _extends({}, spent, aiGenerationSpent(result));
734
771
  if (result.status === 'ok') {
735
- var _result_value_title, _result_value_description;
772
+ // A written field that shows a placeholder keeps the plan's, which
773
+ // the plan's own check already held to rule 14 (AGL-3827).
774
+ const usable = (text)=>(text == null ? void 0 : text.trim()) && !aiHasPlaceholderToken(text) ? text.trim() : '';
736
775
  values = {
737
- title: ((_result_value_title = result.value.title) == null ? void 0 : _result_value_title.trim()) || values.title,
738
- description: ((_result_value_description = result.value.description) == null ? void 0 : _result_value_description.trim()) || values.description
776
+ title: usable(result.value.title) || values.title,
777
+ description: usable(result.value.description) || values.description
739
778
  };
740
779
  }
741
780
  }
@@ -774,6 +813,11 @@ export function createAiJobPageStep(deps = {}) {
774
813
  draftId
775
814
  ]
776
815
  });
816
+ const startsFrom = await aiPageStartPage(firestore, {
817
+ hostId,
818
+ screen,
819
+ inventory
820
+ });
777
821
  const result = await aiRunLayoutPage(_extends({
778
822
  job,
779
823
  plan,
@@ -783,7 +827,8 @@ export function createAiJobPageStep(deps = {}) {
783
827
  context,
784
828
  reusableComponents,
785
829
  inventory,
786
- model
830
+ model,
831
+ startsFrom
787
832
  }, signal ? {
788
833
  signal
789
834
  } : {}));
@@ -806,17 +851,21 @@ export function createAiJobPageStep(deps = {}) {
806
851
  job,
807
852
  draftId
808
853
  });
809
- const pictured = await aiResolveLayoutPictures(result.value.nodes, {
854
+ const photoWords = aiStockPhotoWordsOf(job);
855
+ const pictured = await aiResolveLayoutPictures(result.value.nodes, _extends({
810
856
  rootId: CANVAS_ROOT_ELEMENT_ID,
811
857
  sectionIds,
812
858
  sectionNames,
813
- seed,
859
+ seed
860
+ }, photoWords.language ? {
861
+ language: photoWords.language
862
+ } : {}, {
814
863
  source: ((_deps_stockPhotos = deps.stockPhotos) != null ? _deps_stockPhotos : aiLayoutStockPhotoSource)(_extends({
815
864
  hostId,
816
865
  uid: job.createdBy,
817
866
  seed,
818
867
  business: aiSiteWords(job.inputs).about
819
- }, aiStockPhotoWordsOf(job), {
868
+ }, photoWords, {
820
869
  sectionNames,
821
870
  jobId: aiOriginJobId(job)
822
871
  }, avoid.length ? {
@@ -824,7 +873,7 @@ export function createAiJobPageStep(deps = {}) {
824
873
  } : {}, signal ? {
825
874
  signal
826
875
  } : {}))
827
- });
876
+ }));
828
877
  if (!written) {
829
878
  // Never written once the job is canceled (AGL-3616).
830
879
  throwIfAiJobCanceled(signal);