@aglyn/plugins-ai 1.0.0-beta.238 → 1.0.0-beta.240

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 (88) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-job-links.js +8 -0
  3. package/src/lib/components/ai-job-links.js.map +1 -1
  4. package/src/lib/components/ai-job-requests.d.ts +5 -0
  5. package/src/lib/components/ai-job-requests.js +4 -2
  6. package/src/lib/components/ai-job-requests.js.map +1 -1
  7. package/src/lib/components/ai-jobs-store.d.ts +12 -0
  8. package/src/lib/components/ai-jobs-store.js +15 -0
  9. package/src/lib/components/ai-jobs-store.js.map +1 -1
  10. package/src/lib/components/ai-usage-meter-refresh.d.ts +35 -0
  11. package/src/lib/components/ai-usage-meter-refresh.js +63 -0
  12. package/src/lib/components/ai-usage-meter-refresh.js.map +1 -0
  13. package/src/lib/components/assist-panel.component.js +17 -1
  14. package/src/lib/components/assist-panel.component.js.map +1 -1
  15. package/src/lib/components/use-ai-usage-meter.d.ts +2 -0
  16. package/src/lib/components/use-ai-usage-meter.js +8 -3
  17. package/src/lib/components/use-ai-usage-meter.js.map +1 -1
  18. package/src/lib/jobs/ai-build-unit-outcome.d.ts +3 -1
  19. package/src/lib/jobs/ai-build-unit-outcome.js +19 -3
  20. package/src/lib/jobs/ai-build-unit-outcome.js.map +1 -1
  21. package/src/lib/jobs/ai-job-build-step.js +29 -2
  22. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  23. package/src/lib/jobs/ai-job-draft-ids.js +7 -2
  24. package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
  25. package/src/lib/jobs/ai-job-form-dataset.d.ts +100 -0
  26. package/src/lib/jobs/ai-job-form-dataset.js +161 -0
  27. package/src/lib/jobs/ai-job-form-dataset.js.map +1 -0
  28. package/src/lib/jobs/ai-job-form-step.d.ts +15 -3
  29. package/src/lib/jobs/ai-job-form-step.js +37 -9
  30. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  31. package/src/lib/jobs/ai-job-layout-language.js +7 -2
  32. package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
  33. package/src/lib/jobs/ai-job-page-language.d.ts +9 -0
  34. package/src/lib/jobs/ai-job-page-language.js +44 -4
  35. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  36. package/src/lib/jobs/ai-job-page-sections.js +13 -2
  37. package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
  38. package/src/lib/jobs/ai-job-page-step.js +32 -2
  39. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  40. package/src/lib/jobs/ai-job-plan-step.d.ts +18 -0
  41. package/src/lib/jobs/ai-job-plan-step.js +41 -4
  42. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  43. package/src/lib/jobs/ai-job-site-datasets.d.ts +183 -0
  44. package/src/lib/jobs/ai-job-site-datasets.js +530 -0
  45. package/src/lib/jobs/ai-job-site-datasets.js.map +1 -0
  46. package/src/lib/jobs/ai-job-site-step.d.ts +15 -8
  47. package/src/lib/jobs/ai-job-site-step.js +148 -29
  48. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  49. package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.d.ts +30 -0
  50. package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.js +637 -0
  51. package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.js.map +1 -0
  52. package/src/lib/layout-language/ai-layout-compiler.d.ts +10 -0
  53. package/src/lib/layout-language/ai-layout-compiler.js +93 -1
  54. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  55. package/src/lib/layout-language/ai-layout-gaps.js +17 -1
  56. package/src/lib/layout-language/ai-layout-gaps.js.map +1 -1
  57. package/src/lib/layout-language/ai-layout-listings.d.ts +32 -3
  58. package/src/lib/layout-language/ai-layout-listings.js +62 -9
  59. package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
  60. package/src/lib/layout-language/ai-layout-pictures.js +12 -4
  61. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
  62. package/src/lib/model/ai-build-job.d.ts +2 -0
  63. package/src/lib/model/ai-build-job.js +16 -1
  64. package/src/lib/model/ai-build-job.js.map +1 -1
  65. package/src/lib/model/ai-build-plan.d.ts +23 -3
  66. package/src/lib/model/ai-build-plan.js +47 -6
  67. package/src/lib/model/ai-build-plan.js.map +1 -1
  68. package/src/lib/model/ai-plan-capabilities.d.ts +7 -0
  69. package/src/lib/model/ai-plan-capabilities.js.map +1 -1
  70. package/src/lib/model/ai-site-job.d.ts +19 -2
  71. package/src/lib/model/ai-site-job.js +21 -6
  72. package/src/lib/model/ai-site-job.js.map +1 -1
  73. package/src/lib/runtime/ai-dataset-generation.d.ts +77 -0
  74. package/src/lib/runtime/ai-dataset-generation.js +127 -0
  75. package/src/lib/runtime/ai-dataset-generation.js.map +1 -0
  76. package/src/lib/runtime/ai-doctrine-validators.d.ts +84 -0
  77. package/src/lib/runtime/ai-doctrine-validators.js +307 -1
  78. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  79. package/src/lib/runtime/ai-doctrine.js +10 -4
  80. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  81. package/src/lib/runtime/ai-node-tree.d.ts +2 -0
  82. package/src/lib/runtime/ai-node-tree.js +16 -0
  83. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  84. package/src/lib/tools/ai-dataset-tool.d.ts +68 -0
  85. package/src/lib/tools/ai-dataset-tool.js +231 -0
  86. package/src/lib/tools/ai-dataset-tool.js.map +1 -0
  87. package/src/lib/usage/free-ai-credits-left.js +26 -2
  88. package/src/lib/usage/free-ai-credits-left.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-form-step.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 { throwIfAiJobCanceled } from './ai-job-cancel'\nimport {\n checkFormContract,\n formFieldsCanYieldAnEmail,\n} from '@aglyn/aglyn/app-utils/form-contract'\nimport {\n collectFormFieldNodeIds,\n FORM_COMPONENT_ID,\n FORM_FIELD_COMPONENT_ID,\n FORM_ID_PROP,\n formFieldDeclsFromNodes,\n formNodeIdIn,\n isMarketingConsentFieldName,\n MARKETING_CONSENT_FORM_FIELD,\n type FormDocument,\n type FormFieldDecl,\n type FormRouting,\n} from '@aglyn/aglyn/app-utils/forms'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { aiSiteSubmissions, aiSiteWords, type AiSiteSubmissions } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n aiDoctrineTreeTool,\n runValidatedGeneration,\n type AiValidatedTree,\n} from '../runtime/ai-doctrine'\nimport type { AiDoctrineTree, AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock, AiTool } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobPlanCreationsRefusal } from './ai-job-plan-creations'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The form step (AGL-2913): the generation step of a `form` job, run once a\n * member confirmed the job's plan.\n *\n * A form is two halves that must agree for its submissions to arrive: the\n * DESIGN a visitor fills in (`rootId`, `nodes`) and the DECLARATION the submit\n * route reads (`fields`, `consentFieldName`, `routing`). `checkFormContract`\n * is the rule that holds them together when a form is published. So the model\n * writes only the design, through `runValidatedGeneration('form', …)`, and\n * everything else is derived from it with the functions the publish paths\n * use:\n *\n * - `fields` is `formFieldDeclsFromNodes` over the design;\n * - a form that can yield an email address gets the platform's marketing\n * consent field (`MARKETING_CONSENT_FORM_FIELD`, the Forms editor preset's own\n * props) in place of any consent-like field the model drew, named as its\n * `consentFieldName`;\n * - `routing` is `{ lead: true }` when the answer proposes a lead, and\n * nothing otherwise. The stored routing has no place for an email list,\n * so a list proposal leaves the form on the Inbox and says, in the output's\n * `note`, how to enroll the people who tick consent — naming a list only\n * when the brief named one. The step reads no list, contact, CRM record or\n * submission, and sends none.\n *\n * The design is then stamped the way the Forms page's Create stamps one — the\n * form node bound to the new form's id, a canvas root above it — and\n * `checkFormContract` runs on it through `extend`, beside the doctrine's own\n * checks, so a design the contract would refuse at publish is asked for again\n * with the violation named.\n *\n * The form lands as a new draft (`ai-job-drafts.ts`) that no page places and\n * nothing promotes. A plan that starts from a copy of a form the site has gets\n * that copy, through the platform's duplicate module, and nothing generated —\n * and because that path reaches no model, `extend` never runs on it, so the\n * step asks `checkFormContract` of the stored copy itself before it reports\n * one (AGL-3024). A copy still bound to the form it was copied from is a\n * failure, never an output.\n *\n * Like the other generation steps, it runs on the job beat, never at an inline\n * door: it registers the least time its lookup rounds, its answer and its\n * re-ask need (AGL-3035), and runs without extended thinking under the routing\n * table's ceiling for a form, which is the doctrine's own.\n */\n\n/**\n * The longest answer a form may run to: the routing table's `job.form`\n * ceiling, which holds the largest form the output budget admits\n * (`ai-job-form-step.spec.ts` measures it) and is the doctrine's ceiling for\n * the form kind.\n */\nexport const AI_JOB_FORM_MAX_TOKENS = AI_ROUTING_TABLE['job.form'].maxTokens\n\n/**\n * The form step's time (AGL-3035, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at that ceiling on the tier `job.form` is served\n * from, fitted to what a beat can give a step.\n */\nexport const AI_JOB_FORM_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.form'],\n maxTokens: AI_JOB_FORM_MAX_TOKENS,\n})\n\n/** The least time one form step needs before it starts. */\nexport const AI_JOB_FORM_STEP_MINIMUM_MS = AI_JOB_FORM_STEP_BUDGET.minimumMs\n\n/** A form's name when the plan names none. */\nexport const AI_JOB_FORM_DEFAULT_NAME = 'New form'\n\n/** Where a proposal routes a form's submissions. */\nexport const AI_FORM_ROUTING_KINDS = ['inbox', 'list', 'lead'] as const\n\nexport type AiFormRoutingKind = (typeof AI_FORM_ROUTING_KINDS)[number]\n\n/** The most things a note says the brief asked for and a form cannot collect. */\nexport const AI_FORM_CANNOT_COLLECT_MAX = 3\n\nconst CANNOT_COLLECT_MAX_CHARS = 60\nconst LIST_NAME_MAX_CHARS = 80\n\n/** The node id the platform's consent field takes in a generated design. */\nexport const AI_FORM_CONSENT_NODE_ID = 'marketingConsentField'\n\n/** The form step's own instructions, cached after the doctrine. */\nexport const AI_JOB_FORM_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one form for a website: the fields a visitor fills in and the button that sends them. Answer with submit_form: the whole form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n 'The root is one Form (form) holding its Form Fields (formField) in the order a visitor fills them in. Give the form a submitLabel and a successMessage in the site’s voice.',\n 'Every field has a fieldName that is unique in the form and says what it holds in camelCase, such as fullName, email, phone or roofType; a label a visitor reads; and required only when the form cannot do its job without it. Use fieldType email for an email address, textarea for a description, select or radio with options for one choice, checkbox with options for several, and rating for a score. Put each option on its own line and never put a comma inside an option, because a comma starts a new one.',\n 'A form collects text, choices and ratings only. When the brief asks for something else, such as a file or photo upload, a signature or a payment, leave it out and name it in cannotCollect.',\n 'Never draw a marketing consent, newsletter or subscribe checkbox: when the form asks for an email address, the platform adds its own.',\n 'routing.kind is inbox when submissions only need to be read, lead when each one is a sales lead to follow up, and list when the people who send it should join an email list. routing.list is the list’s name only when the brief names one, and null otherwise.',\n ].join('\\n'),\n },\n]\n\nconst TREE_TOOL = aiDoctrineTreeTool('form')\n\n/**\n * The doctrine's form tree tool, with the two things a design cannot say: the\n * routing it proposes and what the brief asked for that no field can collect.\n * Structured fields only, so the step writes every sentence a person reads.\n */\nexport const AI_JOB_FORM_TOOL: AiTool = {\n name: TREE_TOOL.name,\n description:\n 'Submit the form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree', 'routing', 'cannotCollect'],\n properties: {\n tree: (TREE_TOOL.inputSchema['properties'] as Record<string, unknown>)['tree'],\n routing: {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'list'],\n properties: {\n kind: {\n type: 'string',\n enum: [...AI_FORM_ROUTING_KINDS],\n description:\n 'inbox: submissions are read in the Inbox. lead: each submission with an email address is a sales lead. list: the people who send it should join an email list.',\n },\n list: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: 'The email list the brief names, as it names it; null when it names none.',\n },\n },\n },\n cannotCollect: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'What the brief asks the form to collect that its field types cannot, a few words each, such as \"photo upload\"; empty when there is nothing.',\n },\n },\n },\n}\n\n/** The routing and the gaps an answer proposes, read defensively. */\nexport interface AiFormAnswer {\n routing: { kind: AiFormRoutingKind; list: string | null }\n cannotCollect: string[]\n}\n\n/**\n * What the person already decided about this form, where they were asked\n * (AGL-2918).\n *\n * Only the guided start asks, so only a scaffold's form unit carries one.\n * Whether a submission is a note to read or a lead to chase is a fact about\n * how a business runs, not something readable off a brief, so an answer here\n * BINDS the routing instead of joining the evidence the model weighs: a\n * person who said \"the Inbox\" and got a form filing leads would have been\n * asked a question for nothing.\n */\nexport interface AiFormDecisions {\n /** Where submissions go; `null` where nobody was asked. */\n submissions: AiSiteSubmissions | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction oneLine(value: string, max: number): string {\n return value.replace(/\\s+/g, ' ').trim().slice(0, max).trim()\n}\n\n/**\n * An answer's routing and gaps: an unknown kind is the Inbox, and the rest is\n * trimmed and capped. Where the person was asked where submissions go, their\n * answer replaces the model's proposal — the whole of the difference a\n * question makes.\n */\nexport function parseAiFormAnswer(\n answer: Record<string, unknown>,\n decisions: AiFormDecisions = { submissions: null },\n): AiFormAnswer {\n const routing = isRecord(answer['routing']) ? answer['routing'] : {}\n const proposed = (AI_FORM_ROUTING_KINDS as readonly unknown[]).includes(routing['kind'])\n ? (routing['kind'] as AiFormRoutingKind)\n : 'inbox'\n const kind: AiFormRoutingKind = decisions.submissions ?? proposed\n const list = typeof routing['list'] === 'string' ? oneLine(routing['list'], LIST_NAME_MAX_CHARS) : ''\n const seen = new Set<string>()\n const cannotCollect: string[] = []\n for (const entry of Array.isArray(answer['cannotCollect']) ? answer['cannotCollect'] : []) {\n if (typeof entry !== 'string') continue\n const text = oneLine(entry, CANNOT_COLLECT_MAX_CHARS)\n if (!text || seen.has(text.toLowerCase())) continue\n seen.add(text.toLowerCase())\n cannotCollect.push(text)\n if (cannotCollect.length === AI_FORM_CANNOT_COLLECT_MAX) break\n }\n return { routing: { kind, list: kind === 'list' && list ? list : null }, cannotCollect }\n}\n\n/** A generated form as its draft is written: the stamped design and what it declares. */\nexport interface AiFormDraft {\n /** The design as the Forms page's Create stores one: a canvas root above the bound form. */\n nodes: NodesMap\n rootId: string\n formNodeId: string\n fields: FormFieldDecl[]\n consentFieldName: string | null\n routing: FormRouting | null\n answer: AiFormAnswer\n}\n\n/**\n * The draft a validated design and its answer make: the form node bound to\n * `formId` and captioned `name`, no dataset binding, the platform's consent\n * field when the fields can yield an email address, the canvas root above,\n * and the declaration read off the result. Pure; the input tree is not\n * changed.\n */\nexport function aiFormDraft(\n tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>,\n answer: Record<string, unknown>,\n identity: { formId: string; name: string; decisions?: AiFormDecisions },\n): AiFormDraft {\n const parsed = parseAiFormAnswer(answer, identity.decisions ?? { submissions: null })\n const formNodeId = tree.rootId\n const nodes: NodesMap = {}\n for (const [id, node] of Object.entries(tree.nodes)) {\n nodes[id] = {\n ...node,\n props: { ...(node.props ?? {}) },\n nodes: Array.isArray(node.nodes) ? [...(node.nodes as string[])] : [],\n }\n }\n const form = nodes[formNodeId]\n let consentFieldName: string | null = null\n if (form?.componentId === FORM_COMPONENT_ID) {\n const props = form.props as Record<string, unknown>\n // A dataset binding decides where every submission is also written; it\n // stays the person's choice, made on the Form element.\n delete props['datasetId']\n delete props['datasetName']\n props[FORM_ID_PROP] = identity.formId\n props['formName'] = identity.name\n\n for (const id of collectFormFieldNodeIds(nodes as never, formNodeId)) {\n const fieldName = (nodes[id]?.props as Record<string, unknown> | undefined)?.['fieldName']\n if (!isMarketingConsentFieldName(fieldName)) continue\n const parent = nodes[String(nodes[id]?.parentId ?? '')]\n if (parent && Array.isArray(parent.nodes)) {\n parent.nodes = (parent.nodes as string[]).filter((child) => child !== id)\n }\n delete nodes[id]\n }\n if (formFieldsCanYieldAnEmail(formFieldDeclsFromNodes(nodes as never, formNodeId))) {\n nodes[AI_FORM_CONSENT_NODE_ID] = {\n $id: AI_FORM_CONSENT_NODE_ID,\n type: NodeType.NODE,\n componentId: FORM_FIELD_COMPONENT_ID,\n pluginId: AI_PALETTE[FORM_FIELD_COMPONENT_ID]?.pluginId,\n parentId: formNodeId,\n nodes: [],\n props: { ...MARKETING_CONSENT_FORM_FIELD },\n } as NodesMap[string]\n form.nodes = [...(form.nodes as string[]), AI_FORM_CONSENT_NODE_ID]\n consentFieldName = MARKETING_CONSENT_FORM_FIELD.fieldName\n }\n form.parentId = CANVAS_ROOT_ELEMENT_ID\n }\n nodes[CANVAS_ROOT_ELEMENT_ID] = {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n nodes: [formNodeId],\n } as NodesMap[string]\n return {\n nodes,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n formNodeId,\n fields: formFieldDeclsFromNodes(nodes as never, formNodeId),\n consentFieldName,\n routing: parsed.routing.kind === 'lead' ? { lead: true } : null,\n answer: parsed,\n }\n}\n\n/**\n * What a draft would break once published, as building-rule violations\n * (rule 3: a form is built with its fields, validation, consent and routing\n * together): the form contract's findings, a form with no field, and a list\n * proposal on a form that asks for no email address. Offending nodes are\n * named by the ids the model wrote.\n */\nexport function aiFormDraftViolations(\n draft: AiFormDraft,\n formId: string,\n sourceIds: Readonly<Record<string, string>>,\n): AiDoctrineViolation[] {\n const violations: AiDoctrineViolation[] = checkFormContract({\n form: {\n ...(draft.routing ? { routing: draft.routing } : {}),\n ...(draft.consentFieldName ? { consentFieldName: draft.consentFieldName } : {}),\n },\n formId,\n nodes: draft.nodes as never,\n formNodeId: draft.formNodeId,\n }).map((violation) => ({\n rule: 3 as const,\n code: violation.code,\n message: violation.message,\n ...(violation.nodeId ? { nodeIds: aiModelNodeIds([violation.nodeId], sourceIds) } : {}),\n }))\n if (!draft.fields.length) {\n violations.push({\n rule: 3,\n code: 'form-has-no-fields',\n message:\n 'This form has no named fields, so a visitor has nothing to fill in. Draw the fields the brief asks for.',\n })\n }\n if (draft.answer.routing.kind === 'list' && !formFieldsCanYieldAnEmail(draft.fields)) {\n violations.push({\n rule: 3,\n code: 'list-routing-has-no-email-field',\n message:\n 'This form proposes adding the people who send it to an email list, and it asks for no email address. Add an email field, or route its submissions to the Inbox.',\n paths: ['routing.kind'],\n })\n }\n return violations\n}\n\n/**\n * The door's check for `extend`, and the draft each admitted tree made: the\n * tree a generation returns is the object its last check saw, so the step\n * writes exactly the draft the contract passed.\n */\nexport function aiFormDraftCheck(identity: {\n formId: string\n name: string\n decisions?: AiFormDecisions\n}): {\n extend: (tree: AiValidatedTree, answer: Record<string, unknown>) => AiDoctrineViolation[]\n draftFor: (tree: AiValidatedTree) => AiFormDraft | undefined\n} {\n const drafts = new WeakMap<AiValidatedTree, AiFormDraft>()\n return {\n extend: (tree, answer) => {\n const draft = aiFormDraft(tree, answer, identity)\n drafts.set(tree, draft)\n return aiFormDraftViolations(draft, identity.formId, tree.sourceIds)\n },\n draftFor: (tree) => drafts.get(tree),\n }\n}\n\n/**\n * What a job says when the copy it asked for came back naming the form it\n * was copied FROM (AGL-3024). The contract's own sentence follows it and\n * names the consequence; this one names what to do about it.\n */\nexport const AI_FORM_COPY_UNBOUND_FAILURE =\n 'The copy of that form did not take on an identity of its own, so it is on ' +\n 'the site and not safe to collect with — delete it in Forms and try again.'\n\n/**\n * Whether the copy the platform just wrote is bound to ITSELF, asked of the\n * document rather than of the answer — `null` when it is, and the sentence a\n * person reads when it is not.\n *\n * ## Why a step that generated nothing still has something to check\n *\n * A \"creates X from a copy of Y\" plan reaches no model: the copy IS the\n * output, so there is no answer for the doctrine to refuse and `extend`\n * never runs. That left the one thing a copy can get wrong unasked. A form's\n * design names its own form inside itself, and a copy that kept the source's\n * name files every submission under the source — the console's form page\n * banners exactly this, and the job reported Done beside it.\n *\n * So the check is `checkFormContract`, the SAME function the console's\n * banner and the promotion route ask, run here on the stored copy. Not a\n * second predicate shaped like it: a copy this one passed and that one\n * refused would be a form the job called finished and the console called\n * broken, which is the state this exists to make impossible.\n *\n * Narrowed to `form-id-unbound`, and only that, because it is the one\n * violation duplication CAUSES. Every other code the contract can report —\n * an unnamed field, a consent field the design lost — the copy inherited\n * from a form the site already has and the member chose to copy; refusing\n * those would be refusing to copy a form they can already see.\n */\nexport async function aiFormCopyUnboundFailure(\n firestore: FirebaseFirestore.Firestore,\n copy: { hostId: string; formId: string },\n): Promise<string | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(copy.hostId)\n .collection('forms')\n .doc(copy.formId)\n .get()\n const form = (snapshot.data() ?? null) as Partial<FormDocument> | null\n const nodes = decodeStoredNodes(form?.nodes)\n const unbound = checkFormContract({\n form,\n formId: copy.formId,\n nodes: nodes as never,\n formNodeId: formNodeIdIn(nodes as never),\n }).find((violation) => violation.code === 'form-id-unbound')\n return unbound ? `${AI_FORM_COPY_UNBOUND_FAILURE} ${unbound.message}` : null\n}\n\n/**\n * The fields the confirmed plan gives the form, against the form a COPY\n * actually produced (AGL-3024); `null` when the copy keeps the plan, or when\n * the plan promised no field to keep.\n *\n * The fourth kind to need this, after the layout, the page and the component.\n * `aiFormCopyUnboundFailure` above already refuses the one violation\n * duplication CAUSES; this refuses the one duplication HIDES — a plan reading\n * \"start from the consultation form and add a case-type question\" getting the\n * consultation form and nothing else, reported as built.\n *\n * A field the plan names is matched on its name alone: a copy that collects\n * the answer under a different label is still collecting it, and this check\n * has no way to tell a renamed field from a missing one without guessing.\n */\nexport async function aiCopiedFormReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; formId: string; name: string; plan: AiJobPlan | null },\n): Promise<AiJobReview | null> {\n const promised = (aiPlanCreation(input.plan, 'form')?.fields ?? [])\n .map((field) => field.split(':')[0]?.trim().toLowerCase())\n .filter((field): field is string => Boolean(field))\n if (!promised.length) return null\n const snapshot = await firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('forms')\n .doc(input.formId)\n .get()\n if (!snapshot.exists) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the form the plan names, and this job could not read the copy back to check it collects what the plan gives it. Open the form and check it before you put it on a page.`,\n findings: [],\n }\n }\n const fields = (snapshot.get('fields') ?? []) as unknown[]\n const collected = new Set(\n fields\n .map((field) =>\n field && typeof field === 'object'\n ? String((field as Record<string, unknown>)['fieldName'] ?? (field as Record<string, unknown>)['name'] ?? '')\n : '',\n )\n .filter(Boolean)\n .map((name) => name.toLowerCase()),\n )\n const missing = promised.filter((name) => !collected.has(name))\n if (!missing.length) return null\n const one = missing.length === 1\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the form the plan names, and a copy is all it is: the plan gives it ${\n one ? 'a field' : 'fields'\n } the copy does not collect.`,\n violations: [\n {\n rule: null,\n code: 'plan-fields-missing',\n message: `The confirmed plan says this form collects ${missing.join(', ')}, and the copy collects ${\n collected.size ? [...collected].join(', ') : 'nothing'\n }. Add ${one ? 'it' : 'each of them'}, or the copy is the form it was copied from.`,\n },\n ],\n })\n}\n\n/**\n * What the form a short copy would have started from collects, as the build\n * that replaces the copy is told it (AGL-3143 §14): every field it asks for,\n * so the build keeps them beside what the plan adds. Empty when the form\n * cannot be read.\n */\nexport async function aiFormSourceLines(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string },\n): Promise<string[]> {\n const snapshot = await firestore.collection('hosts').doc(input.hostId).collection('forms').doc(input.id).get()\n const fields = snapshot.exists ? ((snapshot.get('fields') ?? []) as unknown[]) : []\n const asked = fields.flatMap((field) => {\n if (!field || typeof field !== 'object') return []\n const row = field as Record<string, unknown>\n const name = String(row['fieldName'] ?? row['name'] ?? '').trim()\n if (!name) return []\n const fieldType = row['fieldType'] ?? row['type']\n const type = typeof fieldType === 'string' ? ` (${fieldType}${row['required'] ? ', required' : ''})` : ''\n return [`${name}${type}`]\n })\n if (!asked.length) return []\n return [\n `The plan starts from a copy of the form \"${input.name}\", which lacks part of what the plan gives it. Build from it: it collects ${asked.join(', ')}. Keep each of those, and add what the plan adds.`,\n ]\n}\n\nfunction listOf(items: readonly string[]): string {\n return items.length < 2\n ? items.join('')\n : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\n/**\n * What the person decides next, in words the step writes itself: a lead\n * routing to keep or switch off, the list a proposal could not store, and what\n * the brief asked for that a form cannot collect. `null` when there is none.\n */\nexport function aiFormOutputNote(answer: AiFormAnswer): string | null {\n const sentences: string[] = []\n if (answer.routing.kind === 'lead') {\n sentences.push(\n 'Each submission with an email address also files a lead in CRM → Leads; you can switch that off on the form’s page.',\n )\n }\n if (answer.routing.kind === 'list') {\n const list = answer.routing.list ? `your \"${answer.routing.list}\" list` : 'an email list'\n sentences.push(\n `Submissions arrive in the Inbox. To add the people who tick \"${MARKETING_CONSENT_FORM_FIELD.label}\" to ${list}, add an action on form submissions in Automation that enrolls them.`,\n )\n }\n if (answer.cannotCollect.length) {\n sentences.push(\n `Forms cannot collect ${listOf(answer.cannotCollect)} yet, so this form leaves ${\n answer.cannotCollect.length === 1 ? 'it' : 'them'\n } out.`,\n )\n }\n return sentences.length ? sentences.join(' ') : null\n}\n\n/**\n * The form job as the generation's user turn: the name, who fills the form\n * in, the brief, and the confirmed plan.\n *\n * Who the form is for (AGL-2918) is the answer a contact form's FIELDS turn\n * on — a trades business asks where the work is, a practice asks what the\n * appointment is about — and it is not something a brief about a whole site\n * says in a place the form can find. It rides here, in the turn, because it\n * is one site's own words.\n *\n * Where submissions go rides here too, and it is NOT a hint: the step binds\n * the routing to it whatever the model answers. It is stated so the model\n * does not spend its answer proposing something that will be replaced, and\n * so a form told its submissions are leads asks for the address that makes\n * one.\n */\nexport function aiJobFormPrompt(\n job: Pick<AiJob, 'brief'>,\n plan: AiJobPlan | null,\n name: string,\n context: { audience?: string; submissions?: AiSiteSubmissions | null } = {},\n): string {\n const audience = (context.audience ?? '').trim()\n return [\n `Form name: ${name}`,\n audience ? `The people who fill it in: ${audience}` : '',\n context.submissions ? `Where its submissions go: ${SUBMISSION_WORDS[context.submissions]}` : '',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** What each decided routing is, said to the model the way the tool says it. */\nconst SUBMISSION_WORDS: Record<AiSiteSubmissions, string> = {\n inbox: 'the Inbox, to be read — routing.kind is inbox',\n lead: 'the Inbox, and each one with an email address is a sales lead — routing.kind is lead',\n}\n\n/**\n * A form job is admitted for a site of the job's own org whose plan has\n * forms, with a form to spare, and confirmed only for a plan that creates\n * nothing but the form: a form places nothing another job builds\n * (AGL-3143 §15).\n */\nexport const aiFormJobAdmission: AiJobAdmission = (context) =>\n aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'form',\n org: context.org,\n ownCheck: (hostId) => aiJobPlanCreationsRefusal('form', context, hostId),\n })\n\nexport interface AiJobFormStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n}\n\nexport function createAiJobFormStep(deps: AiJobFormStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a form job names no site, and its admission refuses one')\n const output = (\n draft: AiDraftRecord,\n extra: { load?: AiLoadEstimate | null; note?: string | null } = {},\n ): AiJobOutput => ({\n resource: 'form',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(extra.load ? { load: extra.load } : {}),\n ...(extra.note ? { note: extra.note } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.form') ?? aiModelForStep('job.form')\n\n // A run cut off after its draft was written reports that draft, found by the id the job recorded.\n const draftId = aiJobDraftId(job, 'form')\n const written = await readAiDraft(firestore, { kind: 'form', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n ])\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'form')\n const name = creation?.name || AI_JOB_FORM_DEFAULT_NAME\n\n // The plan starts from a copy of a form the site has (rule 15): the copy\n // is the draft, and nothing is generated. A source gone since the plan\n // was made is built from the brief instead, and one that does not collect\n // a field the plan gives the form is built from the plan, told what the\n // source collects (AGL-3143 §14): copying it could only end in the review\n // below. A source this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.forms.find((form) => form.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedFormReview(firestore, { hostId, formId: source.id, name: source.name, plan })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n const sourceLines =\n source && sourceShort ? await aiFormSourceLines(firestore, { hostId, id: source.id, name: source.name }) : []\n if (creation?.duplicateOf && source && !sourceShort) {\n const copy = await duplicate('form', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n // The copy is the whole output, so the contract is asked of it here\n // or nowhere: a copy still bound to its source is not a form this\n // job may report as built (AGL-3024).\n const unbound = await aiFormCopyUnboundFailure(firestore, { hostId, formId: copy.id })\n if (unbound) return { ...aiUnspentOutcome(model), failure: unbound }\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // And the one duplication hides: what the plan promised of the copy,\n // read back (AGL-3024). This branch generates nothing, so nothing\n // else can answer for it.\n const review = await aiCopiedFormReview(firestore, {\n hostId,\n formId: copy.id,\n name: copy.name,\n plan,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: copy.versionId, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'form', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n // What the person answered about this form, where they were asked\n // (AGL-2918): a scaffold's form unit carries the guided start's inputs.\n const decisions: AiFormDecisions = { submissions: aiSiteSubmissions(job.inputs) }\n const { audience } = aiSiteWords(job.inputs)\n const check = aiFormDraftCheck({ formId: draftId, name, decisions })\n const result = await runValidatedGeneration('form', {\n step: 'job.form',\n model,\n instructions: AI_JOB_FORM_INSTRUCTIONS,\n inventory,\n messages: [\n {\n role: 'user',\n content: [\n aiJobFormPrompt(job, plan, name, {\n audience,\n submissions: decisions.submissions,\n }),\n ...sourceLines,\n ].join('\\n'),\n },\n ],\n tool: AI_JOB_FORM_TOOL,\n maxTokens: AI_JOB_FORM_STEP_BUDGET.maxTokens(model),\n thinking: 'off',\n extend: check.extend,\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n const draft = check.draftFor(result.value)\n if (!draft) throw new Error('a form the doctrine admitted has no draft from its check')\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const write = await writeAiDraft(firestore, {\n kind: 'form',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: draft.nodes,\n form: {\n rootId: draft.rootId,\n formNodeId: draft.formNodeId,\n fields: draft.fields,\n consentFieldName: draft.consentFieldName,\n routing: draft.routing,\n },\n now,\n })\n if (write.ok === false) {\n if (write.status === 404) throw new Error(`site ${hostId} vanished while its form was generated`)\n return { ...spent, review: aiLimitReview(write.error) }\n }\n // What the person decides next, then the facts the brief did not give (AGL-3056).\n const note = [\n aiFormOutputNote(draft.answer),\n aiBracketedFactsNote({\n tree: { rootId: result.value.rootId, nodes: result.value.nodes as unknown as AiDoctrineTree['nodes'] },\n inventory,\n }),\n ]\n .filter(Boolean)\n .join(' ')\n return {\n ...spent,\n outputs: [output(write, { load: result.value.load, note })],\n }\n }\n}\n\nexport const runAiJobFormStep = createAiJobFormStep()\n\n/** Registers the form step and the check a form job passes before it is created or resumed. */\nexport function registerAiFormJob(): void {\n registerAiJobStep('form', runAiJobFormStep, { minimumMs: AI_JOB_FORM_STEP_MINIMUM_MS })\n registerAiJobAdmission('form', aiFormJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","checkFormContract","formFieldsCanYieldAnEmail","collectFormFieldNodeIds","FORM_COMPONENT_ID","FORM_FIELD_COMPONENT_ID","FORM_ID_PROP","formFieldDeclsFromNodes","formNodeIdIn","isMarketingConsentFieldName","MARKETING_CONSENT_FORM_FIELD","decodeStoredNodes","CANVAS_ROOT_ELEMENT_ID","NodeType","duplicateResource","aiSiteSubmissions","aiSiteWords","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","AI_PALETTE","readSiteInventory","registerAiJobAdmission","aiJobPlanCreationsRefusal","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","writeAiDraft","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlanCreation","aiPlanReferenceLines","aiUnspentOutcome","aiJobStepBudget","registerAiJobStep","AI_JOB_FORM_MAX_TOKENS","maxTokens","AI_JOB_FORM_STEP_BUDGET","tier","AI_JOB_FORM_STEP_MINIMUM_MS","minimumMs","AI_JOB_FORM_DEFAULT_NAME","AI_FORM_ROUTING_KINDS","AI_FORM_CANNOT_COLLECT_MAX","CANNOT_COLLECT_MAX_CHARS","LIST_NAME_MAX_CHARS","AI_FORM_CONSENT_NODE_ID","AI_JOB_FORM_INSTRUCTIONS","text","join","TREE_TOOL","AI_JOB_FORM_TOOL","name","description","strict","inputSchema","type","additionalProperties","required","properties","tree","routing","kind","enum","list","anyOf","cannotCollect","items","isRecord","value","Array","isArray","oneLine","max","replace","trim","slice","parseAiFormAnswer","answer","decisions","submissions","proposed","includes","seen","Set","entry","has","toLowerCase","add","push","length","aiFormDraft","identity","parsed","formNodeId","rootId","nodes","id","node","Object","entries","props","form","consentFieldName","componentId","formId","fieldName","parent","String","parentId","filter","child","$id","NODE","pluginId","fields","lead","aiFormDraftViolations","draft","sourceIds","violations","map","violation","rule","code","message","nodeId","nodeIds","paths","aiFormDraftCheck","drafts","WeakMap","extend","set","draftFor","get","AI_FORM_COPY_UNBOUND_FAILURE","aiFormCopyUnboundFailure","firestore","copy","snapshot","collection","doc","hostId","data","unbound","find","aiCopiedFormReview","input","promised","plan","field","split","Boolean","exists","reason","findings","collected","missing","one","size","aiFormSourceLines","asked","flatMap","row","fieldType","listOf","aiFormOutputNote","sentences","label","aiJobFormPrompt","job","context","audience","SUBMISSION_WORDS","inbox","aiFormJobAdmission","orgId","org","ownCheck","createAiJobFormStep","deps","readInventory","duplicate","now","signal","modelFor","orgSnapshot","Error","output","extra","resource","versionId","hostSubdomain","load","note","model","draftId","written","outputs","inventory","Promise","all","creation","source","duplicateOf","forms","undefined","sourceReview","sourceShort","sourceLines","sourceId","uid","createdBy","attemptKey","ok","failure","review","status","error","allowance","inputs","check","result","step","instructions","messages","role","content","tool","thinking","spent","refused","write","runAiJobFormStep","registerAiFormJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ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AAEmC,QAAQgI,OAAO1J,KAAK,CAAC0B,MAAM;oBAAEC,OAAO+H,OAAO1J,KAAK,CAAC2B,KAAK;gBAAuC;gBACrGwG;YACF;SACD,CACE1F,MAAM,CAAC2C,SACPxG,IAAI,CAAC;QACR,OAAO,aACFsL;YACHhC,SAAS;gBAACV,OAAO4C,OAAO;oBAAEvC,MAAM6B,OAAO1J,KAAK,CAAC6H,IAAI;oBAAEC;gBAAK;aAAG;;IAE/D;AACF;AAEA,OAAO,MAAMuC,mBAAmBtD,sBAAqB;AAErD,6FAA6F,GAC7F,OAAO,SAASuD;IACdzM,kBAAkB,QAAQwM,kBAAkB;QAAElM,WAAWD;IAA4B;IACrFxB,uBAAuB,QAAQiK;AACjC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-form-step.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 { throwIfAiJobCanceled } from './ai-job-cancel'\nimport {\n checkFormContract,\n formFieldsCanYieldAnEmail,\n} from '@aglyn/aglyn/app-utils/form-contract'\nimport {\n collectFormFieldNodeIds,\n FORM_COMPONENT_ID,\n FORM_FIELD_COMPONENT_ID,\n FORM_ID_PROP,\n formFieldDeclsFromNodes,\n formNodeIdIn,\n isMarketingConsentFieldName,\n MARKETING_CONSENT_FORM_FIELD,\n type FormDocument,\n type FormFieldDecl,\n type FormRouting,\n} from '@aglyn/aglyn/app-utils/forms'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { aiSiteSubmissions, aiSiteWords, type AiSiteSubmissions } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n aiDoctrineTreeTool,\n runValidatedGeneration,\n type AiValidatedTree,\n} from '../runtime/ai-doctrine'\nimport type { AiDoctrineTree, AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock, AiTool } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport {\n AI_FORM_DATASET_MADE_INPUT,\n aiBindFormToDataset,\n aiFormDatasetNote,\n aiFormDatasetPromptLine,\n aiReadFormDataset,\n type AiFormDataset,\n type AiFormDatasetBinding,\n type AiFormDatasetReadDeps,\n} from './ai-job-form-dataset'\nimport { aiJobPlanCreationsRefusal } from './ai-job-plan-creations'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The form step (AGL-2913): the generation step of a `form` job, run once a\n * member confirmed the job's plan.\n *\n * A form is two halves that must agree for its submissions to arrive: the\n * DESIGN a visitor fills in (`rootId`, `nodes`) and the DECLARATION the submit\n * route reads (`fields`, `consentFieldName`, `routing`). `checkFormContract`\n * is the rule that holds them together when a form is published. So the model\n * writes only the design, through `runValidatedGeneration('form', …)`, and\n * everything else is derived from it with the functions the publish paths\n * use:\n *\n * - `fields` is `formFieldDeclsFromNodes` over the design;\n * - a form that can yield an email address gets the platform's marketing\n * consent field (`MARKETING_CONSENT_FORM_FIELD`, the Forms editor preset's own\n * props) in place of any consent-like field the model drew, named as its\n * `consentFieldName`;\n * - `routing` is `{ lead: true }` when the answer proposes a lead, and\n * nothing otherwise. The stored routing has no place for an email list,\n * so a list proposal leaves the form on the Inbox and says, in the output's\n * `note`, how to enroll the people who tick consent — naming a list only\n * when the brief named one. The step reads no list, contact, CRM record or\n * submission, and sends none.\n *\n * The design is then stamped the way the Forms page's Create stamps one — the\n * form node bound to the new form's id, a canvas root above it — and\n * `checkFormContract` runs on it through `extend`, beside the doctrine's own\n * checks, so a design the contract would refuse at publish is asked for again\n * with the violation named.\n *\n * The form lands as a new draft (`ai-job-drafts.ts`) that no page places and\n * nothing promotes. A plan that starts from a copy of a form the site has gets\n * that copy, through the platform's duplicate module, and nothing generated —\n * and because that path reaches no model, `extend` never runs on it, so the\n * step asks `checkFormContract` of the stored copy itself before it reports\n * one (AGL-3024). A copy still bound to the form it was copied from is a\n * failure, never an output.\n *\n * Like the other generation steps, it runs on the job beat, never at an inline\n * door: it registers the least time its lookup rounds, its answer and its\n * re-ask need (AGL-3035), and runs without extended thinking under the routing\n * table's ceiling for a form, which is the doctrine's own.\n */\n\n/**\n * The longest answer a form may run to: the routing table's `job.form`\n * ceiling, which holds the largest form the output budget admits\n * (`ai-job-form-step.spec.ts` measures it) and is the doctrine's ceiling for\n * the form kind.\n */\nexport const AI_JOB_FORM_MAX_TOKENS = AI_ROUTING_TABLE['job.form'].maxTokens\n\n/**\n * The form step's time (AGL-3035, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at that ceiling on the tier `job.form` is served\n * from, fitted to what a beat can give a step.\n */\nexport const AI_JOB_FORM_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.form'],\n maxTokens: AI_JOB_FORM_MAX_TOKENS,\n})\n\n/** The least time one form step needs before it starts. */\nexport const AI_JOB_FORM_STEP_MINIMUM_MS = AI_JOB_FORM_STEP_BUDGET.minimumMs\n\n/** A form's name when the plan names none. */\nexport const AI_JOB_FORM_DEFAULT_NAME = 'New form'\n\n/** Where a proposal routes a form's submissions. */\nexport const AI_FORM_ROUTING_KINDS = ['inbox', 'list', 'lead'] as const\n\nexport type AiFormRoutingKind = (typeof AI_FORM_ROUTING_KINDS)[number]\n\n/** The most things a note says the brief asked for and a form cannot collect. */\nexport const AI_FORM_CANNOT_COLLECT_MAX = 3\n\nconst CANNOT_COLLECT_MAX_CHARS = 60\nconst LIST_NAME_MAX_CHARS = 80\n\n/** The node id the platform's consent field takes in a generated design. */\nexport const AI_FORM_CONSENT_NODE_ID = 'marketingConsentField'\n\n/** The form step's own instructions, cached after the doctrine. */\nexport const AI_JOB_FORM_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one form for a website: the fields a visitor fills in and the button that sends them. Answer with submit_form: the whole form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n 'The root is one Form (form) holding its Form Fields (formField) in the order a visitor fills them in. Give the form a submitLabel and a successMessage in the site’s voice.',\n 'Every field has a fieldName that is unique in the form and says what it holds in camelCase, such as fullName, email, phone or roofType; a label a visitor reads; and required only when the form cannot do its job without it. Use fieldType email for an email address, textarea for a description, select or radio with options for one choice, checkbox with options for several, and rating for a score. Put each option on its own line and never put a comma inside an option, because a comma starts a new one.',\n 'A form collects text, choices and ratings only. When the brief asks for something else, such as a file or photo upload, a signature or a payment, leave it out and name it in cannotCollect.',\n 'Never draw a marketing consent, newsletter or subscribe checkbox: when the form asks for an email address, the platform adds its own.',\n 'routing.kind is inbox when submissions only need to be read, lead when each one is a sales lead to follow up, and list when the people who send it should join an email list. routing.list is the list’s name only when the brief names one, and null otherwise.',\n ].join('\\n'),\n },\n]\n\nconst TREE_TOOL = aiDoctrineTreeTool('form')\n\n/**\n * The doctrine's form tree tool, with the two things a design cannot say: the\n * routing it proposes and what the brief asked for that no field can collect.\n * Structured fields only, so the step writes every sentence a person reads.\n */\nexport const AI_JOB_FORM_TOOL: AiTool = {\n name: TREE_TOOL.name,\n description:\n 'Submit the form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree', 'routing', 'cannotCollect'],\n properties: {\n tree: (TREE_TOOL.inputSchema['properties'] as Record<string, unknown>)['tree'],\n routing: {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'list'],\n properties: {\n kind: {\n type: 'string',\n enum: [...AI_FORM_ROUTING_KINDS],\n description:\n 'inbox: submissions are read in the Inbox. lead: each submission with an email address is a sales lead. list: the people who send it should join an email list.',\n },\n list: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: 'The email list the brief names, as it names it; null when it names none.',\n },\n },\n },\n cannotCollect: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'What the brief asks the form to collect that its field types cannot, a few words each, such as \"photo upload\"; empty when there is nothing.',\n },\n },\n },\n}\n\n/** The routing and the gaps an answer proposes, read defensively. */\nexport interface AiFormAnswer {\n routing: { kind: AiFormRoutingKind; list: string | null }\n cannotCollect: string[]\n}\n\n/**\n * What the person already decided about this form, where they were asked\n * (AGL-2918).\n *\n * Only the guided start asks, so only a scaffold's form unit carries one.\n * Whether a submission is a note to read or a lead to chase is a fact about\n * how a business runs, not something readable off a brief, so an answer here\n * BINDS the routing instead of joining the evidence the model weighs: a\n * person who said \"the Inbox\" and got a form filing leads would have been\n * asked a question for nothing.\n */\nexport interface AiFormDecisions {\n /** Where submissions go; `null` where nobody was asked. */\n submissions: AiSiteSubmissions | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction oneLine(value: string, max: number): string {\n return value.replace(/\\s+/g, ' ').trim().slice(0, max).trim()\n}\n\n/**\n * An answer's routing and gaps: an unknown kind is the Inbox, and the rest is\n * trimmed and capped. Where the person was asked where submissions go, their\n * answer replaces the model's proposal — the whole of the difference a\n * question makes.\n */\nexport function parseAiFormAnswer(\n answer: Record<string, unknown>,\n decisions: AiFormDecisions = { submissions: null },\n): AiFormAnswer {\n const routing = isRecord(answer['routing']) ? answer['routing'] : {}\n const proposed = (AI_FORM_ROUTING_KINDS as readonly unknown[]).includes(routing['kind'])\n ? (routing['kind'] as AiFormRoutingKind)\n : 'inbox'\n const kind: AiFormRoutingKind = decisions.submissions ?? proposed\n const list = typeof routing['list'] === 'string' ? oneLine(routing['list'], LIST_NAME_MAX_CHARS) : ''\n const seen = new Set<string>()\n const cannotCollect: string[] = []\n for (const entry of Array.isArray(answer['cannotCollect']) ? answer['cannotCollect'] : []) {\n if (typeof entry !== 'string') continue\n const text = oneLine(entry, CANNOT_COLLECT_MAX_CHARS)\n if (!text || seen.has(text.toLowerCase())) continue\n seen.add(text.toLowerCase())\n cannotCollect.push(text)\n if (cannotCollect.length === AI_FORM_CANNOT_COLLECT_MAX) break\n }\n return { routing: { kind, list: kind === 'list' && list ? list : null }, cannotCollect }\n}\n\n/** A generated form as its draft is written: the stamped design and what it declares. */\nexport interface AiFormDraft {\n /** The design as the Forms page's Create stores one: a canvas root above the bound form. */\n nodes: NodesMap\n rootId: string\n formNodeId: string\n fields: FormFieldDecl[]\n consentFieldName: string | null\n routing: FormRouting | null\n answer: AiFormAnswer\n /** The dataset its submissions are also written to, and what was bound (AGL-3616). */\n dataset?: { dataset: AiFormDataset; binding: AiFormDatasetBinding }\n}\n\n/**\n * The draft a validated design and its answer make: the form node bound to\n * `formId` and captioned `name`, the platform's consent field when the\n * fields can yield an email address, the canvas root above, and the\n * declaration read off the result. A dataset binding is made only where the\n * plan said the form writes to one this step may bind (`identity.dataset`,\n * AGL-3616); any the model drew is dropped. Pure; the input tree is not\n * changed.\n */\nexport function aiFormDraft(\n tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>,\n answer: Record<string, unknown>,\n identity: { formId: string; name: string; decisions?: AiFormDecisions; dataset?: AiFormDataset | null },\n): AiFormDraft {\n const parsed = parseAiFormAnswer(answer, identity.decisions ?? { submissions: null })\n const formNodeId = tree.rootId\n const nodes: NodesMap = {}\n for (const [id, node] of Object.entries(tree.nodes)) {\n nodes[id] = {\n ...node,\n props: { ...(node.props ?? {}) },\n nodes: Array.isArray(node.nodes) ? [...(node.nodes as string[])] : [],\n }\n }\n const form = nodes[formNodeId]\n let consentFieldName: string | null = null\n if (form?.componentId === FORM_COMPONENT_ID) {\n const props = form.props as Record<string, unknown>\n // A dataset binding decides where every submission is also written: the\n // plan's to say (AGL-3616), bound below, never the model's to draw.\n delete props['datasetId']\n delete props['datasetName']\n props[FORM_ID_PROP] = identity.formId\n props['formName'] = identity.name\n\n for (const id of collectFormFieldNodeIds(nodes as never, formNodeId)) {\n const fieldName = (nodes[id]?.props as Record<string, unknown> | undefined)?.['fieldName']\n if (!isMarketingConsentFieldName(fieldName)) continue\n const parent = nodes[String(nodes[id]?.parentId ?? '')]\n if (parent && Array.isArray(parent.nodes)) {\n parent.nodes = (parent.nodes as string[]).filter((child) => child !== id)\n }\n delete nodes[id]\n }\n if (formFieldsCanYieldAnEmail(formFieldDeclsFromNodes(nodes as never, formNodeId))) {\n nodes[AI_FORM_CONSENT_NODE_ID] = {\n $id: AI_FORM_CONSENT_NODE_ID,\n type: NodeType.NODE,\n componentId: FORM_FIELD_COMPONENT_ID,\n pluginId: AI_PALETTE[FORM_FIELD_COMPONENT_ID]?.pluginId,\n parentId: formNodeId,\n nodes: [],\n props: { ...MARKETING_CONSENT_FORM_FIELD },\n } as NodesMap[string]\n form.nodes = [...(form.nodes as string[]), AI_FORM_CONSENT_NODE_ID]\n consentFieldName = MARKETING_CONSENT_FORM_FIELD.fieldName\n }\n form.parentId = CANVAS_ROOT_ELEMENT_ID\n }\n // The dataset the plan says the form writes to (AGL-3616), bound as the\n // Form element binds one.\n const dataset =\n identity.dataset && form?.componentId === FORM_COMPONENT_ID\n ? { dataset: identity.dataset, binding: aiBindFormToDataset(nodes, formNodeId, identity.dataset) }\n : undefined\n nodes[CANVAS_ROOT_ELEMENT_ID] = {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n nodes: [formNodeId],\n } as NodesMap[string]\n return {\n nodes,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n formNodeId,\n fields: formFieldDeclsFromNodes(nodes as never, formNodeId),\n consentFieldName,\n routing: parsed.routing.kind === 'lead' ? { lead: true } : null,\n answer: parsed,\n ...(dataset ? { dataset } : {}),\n }\n}\n\n/**\n * What a draft would break once published, as building-rule violations\n * (rule 3: a form is built with its fields, validation, consent and routing\n * together): the form contract's findings, a form with no field, and a list\n * proposal on a form that asks for no email address. Offending nodes are\n * named by the ids the model wrote.\n */\nexport function aiFormDraftViolations(\n draft: AiFormDraft,\n formId: string,\n sourceIds: Readonly<Record<string, string>>,\n): AiDoctrineViolation[] {\n const violations: AiDoctrineViolation[] = checkFormContract({\n form: {\n ...(draft.routing ? { routing: draft.routing } : {}),\n ...(draft.consentFieldName ? { consentFieldName: draft.consentFieldName } : {}),\n },\n formId,\n nodes: draft.nodes as never,\n formNodeId: draft.formNodeId,\n }).map((violation) => ({\n rule: 3 as const,\n code: violation.code,\n message: violation.message,\n ...(violation.nodeId ? { nodeIds: aiModelNodeIds([violation.nodeId], sourceIds) } : {}),\n }))\n if (!draft.fields.length) {\n violations.push({\n rule: 3,\n code: 'form-has-no-fields',\n message:\n 'This form has no named fields, so a visitor has nothing to fill in. Draw the fields the brief asks for.',\n })\n }\n if (draft.answer.routing.kind === 'list' && !formFieldsCanYieldAnEmail(draft.fields)) {\n violations.push({\n rule: 3,\n code: 'list-routing-has-no-email-field',\n message:\n 'This form proposes adding the people who send it to an email list, and it asks for no email address. Add an email field, or route its submissions to the Inbox.',\n paths: ['routing.kind'],\n })\n }\n return violations\n}\n\n/**\n * The door's check for `extend`, and the draft each admitted tree made: the\n * tree a generation returns is the object its last check saw, so the step\n * writes exactly the draft the contract passed.\n */\nexport function aiFormDraftCheck(identity: {\n formId: string\n name: string\n decisions?: AiFormDecisions\n dataset?: AiFormDataset | null\n}): {\n extend: (tree: AiValidatedTree, answer: Record<string, unknown>) => AiDoctrineViolation[]\n draftFor: (tree: AiValidatedTree) => AiFormDraft | undefined\n} {\n const drafts = new WeakMap<AiValidatedTree, AiFormDraft>()\n return {\n extend: (tree, answer) => {\n const draft = aiFormDraft(tree, answer, identity)\n drafts.set(tree, draft)\n return aiFormDraftViolations(draft, identity.formId, tree.sourceIds)\n },\n draftFor: (tree) => drafts.get(tree),\n }\n}\n\n/**\n * What a job says when the copy it asked for came back naming the form it\n * was copied FROM (AGL-3024). The contract's own sentence follows it and\n * names the consequence; this one names what to do about it.\n */\nexport const AI_FORM_COPY_UNBOUND_FAILURE =\n 'The copy of that form did not take on an identity of its own, so it is on ' +\n 'the site and not safe to collect with — delete it in Forms and try again.'\n\n/**\n * Whether the copy the platform just wrote is bound to ITSELF, asked of the\n * document rather than of the answer — `null` when it is, and the sentence a\n * person reads when it is not.\n *\n * ## Why a step that generated nothing still has something to check\n *\n * A \"creates X from a copy of Y\" plan reaches no model: the copy IS the\n * output, so there is no answer for the doctrine to refuse and `extend`\n * never runs. That left the one thing a copy can get wrong unasked. A form's\n * design names its own form inside itself, and a copy that kept the source's\n * name files every submission under the source — the console's form page\n * banners exactly this, and the job reported Done beside it.\n *\n * So the check is `checkFormContract`, the SAME function the console's\n * banner and the promotion route ask, run here on the stored copy. Not a\n * second predicate shaped like it: a copy this one passed and that one\n * refused would be a form the job called finished and the console called\n * broken, which is the state this exists to make impossible.\n *\n * Narrowed to `form-id-unbound`, and only that, because it is the one\n * violation duplication CAUSES. Every other code the contract can report —\n * an unnamed field, a consent field the design lost — the copy inherited\n * from a form the site already has and the member chose to copy; refusing\n * those would be refusing to copy a form they can already see.\n */\nexport async function aiFormCopyUnboundFailure(\n firestore: FirebaseFirestore.Firestore,\n copy: { hostId: string; formId: string },\n): Promise<string | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(copy.hostId)\n .collection('forms')\n .doc(copy.formId)\n .get()\n const form = (snapshot.data() ?? null) as Partial<FormDocument> | null\n const nodes = decodeStoredNodes(form?.nodes)\n const unbound = checkFormContract({\n form,\n formId: copy.formId,\n nodes: nodes as never,\n formNodeId: formNodeIdIn(nodes as never),\n }).find((violation) => violation.code === 'form-id-unbound')\n return unbound ? `${AI_FORM_COPY_UNBOUND_FAILURE} ${unbound.message}` : null\n}\n\n/**\n * The fields the confirmed plan gives the form, against the form a COPY\n * actually produced (AGL-3024); `null` when the copy keeps the plan, or when\n * the plan promised no field to keep.\n *\n * The fourth kind to need this, after the layout, the page and the component.\n * `aiFormCopyUnboundFailure` above already refuses the one violation\n * duplication CAUSES; this refuses the one duplication HIDES — a plan reading\n * \"start from the consultation form and add a case-type question\" getting the\n * consultation form and nothing else, reported as built.\n *\n * A field the plan names is matched on its name alone: a copy that collects\n * the answer under a different label is still collecting it, and this check\n * has no way to tell a renamed field from a missing one without guessing.\n */\nexport async function aiCopiedFormReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; formId: string; name: string; plan: AiJobPlan | null },\n): Promise<AiJobReview | null> {\n const promised = (aiPlanCreation(input.plan, 'form')?.fields ?? [])\n .map((field) => field.split(':')[0]?.trim().toLowerCase())\n .filter((field): field is string => Boolean(field))\n if (!promised.length) return null\n const snapshot = await firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('forms')\n .doc(input.formId)\n .get()\n if (!snapshot.exists) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the form the plan names, and this job could not read the copy back to check it collects what the plan gives it. Open the form and check it before you put it on a page.`,\n findings: [],\n }\n }\n const fields = (snapshot.get('fields') ?? []) as unknown[]\n const collected = new Set(\n fields\n .map((field) =>\n field && typeof field === 'object'\n ? String((field as Record<string, unknown>)['fieldName'] ?? (field as Record<string, unknown>)['name'] ?? '')\n : '',\n )\n .filter(Boolean)\n .map((name) => name.toLowerCase()),\n )\n const missing = promised.filter((name) => !collected.has(name))\n if (!missing.length) return null\n const one = missing.length === 1\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the form the plan names, and a copy is all it is: the plan gives it ${\n one ? 'a field' : 'fields'\n } the copy does not collect.`,\n violations: [\n {\n rule: null,\n code: 'plan-fields-missing',\n message: `The confirmed plan says this form collects ${missing.join(', ')}, and the copy collects ${\n collected.size ? [...collected].join(', ') : 'nothing'\n }. Add ${one ? 'it' : 'each of them'}, or the copy is the form it was copied from.`,\n },\n ],\n })\n}\n\n/**\n * What the form a short copy would have started from collects, as the build\n * that replaces the copy is told it (AGL-3143 §14): every field it asks for,\n * so the build keeps them beside what the plan adds. Empty when the form\n * cannot be read.\n */\nexport async function aiFormSourceLines(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string },\n): Promise<string[]> {\n const snapshot = await firestore.collection('hosts').doc(input.hostId).collection('forms').doc(input.id).get()\n const fields = snapshot.exists ? ((snapshot.get('fields') ?? []) as unknown[]) : []\n const asked = fields.flatMap((field) => {\n if (!field || typeof field !== 'object') return []\n const row = field as Record<string, unknown>\n const name = String(row['fieldName'] ?? row['name'] ?? '').trim()\n if (!name) return []\n const fieldType = row['fieldType'] ?? row['type']\n const type = typeof fieldType === 'string' ? ` (${fieldType}${row['required'] ? ', required' : ''})` : ''\n return [`${name}${type}`]\n })\n if (!asked.length) return []\n return [\n `The plan starts from a copy of the form \"${input.name}\", which lacks part of what the plan gives it. Build from it: it collects ${asked.join(', ')}. Keep each of those, and add what the plan adds.`,\n ]\n}\n\nfunction listOf(items: readonly string[]): string {\n return items.length < 2\n ? items.join('')\n : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\n/**\n * What the person decides next, in words the step writes itself: a lead\n * routing to keep or switch off, the list a proposal could not store, and what\n * the brief asked for that a form cannot collect. `null` when there is none.\n */\nexport function aiFormOutputNote(answer: AiFormAnswer): string | null {\n const sentences: string[] = []\n if (answer.routing.kind === 'lead') {\n sentences.push(\n 'Each submission with an email address also files a lead in CRM → Leads; you can switch that off on the form’s page.',\n )\n }\n if (answer.routing.kind === 'list') {\n const list = answer.routing.list ? `your \"${answer.routing.list}\" list` : 'an email list'\n sentences.push(\n `Submissions arrive in the Inbox. To add the people who tick \"${MARKETING_CONSENT_FORM_FIELD.label}\" to ${list}, add an action on form submissions in Automation that enrolls them.`,\n )\n }\n if (answer.cannotCollect.length) {\n sentences.push(\n `Forms cannot collect ${listOf(answer.cannotCollect)} yet, so this form leaves ${\n answer.cannotCollect.length === 1 ? 'it' : 'them'\n } out.`,\n )\n }\n return sentences.length ? sentences.join(' ') : null\n}\n\n/**\n * The form job as the generation's user turn: the name, who fills the form\n * in, the brief, and the confirmed plan.\n *\n * Who the form is for (AGL-2918) is the answer a contact form's FIELDS turn\n * on — a trades business asks where the work is, a practice asks what the\n * appointment is about — and it is not something a brief about a whole site\n * says in a place the form can find. It rides here, in the turn, because it\n * is one site's own words.\n *\n * Where submissions go rides here too, and it is NOT a hint: the step binds\n * the routing to it whatever the model answers. It is stated so the model\n * does not spend its answer proposing something that will be replaced, and\n * so a form told its submissions are leads asks for the address that makes\n * one.\n */\nexport function aiJobFormPrompt(\n job: Pick<AiJob, 'brief'>,\n plan: AiJobPlan | null,\n name: string,\n context: { audience?: string; submissions?: AiSiteSubmissions | null } = {},\n): string {\n const audience = (context.audience ?? '').trim()\n return [\n `Form name: ${name}`,\n audience ? `The people who fill it in: ${audience}` : '',\n context.submissions ? `Where its submissions go: ${SUBMISSION_WORDS[context.submissions]}` : '',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** What each decided routing is, said to the model the way the tool says it. */\nconst SUBMISSION_WORDS: Record<AiSiteSubmissions, string> = {\n inbox: 'the Inbox, to be read — routing.kind is inbox',\n lead: 'the Inbox, and each one with an email address is a sales lead — routing.kind is lead',\n}\n\n/**\n * A form job is admitted for a site of the job's own org whose plan has\n * forms, with a form to spare, and confirmed only for a plan that creates\n * nothing but the form: a form places nothing another job builds\n * (AGL-3143 §15).\n */\nexport const aiFormJobAdmission: AiJobAdmission = (context) =>\n aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'form',\n org: context.org,\n ownCheck: (hostId) => aiJobPlanCreationsRefusal('form', context, hostId),\n })\n\nexport interface AiJobFormStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n /** The data plugin's writer lookup the form's dataset is read through (AGL-3616); specs hand in a fake. */\n datasetWriterFor?: AiFormDatasetReadDeps['writerFor']\n}\n\nexport function createAiJobFormStep(deps: AiJobFormStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a form job names no site, and its admission refuses one')\n const output = (\n draft: AiDraftRecord,\n extra: { load?: AiLoadEstimate | null; note?: string | null } = {},\n ): AiJobOutput => ({\n resource: 'form',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(extra.load ? { load: extra.load } : {}),\n ...(extra.note ? { note: extra.note } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.form') ?? aiModelForStep('job.form')\n\n // A run cut off after its draft was written reports that draft, found by the id the job recorded.\n const draftId = aiJobDraftId(job, 'form')\n const written = await readAiDraft(firestore, { kind: 'form', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n ])\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'form')\n const name = creation?.name || AI_JOB_FORM_DEFAULT_NAME\n\n // The plan starts from a copy of a form the site has (rule 15): the copy\n // is the draft, and nothing is generated. A source gone since the plan\n // was made is built from the brief instead, and one that does not collect\n // a field the plan gives the form is built from the plan, told what the\n // source collects (AGL-3143 §14): copying it could only end in the review\n // below. A source this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.forms.find((form) => form.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedFormReview(firestore, { hostId, formId: source.id, name: source.name, plan })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n const sourceLines =\n source && sourceShort ? await aiFormSourceLines(firestore, { hostId, id: source.id, name: source.name }) : []\n if (creation?.duplicateOf && source && !sourceShort) {\n const copy = await duplicate('form', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n // The copy is the whole output, so the contract is asked of it here\n // or nowhere: a copy still bound to its source is not a form this\n // job may report as built (AGL-3024).\n const unbound = await aiFormCopyUnboundFailure(firestore, { hostId, formId: copy.id })\n if (unbound) return { ...aiUnspentOutcome(model), failure: unbound }\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // And the one duplication hides: what the plan promised of the copy,\n // read back (AGL-3024). This branch generates nothing, so nothing\n // else can answer for it.\n const review = await aiCopiedFormReview(firestore, {\n hostId,\n formId: copy.id,\n name: copy.name,\n plan,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: copy.versionId, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'form', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n // What the person answered about this form, where they were asked\n // (AGL-2918): a scaffold's form unit carries the guided start's inputs.\n const decisions: AiFormDecisions = { submissions: aiSiteSubmissions(job.inputs) }\n const { audience } = aiSiteWords(job.inputs)\n // The dataset the plan says the form writes to (AGL-3616), where this\n // workspace may bind one; otherwise the form is the form it always was.\n const dataset = await aiReadFormDataset(\n {\n hostId,\n id: creation?.writesTo,\n org,\n inventory,\n madeId: job.inputs?.[AI_FORM_DATASET_MADE_INPUT],\n },\n deps.datasetWriterFor ? { writerFor: deps.datasetWriterFor } : {},\n )\n const check = aiFormDraftCheck({ formId: draftId, name, decisions, dataset })\n const result = await runValidatedGeneration('form', {\n step: 'job.form',\n model,\n instructions: AI_JOB_FORM_INSTRUCTIONS,\n inventory,\n messages: [\n {\n role: 'user',\n content: [\n aiJobFormPrompt(job, plan, name, {\n audience,\n submissions: decisions.submissions,\n }),\n ...sourceLines,\n ...(dataset ? [aiFormDatasetPromptLine(dataset)] : []),\n ].join('\\n'),\n },\n ],\n tool: AI_JOB_FORM_TOOL,\n maxTokens: AI_JOB_FORM_STEP_BUDGET.maxTokens(model),\n thinking: 'off',\n extend: check.extend,\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n const draft = check.draftFor(result.value)\n if (!draft) throw new Error('a form the doctrine admitted has no draft from its check')\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const write = await writeAiDraft(firestore, {\n kind: 'form',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: draft.nodes,\n form: {\n rootId: draft.rootId,\n formNodeId: draft.formNodeId,\n fields: draft.fields,\n consentFieldName: draft.consentFieldName,\n routing: draft.routing,\n },\n now,\n })\n if (write.ok === false) {\n if (write.status === 404) throw new Error(`site ${hostId} vanished while its form was generated`)\n return { ...spent, review: aiLimitReview(write.error) }\n }\n // What the person decides next, then the facts the brief did not give (AGL-3056).\n const note = [\n aiFormOutputNote(draft.answer),\n draft.dataset ? aiFormDatasetNote(draft.dataset.dataset, draft.dataset.binding) : null,\n aiBracketedFactsNote({\n tree: { rootId: result.value.rootId, nodes: result.value.nodes as unknown as AiDoctrineTree['nodes'] },\n inventory,\n }),\n ]\n .filter(Boolean)\n .join(' ')\n return {\n ...spent,\n outputs: [output(write, { load: result.value.load, note })],\n }\n }\n}\n\nexport const runAiJobFormStep = createAiJobFormStep()\n\n/** Registers the form step and the check a form job passes before it is created or resumed. */\nexport function registerAiFormJob(): void {\n registerAiJobStep('form', runAiJobFormStep, { minimumMs: AI_JOB_FORM_STEP_MINIMUM_MS })\n registerAiJobAdmission('form', aiFormJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","checkFormContract","formFieldsCanYieldAnEmail","collectFormFieldNodeIds","FORM_COMPONENT_ID","FORM_FIELD_COMPONENT_ID","FORM_ID_PROP","formFieldDeclsFromNodes","formNodeIdIn","isMarketingConsentFieldName","MARKETING_CONSENT_FORM_FIELD","decodeStoredNodes","CANVAS_ROOT_ELEMENT_ID","NodeType","duplicateResource","aiSiteSubmissions","aiSiteWords","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","AI_PALETTE","readSiteInventory","registerAiJobAdmission","AI_FORM_DATASET_MADE_INPUT","aiBindFormToDataset","aiFormDatasetNote","aiFormDatasetPromptLine","aiReadFormDataset","aiJobPlanCreationsRefusal","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","writeAiDraft","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlanCreation","aiPlanReferenceLines","aiUnspentOutcome","aiJobStepBudget","registerAiJobStep","AI_JOB_FORM_MAX_TOKENS","maxTokens","AI_JOB_FORM_STEP_BUDGET","tier","AI_JOB_FORM_STEP_MINIMUM_MS","minimumMs","AI_JOB_FORM_DEFAULT_NAME","AI_FORM_ROUTING_KINDS","AI_FORM_CANNOT_COLLECT_MAX","CANNOT_COLLECT_MAX_CHARS","LIST_NAME_MAX_CHARS","AI_FORM_CONSENT_NODE_ID","AI_JOB_FORM_INSTRUCTIONS","text","join","TREE_TOOL","AI_JOB_FORM_TOOL","name","description","strict","inputSchema","type","additionalProperties","required","properties","tree","routing","kind","enum","list","anyOf","cannotCollect","items","isRecord","value","Array","isArray","oneLine","max","replace","trim","slice","parseAiFormAnswer","answer","decisions","submissions","proposed","includes","seen","Set","entry","has","toLowerCase","add","push","length","aiFormDraft","identity","parsed","formNodeId","rootId","nodes","id","node","Object","entries","props","form","consentFieldName","componentId","formId","fieldName","parent","String","parentId","filter","child","$id","NODE","pluginId","dataset","binding","undefined","fields","lead","aiFormDraftViolations","draft","sourceIds","violations","map","violation","rule","code","message","nodeId","nodeIds","paths","aiFormDraftCheck","drafts","WeakMap","extend","set","draftFor","get","AI_FORM_COPY_UNBOUND_FAILURE","aiFormCopyUnboundFailure","firestore","copy","snapshot","collection","doc","hostId","data","unbound","find","aiCopiedFormReview","input","promised","plan","field","split","Boolean","exists","reason","findings","collected","missing","one","size","aiFormSourceLines","asked","flatMap","row","fieldType","listOf","aiFormOutputNote","sentences","label","aiJobFormPrompt","job","context","audience","SUBMISSION_WORDS","inbox","aiFormJobAdmission","orgId","org","ownCheck","createAiJobFormStep","deps","readInventory","duplicate","now","signal","modelFor","orgSnapshot","Error","output","extra","resource","versionId","hostSubdomain","load","note","model","draftId","written","outputs","inventory","Promise","all","creation","source","duplicateOf","forms","sourceReview","sourceShort","sourceLines","sourceId","uid","createdBy","attemptKey","ok","failure","review","status","error","allowance","inputs","writesTo","madeId","datasetWriterFor","writerFor","check","result","step","instructions","messages","role","content","tool","thinking","spent","refused","write","runAiJobFormStep","registerAiFormJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SACEC,iBAAiB,EACjBC,yBAAyB,QACpB,uCAAsC;AAC7C,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,uBAAuB,EACvBC,YAAY,EACZC,uBAAuB,EACvBC,YAAY,EACZC,2BAA2B,EAC3BC,4BAA4B,QAIvB,+BAA8B;AACrC,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SAASC,QAAQ,QAAuB,2BAA0B;AAClE,SAASC,iBAAiB,QAAQ,qDAAoD;AAEtF,SAASC,iBAAiB,EAAEC,WAAW,QAAgC,0BAAsB;AAC7F,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SACEC,kBAAkB,EAClBC,sBAAsB,QAEjB,4BAAwB;AAG/B,SAASC,UAAU,QAAQ,qCAAiC;AAE5D,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,sBAAsB,QAA6B,wBAAoB;AAChF,SACEC,0BAA0B,EAC1BC,mBAAmB,EACnBC,iBAAiB,EACjBC,uBAAuB,EACvBC,iBAAiB,QAIZ,2BAAuB;AAC9B,SAASC,yBAAyB,QAAQ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,MAAMN,OAAO,CAACC,OAAO,IAAI;YAClF7F,qBAAqB;gBACnBqC,MAAM;oBAAEmC,QAAQsI,OAAOhK,KAAK,CAAC0B,MAAM;oBAAEC,OAAOqI,OAAOhK,KAAK,CAAC2B,KAAK;gBAAuC;gBACrG2G;YACF;SACD,CACE7F,MAAM,CAAC8C,SACP3G,IAAI,CAAC;QACR,OAAO,aACF4L;YACHnC,SAAS;gBAACV,OAAO+C,OAAO;oBAAE1C,MAAMgC,OAAOhK,KAAK,CAACgI,IAAI;oBAAEC;gBAAK;aAAG;;IAE/D;AACF;AAEA,OAAO,MAAM0C,mBAAmBzD,sBAAqB;AAErD,6FAA6F,GAC7F,OAAO,SAAS0D;IACd/M,kBAAkB,QAAQ8M,kBAAkB;QAAExM,WAAWD;IAA4B;IACrF7B,uBAAuB,QAAQyK;AACjC"}
@@ -22,7 +22,7 @@ import { aiLayoutStoredTree } from "../layout-language/ai-layout-store.js";
22
22
  import { AI_GENERATION_MAX_ATTEMPTS } from "../runtime/ai-generation-bounds.js";
23
23
  import { aiHomeScreenIds } from "../model/ai-site-inventory.js";
24
24
  import { AI_STEP_TIERS } from "../providers/catalog.js";
25
- import { validateAiDoctrineTree } from "../runtime/ai-doctrine-validators.js";
25
+ import { aiSettleMechanicalRules, validateAiDoctrineTree } from "../runtime/ai-doctrine-validators.js";
26
26
  import { aiSiteKindDesignLines } from "../model/ai-site-kinds.js";
27
27
  import { aiJobStepBudget } from "./ai-job-budget.js";
28
28
  import { aiJobBriefLine } from "./ai-job-generation.js";
@@ -178,7 +178,12 @@ import { AI_SITE_NAME_TOKEN } from "./ai-layout-site-facts.js";
178
178
  ...input.targets.forms.map((form)=>form.id)
179
179
  ]
180
180
  }, last);
181
- const { nodes, dropped } = copy;
181
+ const { dropped } = copy;
182
+ // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660).
183
+ const nodes = aiSettleMechanicalRules({
184
+ rootId: stored.rootId,
185
+ nodes: copy.nodes
186
+ }, 'layout').nodes;
182
187
  const report = validateAiDoctrineTree({
183
188
  rootId: stored.rootId,
184
189
  nodes
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-layout-language.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 type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { aiLayoutDesignChoices, type AiLayoutDesign } from '../layout-language/ai-layout-design'\nimport { aiCompileLayoutFrame } from '../layout-language/ai-layout-frame'\nimport {\n AI_LAYOUT_FRAME_TOOL,\n AI_LAYOUT_LANGUAGE_TEXT,\n aiReadLayoutFrame,\n} from '../layout-language/ai-layout-language'\nimport type {\n AiLayoutPage,\n AiLayoutTargets,\n} from '../layout-language/ai-layout-links'\nimport { aiLayoutCopyCheck } from '../layout-language/ai-layout-gaps'\nimport { aiLayoutStoredTree } from '../layout-language/ai-layout-store'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport type { AiJob } from '../model/ai-jobs.types'\nimport {\n aiHomeScreenIds,\n type AiSiteInventory,\n} from '../model/ai-site-inventory'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiGenerationCheck, AiValidatedTree } from '../runtime/ai-doctrine'\nimport {\n validateAiDoctrineTree,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiSiteKindDesignLines } from '../model/ai-site-kinds'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiJobBriefLine } from './ai-job-generation'\nimport {\n AI_LAYOUT_SITE_PAGES_MAX,\n aiLayoutIsHomeSlug,\n aiLayoutSitePages,\n} from './ai-job-layout-site-pages'\nimport {\n AI_LAYOUT_FRAME_THINKING_TOKENS,\n aiLayoutPageTargets,\n} from './ai-job-page-language'\nimport { AI_SITE_NAME_TOKEN } from './ai-layout-site-facts'\n\n/**\n * A site's layout built in the compact layout language (AGL-3660): the layout\n * step's pass for a guided start's and a build's layout unit. The model\n * designs the header and the footer — their bands, the call to action, the\n * footer's columns and every word — in one short answer through\n * `submit_frame`, and the compiler writes the layout around what the site\n * owes it: its name as the brand, its pages as the navigation and the phone\n * menu, the Layout Slot, and the footer at the bottom of a short page\n * (`ai-layout-frame.ts`).\n */\n\n/**\n * The most a frame's answer asks for: two sections of a few blocks each (the\n * live runs of 2026-10-07 wrote 442 to 583), and the thinking before them.\n */\nexport const AI_JOB_LAYOUT_LANGUAGE_TOKENS = 1_200 + AI_LAYOUT_FRAME_THINKING_TOKENS\n\n/** A language layout pass's time, on the tier the layout step is served from. */\nexport const AI_JOB_LAYOUT_LANGUAGE_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.layout'],\n maxTokens: AI_JOB_LAYOUT_LANGUAGE_TOKENS,\n})\n\n/** The generation kind a frame is asked under, which the doctrine scopes. */\nexport const AI_LAYOUT_FRAME_KIND = 'layout-frame'\n\n/** The language, as the frame door's cached instructions. */\nexport const AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n AI_LAYOUT_LANGUAGE_TEXT,\n '',\n \"Now you design a site's header and footer, each one section of the language, answered with submit_frame.\",\n \"- header: the platform writes the site's name and its navigation itself. Choose its band and align (start, or center for a centered navigation), and give it at most one button: the call to action every page shows.\",\n '- footer: a section like any other, usually a row of two or three columns: a few words about the business, the details the brief gives, and a list of links (items with to). Put no contact detail, opening hours or address in it that the brief does not give, and no gap in square brackets for one.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/** The site's name as the brand: the name the job was given, else the token the site's own name fills. */\nexport function aiLayoutSiteName(job: Pick<AiJob, 'inputs'>): string {\n const given = job.inputs?.['businessName']\n return typeof given === 'string' && given.trim()\n ? given.trim()\n : AI_SITE_NAME_TOKEN\n}\n\n/** The pages a frame's navigation links: the planned pages, else the site's own, in order. */\nexport function aiLayoutNavPages(\n job: Pick<AiJob, 'inputs'>,\n inventory: AiSiteInventory | null,\n): AiLayoutPage[] {\n // The header and the footer link the pages the job was told (AGL-3660),\n // else the site's own, the home page always and first, labelled Home. The\n // model draws neither list, so it cannot drop a page.\n const planned = aiLayoutSitePages(job.inputs)\n const own = (inventory?.screens ?? [])\n .filter((row) => !row.template)\n .map((row) => ({ id: row.id, label: row.name, slug: row.slug }))\n const siteHome = planned.some((page) => aiLayoutIsHomeSlug(page.slug))\n ? []\n : own.filter((page) => aiLayoutIsHomeSlug(page.slug)).slice(0, 1)\n const pages = [...siteHome, ...(planned.length ? planned : own)].filter((page) => page.label.trim())\n const home = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return [\n ...(home ? [{ ...home, label: 'Home' }] : []),\n ...pages.filter((page) => page !== home && !aiLayoutIsHomeSlug(page.slug)),\n ].slice(0, AI_LAYOUT_SITE_PAGES_MAX)\n}\n\n/** The home page the brand links: the planned home, else the site's. */\nexport function aiLayoutHomeId(\n pages: readonly AiLayoutPage[],\n inventory: AiSiteInventory | null,\n): string | null {\n const planned = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return planned?.id ?? aiHomeScreenIds(inventory)[0] ?? null\n}\n\n/** The frame's user turn: the site, its brief, its pages and its form. */\nexport function aiLayoutFramePrompt(input: {\n job: Pick<AiJob, 'brief' | '$id'> & Partial<Pick<AiJob, 'inputs'>>\n siteName: string\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n}): string {\n const { job, pages, targets } = input\n return [\n `Site: ${input.siteName === AI_SITE_NAME_TOKEN ? 'the business the brief describes' : `\"${input.siteName}\"`}`,\n aiJobBriefLine(job),\n ...aiSiteKindDesignLines(job.inputs),\n pages.length\n ? `Its pages, which the navigation links: ${pages.map((page) => `${page.label} (page:${page.id})`).join(', ')}.`\n : 'It has no pages yet.',\n targets.forms.length || targets.formPageId\n ? 'A call to action that asks a visitor to get in touch goes to form.'\n : 'The site has no form yet.',\n // A storefront's header (AGL-3676): its cart, and an announcement line.\n ...(aiLayoutShopPageId(targets)\n ? [\n \"This is an online store: give the header no button, since the platform puts the cart beside the navigation. Give the header one note instead: a short announcement for the bar above it, under 60 characters, about the shop from the brief (a promise it makes, such as its shipping, or what is new); never invent an offer, a discount, a price or a shipping threshold the brief does not give.\",\n ]\n : []),\n `Design seed: ${job.$id.slice(-6)}.`,\n ].join('\\n')\n}\n\n/** A store's Shop page, by its id: the page its catalog's whole list is placed on (AGL-3676). */\nexport function aiLayoutShopPageId(targets: Pick<AiLayoutTargets, 'listings'>): string | null {\n const products = (targets.listings ?? []).find((listing) => listing.kind === 'products')\n return products?.placements.find((placement) => placement.role === 'index')?.screenId ?? null\n}\n\n/** A validated language layout. */\nexport interface AiLayoutFrameBuilt {\n rootId: string\n nodes: NodesMap\n load: AiLoadEstimate | null\n /** What the last answer's gaps took out of the frame (`ai-layout-gaps.ts`). */\n dropped: string[]\n}\n\n/** The check a frame answer is held to: read, compiled, stored and checked as a layout, with the layout door's own checks. */\nexport function aiLayoutFrameCheck(input: {\n /** The header arrangement the site's look chose (AGL-3660); the answer's otherwise. */\n headerAlign?: 'start' | 'center'\n siteName: string\n homeId: string | null\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n extend: (tree: AiValidatedTree) => AiDoctrineViolation[]\n /** The site's design (`aiLayoutDesignOf`), whose pages' closing band the footer sits under. */\n design?: AiLayoutDesign | null\n}): AiGenerationCheck<AiLayoutFrameBuilt> {\n let answers = 0\n return (answer) => {\n // The last answer a generation takes has its gaps taken out rather than asked about again.\n answers += 1\n const last = answers >= AI_GENERATION_MAX_ATTEMPTS\n const frame = aiReadLayoutFrame(answer)\n if (input.headerAlign && frame.header) frame.header.align = input.headerAlign\n const compiled = aiCompileLayoutFrame(\n frame,\n {\n siteName: input.siteName,\n homeId: input.homeId,\n navPages: input.pages,\n closesDark: input.design ? aiLayoutDesignChoices(input.design).coverClose : false,\n // A site that sells carries its cart in the header (AGL-3676).\n cart: (input.targets.listings ?? []).some((listing) => listing.kind === 'products' && listing.cart !== false),\n // And a store's header is a storefront's: no button repeating its navigation, an announcement bar (AGL-3676).\n shopId: aiLayoutShopPageId(input.targets),\n },\n input.targets,\n )\n const context = {\n screenIds: [\n ...new Set([\n ...input.targets.pages.map((page) => page.id),\n ...input.pages.map((page) => page.id),\n ...(input.homeId ? [input.homeId] : []),\n ]),\n ],\n formIds: input.targets.forms.map((form) => form.id),\n homeScreenIds: input.targets.homeIds,\n codeBuilt: true,\n }\n const stored = aiLayoutStoredTree(compiled.tree, 'layout', context)\n if (stored.ok === false) {\n console.error('ai layout frame: a compiled layout did not store', {\n error: stored.error,\n })\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'layout-compile',\n message: 'This layout could not be built. Try again.',\n detail: stored.error,\n },\n ],\n }\n }\n // No gap and no internal reference in the words of a frame every published page shows.\n const navPages = [...input.targets.pages, ...input.pages]\n const copy = aiLayoutCopyCheck(\n stored.nodes,\n stored.rootId,\n {\n pages: navPages,\n ids: [...navPages.map((page) => page.id), ...input.targets.forms.map((form) => form.id)],\n },\n last,\n )\n const { nodes, dropped } = copy\n const report = validateAiDoctrineTree(\n { rootId: stored.rootId, nodes },\n 'layout',\n context,\n )\n const violations = [\n ...report.violations,\n ...copy.violations,\n ...input.extend({\n rootId: stored.rootId,\n nodes,\n repairs: [],\n sourceIds: {},\n score: report.score as AiValidatedTree['score'],\n load: report.load,\n }),\n ]\n return {\n value: violations.length\n ? null\n : { rootId: stored.rootId, nodes, load: report.load, dropped },\n violations,\n }\n }\n}\n\n/** What a frame's links resolve against: the site's pages and its form, as a page's do. */\nexport function aiLayoutFrameTargets(\n job: Pick<AiJob, 'brief' | 'inputs'>,\n inventory: AiSiteInventory | null,\n): AiLayoutTargets {\n return aiLayoutPageTargets({ job, inventory, own: [] })\n}\n"],"names":["aiLayoutDesignChoices","aiCompileLayoutFrame","AI_LAYOUT_LANGUAGE_TEXT","aiReadLayoutFrame","aiLayoutCopyCheck","aiLayoutStoredTree","AI_GENERATION_MAX_ATTEMPTS","aiHomeScreenIds","AI_STEP_TIERS","validateAiDoctrineTree","aiSiteKindDesignLines","aiJobStepBudget","aiJobBriefLine","AI_LAYOUT_SITE_PAGES_MAX","aiLayoutIsHomeSlug","aiLayoutSitePages","AI_LAYOUT_FRAME_THINKING_TOKENS","aiLayoutPageTargets","AI_SITE_NAME_TOKEN","AI_JOB_LAYOUT_LANGUAGE_TOKENS","AI_JOB_LAYOUT_LANGUAGE_BUDGET","tier","maxTokens","AI_LAYOUT_FRAME_KIND","AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS","text","join","cacheBreakpoint","aiLayoutSiteName","job","given","inputs","trim","aiLayoutNavPages","inventory","planned","own","screens","filter","row","template","map","id","label","name","slug","siteHome","some","page","slice","pages","length","home","find","aiLayoutHomeId","aiLayoutFramePrompt","input","targets","siteName","forms","formPageId","aiLayoutShopPageId","$id","products","listings","listing","kind","placements","placement","role","screenId","aiLayoutFrameCheck","answers","answer","last","frame","headerAlign","header","align","compiled","homeId","navPages","closesDark","design","coverClose","cart","shopId","context","screenIds","Set","formIds","form","homeScreenIds","homeIds","codeBuilt","stored","tree","ok","console","error","value","violations","rule","code","message","detail","copy","nodes","rootId","ids","dropped","report","extend","repairs","sourceIds","score","load","aiLayoutFrameTargets"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,qBAAqB,QAA6B,yCAAqC;AAChG,SAASC,oBAAoB,QAAQ,wCAAoC;AACzE,SAEEC,uBAAuB,EACvBC,iBAAiB,QACZ,2CAAuC;AAK9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AAOtG,kBACX2F,OAAOY,KAAK,EACZZ,OAAOa,MAAM,EACb;YACE1D,OAAO+B;YACP4B,KAAK;mBAAI5B,SAASxC,GAAG,CAAC,CAACO,OAASA,KAAKN,EAAE;mBAAMc,MAAMC,OAAO,CAACE,KAAK,CAAClB,GAAG,CAAC,CAACkD,OAASA,KAAKjD,EAAE;aAAE;QAC1F,GACAgC;QAEF,MAAM,EAAEiC,KAAK,EAAEG,OAAO,EAAE,GAAGJ;QAC3B,MAAMK,SAAStG,uBACb;YAAEmG,QAAQb,OAAOa,MAAM;YAAED;QAAM,GAC/B,UACApB;QAEF,MAAMc,aAAa;eACdU,OAAOV,UAAU;eACjBK,KAAKL,UAAU;eACf7C,MAAMwD,MAAM,CAAC;gBACdJ,QAAQb,OAAOa,MAAM;gBACrBD;gBACAM,SAAS,EAAE;gBACXC,WAAW,CAAC;gBACZC,OAAOJ,OAAOI,KAAK;gBACnBC,MAAML,OAAOK,IAAI;YACnB;SACD;QACD,OAAO;YACLhB,OAAOC,WAAWlD,MAAM,GACpB,OACA;gBAAEyD,QAAQb,OAAOa,MAAM;gBAAED;gBAAOS,MAAML,OAAOK,IAAI;gBAAEN;YAAQ;YAC/DT;QACF;IACF;AACF;AAEA,yFAAyF,GACzF,OAAO,SAASgB,qBACdxF,GAAoC,EACpCK,SAAiC;IAEjC,OAAOjB,oBAAoB;QAAEY;QAAKK;QAAWE,KAAK,EAAE;IAAC;AACvD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-layout-language.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 type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { aiLayoutDesignChoices, type AiLayoutDesign } from '../layout-language/ai-layout-design'\nimport { aiCompileLayoutFrame } from '../layout-language/ai-layout-frame'\nimport {\n AI_LAYOUT_FRAME_TOOL,\n AI_LAYOUT_LANGUAGE_TEXT,\n aiReadLayoutFrame,\n} from '../layout-language/ai-layout-language'\nimport type {\n AiLayoutPage,\n AiLayoutTargets,\n} from '../layout-language/ai-layout-links'\nimport { aiLayoutCopyCheck } from '../layout-language/ai-layout-gaps'\nimport { aiLayoutStoredTree } from '../layout-language/ai-layout-store'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport type { AiJob } from '../model/ai-jobs.types'\nimport {\n aiHomeScreenIds,\n type AiSiteInventory,\n} from '../model/ai-site-inventory'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiGenerationCheck, AiValidatedTree } from '../runtime/ai-doctrine'\nimport {\n aiSettleMechanicalRules,\n validateAiDoctrineTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiSiteKindDesignLines } from '../model/ai-site-kinds'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiJobBriefLine } from './ai-job-generation'\nimport {\n AI_LAYOUT_SITE_PAGES_MAX,\n aiLayoutIsHomeSlug,\n aiLayoutSitePages,\n} from './ai-job-layout-site-pages'\nimport {\n AI_LAYOUT_FRAME_THINKING_TOKENS,\n aiLayoutPageTargets,\n} from './ai-job-page-language'\nimport { AI_SITE_NAME_TOKEN } from './ai-layout-site-facts'\n\n/**\n * A site's layout built in the compact layout language (AGL-3660): the layout\n * step's pass for a guided start's and a build's layout unit. The model\n * designs the header and the footer — their bands, the call to action, the\n * footer's columns and every word — in one short answer through\n * `submit_frame`, and the compiler writes the layout around what the site\n * owes it: its name as the brand, its pages as the navigation and the phone\n * menu, the Layout Slot, and the footer at the bottom of a short page\n * (`ai-layout-frame.ts`).\n */\n\n/**\n * The most a frame's answer asks for: two sections of a few blocks each (the\n * live runs of 2026-10-07 wrote 442 to 583), and the thinking before them.\n */\nexport const AI_JOB_LAYOUT_LANGUAGE_TOKENS = 1_200 + AI_LAYOUT_FRAME_THINKING_TOKENS\n\n/** A language layout pass's time, on the tier the layout step is served from. */\nexport const AI_JOB_LAYOUT_LANGUAGE_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.layout'],\n maxTokens: AI_JOB_LAYOUT_LANGUAGE_TOKENS,\n})\n\n/** The generation kind a frame is asked under, which the doctrine scopes. */\nexport const AI_LAYOUT_FRAME_KIND = 'layout-frame'\n\n/** The language, as the frame door's cached instructions. */\nexport const AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n AI_LAYOUT_LANGUAGE_TEXT,\n '',\n \"Now you design a site's header and footer, each one section of the language, answered with submit_frame.\",\n \"- header: the platform writes the site's name and its navigation itself. Choose its band and align (start, or center for a centered navigation), and give it at most one button: the call to action every page shows.\",\n '- footer: a section like any other, usually a row of two or three columns: a few words about the business, the details the brief gives, and a list of links (items with to). Put no contact detail, opening hours or address in it that the brief does not give, and no gap in square brackets for one.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/** The site's name as the brand: the name the job was given, else the token the site's own name fills. */\nexport function aiLayoutSiteName(job: Pick<AiJob, 'inputs'>): string {\n const given = job.inputs?.['businessName']\n return typeof given === 'string' && given.trim()\n ? given.trim()\n : AI_SITE_NAME_TOKEN\n}\n\n/** The pages a frame's navigation links: the planned pages, else the site's own, in order. */\nexport function aiLayoutNavPages(\n job: Pick<AiJob, 'inputs'>,\n inventory: AiSiteInventory | null,\n): AiLayoutPage[] {\n // The header and the footer link the pages the job was told (AGL-3660),\n // else the site's own, the home page always and first, labelled Home. The\n // model draws neither list, so it cannot drop a page.\n const planned = aiLayoutSitePages(job.inputs)\n const own = (inventory?.screens ?? [])\n .filter((row) => !row.template)\n .map((row) => ({ id: row.id, label: row.name, slug: row.slug }))\n const siteHome = planned.some((page) => aiLayoutIsHomeSlug(page.slug))\n ? []\n : own.filter((page) => aiLayoutIsHomeSlug(page.slug)).slice(0, 1)\n const pages = [...siteHome, ...(planned.length ? planned : own)].filter((page) => page.label.trim())\n const home = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return [\n ...(home ? [{ ...home, label: 'Home' }] : []),\n ...pages.filter((page) => page !== home && !aiLayoutIsHomeSlug(page.slug)),\n ].slice(0, AI_LAYOUT_SITE_PAGES_MAX)\n}\n\n/** The home page the brand links: the planned home, else the site's. */\nexport function aiLayoutHomeId(\n pages: readonly AiLayoutPage[],\n inventory: AiSiteInventory | null,\n): string | null {\n const planned = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return planned?.id ?? aiHomeScreenIds(inventory)[0] ?? null\n}\n\n/** The frame's user turn: the site, its brief, its pages and its form. */\nexport function aiLayoutFramePrompt(input: {\n job: Pick<AiJob, 'brief' | '$id'> & Partial<Pick<AiJob, 'inputs'>>\n siteName: string\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n}): string {\n const { job, pages, targets } = input\n return [\n `Site: ${input.siteName === AI_SITE_NAME_TOKEN ? 'the business the brief describes' : `\"${input.siteName}\"`}`,\n aiJobBriefLine(job),\n ...aiSiteKindDesignLines(job.inputs),\n pages.length\n ? `Its pages, which the navigation links: ${pages.map((page) => `${page.label} (page:${page.id})`).join(', ')}.`\n : 'It has no pages yet.',\n targets.forms.length || targets.formPageId\n ? 'A call to action that asks a visitor to get in touch goes to form.'\n : 'The site has no form yet.',\n // A storefront's header (AGL-3676): its cart, and an announcement line.\n ...(aiLayoutShopPageId(targets)\n ? [\n \"This is an online store: give the header no button, since the platform puts the cart beside the navigation. Give the header one note instead: a short announcement for the bar above it, under 60 characters, about the shop from the brief (a promise it makes, such as its shipping, or what is new); never invent an offer, a discount, a price or a shipping threshold the brief does not give.\",\n ]\n : []),\n `Design seed: ${job.$id.slice(-6)}.`,\n ].join('\\n')\n}\n\n/** A store's Shop page, by its id: the page its catalog's whole list is placed on (AGL-3676). */\nexport function aiLayoutShopPageId(targets: Pick<AiLayoutTargets, 'listings'>): string | null {\n const products = (targets.listings ?? []).find((listing) => listing.kind === 'products')\n return products?.placements.find((placement) => placement.role === 'index')?.screenId ?? null\n}\n\n/** A validated language layout. */\nexport interface AiLayoutFrameBuilt {\n rootId: string\n nodes: NodesMap\n load: AiLoadEstimate | null\n /** What the last answer's gaps took out of the frame (`ai-layout-gaps.ts`). */\n dropped: string[]\n}\n\n/** The check a frame answer is held to: read, compiled, stored and checked as a layout, with the layout door's own checks. */\nexport function aiLayoutFrameCheck(input: {\n /** The header arrangement the site's look chose (AGL-3660); the answer's otherwise. */\n headerAlign?: 'start' | 'center'\n siteName: string\n homeId: string | null\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n extend: (tree: AiValidatedTree) => AiDoctrineViolation[]\n /** The site's design (`aiLayoutDesignOf`), whose pages' closing band the footer sits under. */\n design?: AiLayoutDesign | null\n}): AiGenerationCheck<AiLayoutFrameBuilt> {\n let answers = 0\n return (answer) => {\n // The last answer a generation takes has its gaps taken out rather than asked about again.\n answers += 1\n const last = answers >= AI_GENERATION_MAX_ATTEMPTS\n const frame = aiReadLayoutFrame(answer)\n if (input.headerAlign && frame.header) frame.header.align = input.headerAlign\n const compiled = aiCompileLayoutFrame(\n frame,\n {\n siteName: input.siteName,\n homeId: input.homeId,\n navPages: input.pages,\n closesDark: input.design ? aiLayoutDesignChoices(input.design).coverClose : false,\n // A site that sells carries its cart in the header (AGL-3676).\n cart: (input.targets.listings ?? []).some((listing) => listing.kind === 'products' && listing.cart !== false),\n // And a store's header is a storefront's: no button repeating its navigation, an announcement bar (AGL-3676).\n shopId: aiLayoutShopPageId(input.targets),\n },\n input.targets,\n )\n const context = {\n screenIds: [\n ...new Set([\n ...input.targets.pages.map((page) => page.id),\n ...input.pages.map((page) => page.id),\n ...(input.homeId ? [input.homeId] : []),\n ]),\n ],\n formIds: input.targets.forms.map((form) => form.id),\n homeScreenIds: input.targets.homeIds,\n codeBuilt: true,\n }\n const stored = aiLayoutStoredTree(compiled.tree, 'layout', context)\n if (stored.ok === false) {\n console.error('ai layout frame: a compiled layout did not store', {\n error: stored.error,\n })\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'layout-compile',\n message: 'This layout could not be built. Try again.',\n detail: stored.error,\n },\n ],\n }\n }\n // No gap and no internal reference in the words of a frame every published page shows.\n const navPages = [...input.targets.pages, ...input.pages]\n const copy = aiLayoutCopyCheck(\n stored.nodes,\n stored.rootId,\n {\n pages: navPages,\n ids: [...navPages.map((page) => page.id), ...input.targets.forms.map((form) => form.id)],\n },\n last,\n )\n const { dropped } = copy\n // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660).\n const nodes = aiSettleMechanicalRules(\n { rootId: stored.rootId, nodes: copy.nodes as unknown as Record<string, AiDoctrineNode> },\n 'layout',\n ).nodes as unknown as typeof copy.nodes\n const report = validateAiDoctrineTree(\n { rootId: stored.rootId, nodes },\n 'layout',\n context,\n )\n const violations = [\n ...report.violations,\n ...copy.violations,\n ...input.extend({\n rootId: stored.rootId,\n nodes,\n repairs: [],\n sourceIds: {},\n score: report.score as AiValidatedTree['score'],\n load: report.load,\n }),\n ]\n return {\n value: violations.length\n ? null\n : { rootId: stored.rootId, nodes, load: report.load, dropped },\n violations,\n }\n }\n}\n\n/** What a frame's links resolve against: the site's pages and its form, as a page's do. */\nexport function aiLayoutFrameTargets(\n job: Pick<AiJob, 'brief' | 'inputs'>,\n inventory: AiSiteInventory | null,\n): AiLayoutTargets {\n return aiLayoutPageTargets({ job, inventory, own: [] })\n}\n"],"names":["aiLayoutDesignChoices","aiCompileLayoutFrame","AI_LAYOUT_LANGUAGE_TEXT","aiReadLayoutFrame","aiLayoutCopyCheck","aiLayoutStoredTree","AI_GENERATION_MAX_ATTEMPTS","aiHomeScreenIds","AI_STEP_TIERS","aiSettleMechanicalRules","validateAiDoctrineTree","aiSiteKindDesignLines","aiJobStepBudget","aiJobBriefLine","AI_LAYOUT_SITE_PAGES_MAX","aiLayoutIsHomeSlug","aiLayoutSitePages","AI_LAYOUT_FRAME_THINKING_TOKENS","aiLayoutPageTargets","AI_SITE_NAME_TOKEN","AI_JOB_LAYOUT_LANGUAGE_TOKENS","AI_JOB_LAYOUT_LANGUAGE_BUDGET","tier","maxTokens","AI_LAYOUT_FRAME_KIND","AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS","text","join","cacheBreakpoint","aiLayoutSiteName","job","given","inputs","trim","aiLayoutNavPages","inventory","planned","own","screens","filter","row","template","map","id","label","name","slug","siteHome","some","page","slice","pages","length","home","find","aiLayoutHomeId","aiLayoutFramePrompt","input","targets","siteName","forms","formPageId","aiLayoutShopPageId","$id","products","listings","listing","kind","placements","placement","role","screenId","aiLayoutFrameCheck","answers","answer","last","frame","headerAlign","header","align","compiled","homeId","navPages","closesDark","design","coverClose","cart","shopId","context","screenIds","Set","formIds","form","homeScreenIds","homeIds","codeBuilt","stored","tree","ok","console","error","value","violations","rule","code","message","detail","copy","nodes","rootId","ids","dropped","report","extend","repairs","sourceIds","score","load","aiLayoutFrameTargets"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,qBAAqB,QAA6B,yCAAqC;AAChG,SAASC,oBAAoB,QAAQ,wCAAoC;AACzE,SAEEC,uBAAuB,EACvBC,iBAAiB,QACZ,2CAAuC;AAK9C,SAASC,iBAAiB,QAAQ,uCAAmC;AACrE,SAASC,kBAAkB,QAAQ,wCAAoC;AACvE,SAASC,0BAA0B,QAAQ,qCAAiC;AAE5E,SACEC,eAAe,QAEV,gCAA4B;AACnC,SAASC,aAAa,QAAQ,0BAAsB;AAEpD,SACEC,uBAAuB,EACvBC,sBAAsB,QAG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OAASA,KAAKjD,EAAE;aAAE;QAC1F,GACAgC;QAEF,MAAM,EAAEoC,OAAO,EAAE,GAAGJ;QACpB,8FAA8F;QAC9F,MAAMC,QAAQnG,wBACZ;YAAEoG,QAAQb,OAAOa,MAAM;YAAED,OAAOD,KAAKC,KAAK;QAA8C,GACxF,UACAA,KAAK;QACP,MAAMI,SAAStG,uBACb;YAAEmG,QAAQb,OAAOa,MAAM;YAAED;QAAM,GAC/B,UACApB;QAEF,MAAMc,aAAa;eACdU,OAAOV,UAAU;eACjBK,KAAKL,UAAU;eACf7C,MAAMwD,MAAM,CAAC;gBACdJ,QAAQb,OAAOa,MAAM;gBACrBD;gBACAM,SAAS,EAAE;gBACXC,WAAW,CAAC;gBACZC,OAAOJ,OAAOI,KAAK;gBACnBC,MAAML,OAAOK,IAAI;YACnB;SACD;QACD,OAAO;YACLhB,OAAOC,WAAWlD,MAAM,GACpB,OACA;gBAAEyD,QAAQb,OAAOa,MAAM;gBAAED;gBAAOS,MAAML,OAAOK,IAAI;gBAAEN;YAAQ;YAC/DT;QACF;IACF;AACF;AAEA,yFAAyF,GACzF,OAAO,SAASgB,qBACdxF,GAAoC,EACpCK,SAAiC;IAEjC,OAAOjB,oBAAoB;QAAEY;QAAKK;QAAWE,KAAK,EAAE;IAAC;AACvD"}
@@ -18,6 +18,7 @@ import type { NodesMap } from '@aglyn/aglyn/types/nodes';
18
18
  import { type AiBuildPlanScreen } from '../model/ai-build-plan';
19
19
  import type { AiJob, AiJobPlan } from '../model/ai-jobs.types';
20
20
  import { type AiSiteInventory } from '../model/ai-site-inventory';
21
+ import { type AiLayoutListing } from '../layout-language/ai-layout-listings';
21
22
  import { type AiLayoutSection, type AiLayoutSettlement } from '../layout-language/ai-layout-language';
22
23
  import type { AiLayoutTargets } from '../layout-language/ai-layout-links';
23
24
  import { type AiGenerationCheck, type AiValidatedGeneration } from '../runtime/ai-doctrine';
@@ -108,6 +109,14 @@ export declare function aiLayoutPageTargets(input: {
108
109
  inventory: AiSiteInventory | null;
109
110
  own: ReadonlyArray<string | null | undefined>;
110
111
  }): AiLayoutTargets;
112
+ /**
113
+ * A page's listings with each dataset's held to the site's inventory
114
+ * (AGL-3616): a records listing is kept only where the site has the dataset —
115
+ * the tree check admits a repeat over no other, and a card left repeating
116
+ * over nothing would show its `{{item.*}}` — and one that names no fields
117
+ * takes the inventory's, in the dataset's order.
118
+ */
119
+ export declare function aiLayoutListingsWithDatasets(listings: readonly AiLayoutListing[], inventory: Pick<AiSiteInventory, 'datasets'> | null): AiLayoutListing[];
111
120
  /**
112
121
  * The page check's context with what a section listing the blog's posts
113
122
  * binds (AGL-3676): each post's card links its post and shows its cover by
@@ -25,7 +25,7 @@ import { aiLayoutStoredTree } from "../layout-language/ai-layout-store.js";
25
25
  import { AI_GENERATION_MAX_ATTEMPTS } from "../runtime/ai-generation-bounds.js";
26
26
  import { AI_STEP_TIERS } from "../providers/catalog.js";
27
27
  import { runValidatedGeneration } from "../runtime/ai-doctrine.js";
28
- import { validateAiDoctrineTree } from "../runtime/ai-doctrine-validators.js";
28
+ import { aiSettleMechanicalRules, validateAiDoctrineTree } from "../runtime/ai-doctrine-validators.js";
29
29
  import { aiSiteKindDesignLines, aiSiteKindOfInputs } from "../model/ai-site-kinds.js";
30
30
  import { aiSiteSeed } from "../model/ai-site-look.js";
31
31
  import { aiOriginJobId } from "./ai-job-draft-ids.js";
@@ -159,10 +159,40 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
159
159
  props: component.props
160
160
  })),
161
161
  facts: aiLayoutFacts(job),
162
- // The site's catalog and blog, and the sections that list them (AGL-3676).
163
- listings: aiLayoutListingsOf(job.inputs)
162
+ // The site's catalog and blog, and the sections that list them (AGL-3676),
163
+ // and its datasets (AGL-3616).
164
+ listings: aiLayoutListingsWithDatasets(aiLayoutListingsOf(job.inputs), inventory)
164
165
  };
165
166
  }
167
+ /**
168
+ * A page's listings with each dataset's held to the site's inventory
169
+ * (AGL-3616): a records listing is kept only where the site has the dataset —
170
+ * the tree check admits a repeat over no other, and a card left repeating
171
+ * over nothing would show its `{{item.*}}` — and one that names no fields
172
+ * takes the inventory's, in the dataset's order.
173
+ */ export function aiLayoutListingsWithDatasets(listings, inventory) {
174
+ return listings.flatMap((listing)=>{
175
+ var _listing_fields;
176
+ if (listing.kind !== 'records') return [
177
+ listing
178
+ ];
179
+ const row = inventory == null ? void 0 : inventory.datasets.find((dataset)=>dataset.id === listing.datasetId);
180
+ if (!row) return [];
181
+ const fields = ((_listing_fields = listing.fields) == null ? void 0 : _listing_fields.length) ? listing.fields : row.fields.map((name, index)=>{
182
+ var _row_fieldIds;
183
+ return {
184
+ id: ((_row_fieldIds = row.fieldIds) == null ? void 0 : _row_fieldIds[index]) || name,
185
+ name,
186
+ type: 'text'
187
+ };
188
+ });
189
+ return fields.length ? [
190
+ _extends({}, listing, {
191
+ fields
192
+ })
193
+ ] : [];
194
+ });
195
+ }
166
196
  /**
167
197
  * The page check's context with what a section listing the blog's posts
168
198
  * binds (AGL-3676): each post's card links its post and shows its cover by
@@ -201,6 +231,11 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
201
231
  // A store's newsletter field (AGL-3676), placed by the platform.
202
232
  return `${index + 1}. "${section.name}"${places}; the platform places the newsletter sign-up field here: write its heading and one line on what subscribers hear about, from the brief, and no form, button or offer the brief does not make`;
203
233
  }
234
+ if ((listed == null ? void 0 : listed.listing.kind) === 'records') {
235
+ // One of the site's datasets (AGL-3616), repeated by the platform over its records.
236
+ const names = listed.listing.records.length ? ` (${listed.listing.records.slice(0, 6).map((name)=>`“${name}”`).join(', ')})` : '';
237
+ return `${index + 1}. "${section.name}"${places}; the platform lists the records of the dataset “${listed.listing.name}”${names} here itself, one card each: write only its heading and a line about them, and no cards, list or images for them`;
238
+ }
204
239
  if (listed) {
205
240
  return `${index + 1}. "${section.name}"${places}; the platform lists ${listed.listing.name}'s ${listed.listing.kind} here itself, with their photos and links: write only its heading and a line about them, and no cards, list or images for them`;
206
241
  }
@@ -374,7 +409,12 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
374
409
  ] : []
375
410
  ]
376
411
  }, last);
377
- const { nodes, dropped } = copy;
412
+ const { dropped } = copy;
413
+ // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660).
414
+ const nodes = aiSettleMechanicalRules({
415
+ rootId: CANVAS_ROOT_ELEMENT_ID,
416
+ nodes: copy.nodes
417
+ }, 'page').nodes;
378
418
  const report = validateAiDoctrineTree({
379
419
  rootId: CANVAS_ROOT_ELEMENT_ID,
380
420
  nodes