@aglyn/plugins-ai 1.0.0-beta.219 → 1.0.0-beta.221

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 (181) hide show
  1. package/package.json +18 -18
  2. package/src/lib/billing/ai-month-meter.d.ts +51 -0
  3. package/src/lib/billing/ai-month-meter.js +89 -0
  4. package/src/lib/billing/ai-month-meter.js.map +1 -0
  5. package/src/lib/billing/ai-overage-close.d.ts +11 -33
  6. package/src/lib/billing/ai-overage-close.js +4 -3
  7. package/src/lib/billing/ai-overage-close.js.map +1 -1
  8. package/src/lib/billing/ai-overage-cutover.d.ts +28 -12
  9. package/src/lib/billing/ai-overage-cutover.js +1 -28
  10. package/src/lib/billing/ai-overage-cutover.js.map +1 -1
  11. package/src/lib/billing/ai-overage-ledger.js +1 -1
  12. package/src/lib/billing/ai-overage-ledger.js.map +1 -1
  13. package/src/lib/billing/ai-overage-standing.js +1 -1
  14. package/src/lib/billing/ai-overage-standing.js.map +1 -1
  15. package/src/lib/components/ai-allotment-editor.component.js +1 -1
  16. package/src/lib/components/ai-allotment-editor.component.js.map +1 -1
  17. package/src/lib/components/ai-assist-provider.component.js +3 -2
  18. package/src/lib/components/ai-assist-provider.component.js.map +1 -1
  19. package/src/lib/components/ai-automation-zones.d.ts +63 -0
  20. package/src/lib/components/ai-automation-zones.js +31 -0
  21. package/src/lib/components/ai-automation-zones.js.map +1 -0
  22. package/src/lib/components/ai-describe-automation.component.d.ts +1 -1
  23. package/src/lib/components/ai-describe-automation.component.js.map +1 -1
  24. package/src/lib/components/ai-describe-button.component.d.ts +6 -3
  25. package/src/lib/components/ai-describe-button.component.js +4 -1
  26. package/src/lib/components/ai-describe-button.component.js.map +1 -1
  27. package/src/lib/components/ai-explain-automation.component.d.ts +1 -1
  28. package/src/lib/components/ai-explain-automation.component.js.map +1 -1
  29. package/src/lib/components/billing-ai-allotments.component.js +1 -1
  30. package/src/lib/components/billing-ai-allotments.component.js.map +1 -1
  31. package/src/lib/components/billing-assist-overage-card.component.js +1 -1
  32. package/src/lib/components/billing-assist-overage-card.component.js.map +1 -1
  33. package/src/lib/constants.d.ts +5 -0
  34. package/src/lib/constants.js +4 -0
  35. package/src/lib/constants.js.map +1 -1
  36. package/src/lib/declarations.js +2 -0
  37. package/src/lib/declarations.js.map +1 -1
  38. package/src/lib/declarations.server.js +24 -10
  39. package/src/lib/declarations.server.js.map +1 -1
  40. package/src/lib/insights/ai-dataset-catalog.d.ts +49 -0
  41. package/src/lib/insights/ai-dataset-catalog.js +57 -0
  42. package/src/lib/insights/ai-dataset-catalog.js.map +1 -0
  43. package/src/lib/insights/ai-figure-readers.d.ts +6 -39
  44. package/src/lib/insights/ai-figure-readers.js +2 -391
  45. package/src/lib/insights/ai-figure-readers.js.map +1 -1
  46. package/src/lib/insights/ai-insight-digest.d.ts +10 -1
  47. package/src/lib/insights/ai-insight-digest.js +16 -4
  48. package/src/lib/insights/ai-insight-digest.js.map +1 -1
  49. package/src/lib/insights/ai-insight-readers.d.ts +1 -1
  50. package/src/lib/insights/ai-insight-readers.js.map +1 -1
  51. package/src/lib/jobs/ai-job-component-step.d.ts +6 -1
  52. package/src/lib/jobs/ai-job-component-step.js +23 -6
  53. package/src/lib/jobs/ai-job-component-step.js.map +1 -1
  54. package/src/lib/jobs/ai-job-draft-ids.js +11 -0
  55. package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
  56. package/src/lib/jobs/ai-job-email-step.d.ts +5 -1
  57. package/src/lib/jobs/ai-job-email-step.js +10 -1
  58. package/src/lib/jobs/ai-job-email-step.js.map +1 -1
  59. package/src/lib/jobs/ai-job-form-step.d.ts +17 -1
  60. package/src/lib/jobs/ai-job-form-step.js +60 -8
  61. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  62. package/src/lib/jobs/ai-job-generation.d.ts +21 -0
  63. package/src/lib/jobs/ai-job-generation.js +53 -1
  64. package/src/lib/jobs/ai-job-generation.js.map +1 -1
  65. package/src/lib/jobs/ai-job-insight-step.js +1 -1
  66. package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
  67. package/src/lib/jobs/ai-job-layout-step.d.ts +15 -4
  68. package/src/lib/jobs/ai-job-layout-step.js +45 -12
  69. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  70. package/src/lib/jobs/ai-job-plan-conformance.d.ts +5 -0
  71. package/src/lib/jobs/ai-job-plan-conformance.js +7 -1
  72. package/src/lib/jobs/ai-job-plan-conformance.js.map +1 -1
  73. package/src/lib/jobs/ai-job-plan-creations.d.ts +80 -0
  74. package/src/lib/jobs/ai-job-plan-creations.js +199 -0
  75. package/src/lib/jobs/ai-job-plan-creations.js.map +1 -0
  76. package/src/lib/jobs/ai-job-plan-step.d.ts +8 -2
  77. package/src/lib/jobs/ai-job-plan-step.js +20 -6
  78. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  79. package/src/lib/jobs/ai-job-site-step.d.ts +2 -0
  80. package/src/lib/jobs/ai-job-site-step.js +6 -6
  81. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  82. package/src/lib/jobs/ai-job-template-step.d.ts +9 -6
  83. package/src/lib/jobs/ai-job-template-step.js +72 -15
  84. package/src/lib/jobs/ai-job-template-step.js.map +1 -1
  85. package/src/lib/jobs/ai-jobs.js +1 -1
  86. package/src/lib/jobs/ai-jobs.js.map +1 -1
  87. package/src/lib/jobs/ai-workflow-records.d.ts +5 -4
  88. package/src/lib/jobs/ai-workflow-records.js +26 -22
  89. package/src/lib/jobs/ai-workflow-records.js.map +1 -1
  90. package/src/lib/model/ai-allotments.d.ts +16 -3
  91. package/src/lib/model/ai-allotments.js +34 -11
  92. package/src/lib/model/ai-allotments.js.map +1 -1
  93. package/src/lib/model/ai-job-creations.d.ts +55 -0
  94. package/src/lib/model/ai-job-creations.js +85 -0
  95. package/src/lib/model/ai-job-creations.js.map +1 -0
  96. package/src/lib/model/ai-page-job.d.ts +3 -2
  97. package/src/lib/model/ai-page-job.js +4 -3
  98. package/src/lib/model/ai-page-job.js.map +1 -1
  99. package/src/lib/model/ai-site-job.d.ts +4 -2
  100. package/src/lib/model/ai-site-job.js +8 -4
  101. package/src/lib/model/ai-site-job.js.map +1 -1
  102. package/src/lib/model/ai-template-subjects.d.ts +10 -0
  103. package/src/lib/model/ai-template-subjects.js +14 -0
  104. package/src/lib/model/ai-template-subjects.js.map +1 -1
  105. package/src/lib/model/ai-tokens.js +1 -1
  106. package/src/lib/model/ai-tokens.js.map +1 -1
  107. package/src/lib/model/ai-usage-by-user.js +1 -1
  108. package/src/lib/model/ai-usage-by-user.js.map +1 -1
  109. package/src/lib/providers/catalog.js +1 -1
  110. package/src/lib/providers/catalog.js.map +1 -1
  111. package/src/lib/providers/model-choice.js +1 -1
  112. package/src/lib/providers/model-choice.js.map +1 -1
  113. package/src/lib/runtime/ai-device-audit.d.ts +1 -1
  114. package/src/lib/runtime/ai-device-audit.js +1 -1
  115. package/src/lib/runtime/ai-device-audit.js.map +1 -1
  116. package/src/lib/runtime/ai-eval-live.js +1 -1
  117. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  118. package/src/lib/runtime/ai-eval.d.ts +1 -1
  119. package/src/lib/runtime/ai-eval.js.map +1 -1
  120. package/src/lib/runtime/ai-gate.js +1 -1
  121. package/src/lib/runtime/ai-gate.js.map +1 -1
  122. package/src/lib/runtime/ai-palette.d.ts +1 -1
  123. package/src/lib/runtime/ai-palette.generated.d.ts +1 -1
  124. package/src/lib/runtime/ai-palette.generated.js +1 -1
  125. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  126. package/src/lib/runtime/ai-palette.js.map +1 -1
  127. package/src/lib/runtime/site-inventory.js +28 -22
  128. package/src/lib/runtime/site-inventory.js.map +1 -1
  129. package/src/lib/server/ai-admin-org.js +1 -1
  130. package/src/lib/server/ai-admin-org.js.map +1 -1
  131. package/src/lib/server/ai-admin-orgs-spend.js +1 -1
  132. package/src/lib/server/ai-admin-orgs-spend.js.map +1 -1
  133. package/src/lib/server/ai-admin-signals.js +1 -1
  134. package/src/lib/server/ai-admin-signals.js.map +1 -1
  135. package/src/lib/server/ai-allotments.js +1 -1
  136. package/src/lib/server/ai-allotments.js.map +1 -1
  137. package/src/lib/server/ai-assist.js +2 -2
  138. package/src/lib/server/ai-assist.js.map +1 -1
  139. package/src/lib/server/assist-chat.d.ts +1 -1
  140. package/src/lib/server/assist-chat.js +2 -2
  141. package/src/lib/server/assist-chat.js.map +1 -1
  142. package/src/lib/server/billing-credits.d.ts +5 -0
  143. package/src/lib/server/billing-credits.js +8 -2
  144. package/src/lib/server/billing-credits.js.map +1 -1
  145. package/src/lib/server/billing-overage.js +2 -2
  146. package/src/lib/server/billing-overage.js.map +1 -1
  147. package/src/lib/testing/stand-in-dataset-index.d.ts +20 -0
  148. package/src/lib/testing/stand-in-dataset-index.js +80 -0
  149. package/src/lib/testing/stand-in-dataset-index.js.map +1 -0
  150. package/src/lib/usage/ai-allotment-alerts.d.ts +10 -7
  151. package/src/lib/usage/ai-allotment-alerts.js +31 -14
  152. package/src/lib/usage/ai-allotment-alerts.js.map +1 -1
  153. package/src/lib/usage/ai-quota-checks.d.ts +37 -0
  154. package/src/lib/usage/ai-quota-checks.js +69 -0
  155. package/src/lib/usage/ai-quota-checks.js.map +1 -0
  156. package/src/lib/usage/ai-usage-alerts.js +22 -10
  157. package/src/lib/usage/ai-usage-alerts.js.map +1 -1
  158. package/src/lib/usage/ai-usage-by-user.js +1 -1
  159. package/src/lib/usage/ai-usage-by-user.js.map +1 -1
  160. package/src/lib/usage/assist-ceiling.d.ts +2 -2
  161. package/src/lib/usage/assist-ceiling.js +4 -4
  162. package/src/lib/usage/assist-ceiling.js.map +1 -1
  163. package/src/lib/usage/assist-credits.d.ts +494 -0
  164. package/src/lib/usage/assist-credits.js +524 -0
  165. package/src/lib/usage/assist-credits.js.map +1 -0
  166. package/src/lib/usage/assist-free-taste.d.ts +1 -1
  167. package/src/lib/usage/assist-free-taste.js +1 -1
  168. package/src/lib/usage/assist-free-taste.js.map +1 -1
  169. package/src/lib/usage/assist-signal-mining.js +1 -1
  170. package/src/lib/usage/assist-signal-mining.js.map +1 -1
  171. package/src/lib/usage/assist-spend-guards.d.ts +153 -0
  172. package/src/lib/usage/assist-spend-guards.js +182 -0
  173. package/src/lib/usage/assist-spend-guards.js.map +1 -0
  174. package/src/lib/usage/assist-usage.d.ts +1 -1
  175. package/src/lib/usage/assist-usage.js +1 -1
  176. package/src/lib/usage/assist-usage.js.map +1 -1
  177. package/src/lib/usage/staff-org-ai.js +1 -1
  178. package/src/lib/usage/staff-org-ai.js.map +1 -1
  179. package/src/lib/usage-axes.d.ts +10 -0
  180. package/src/lib/usage-axes.js +40 -2
  181. package/src/lib/usage-axes.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 {\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 { 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\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/** A form job is admitted for a site of the job's own org whose plan has forms, with a form to spare. */\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 })\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.\n if (creation?.duplicateOf && inventory.forms.some((form) => form.id === creation.duplicateOf)) {\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: aiJobFormPrompt(job, plan, name, {\n audience,\n submissions: decisions.submissions,\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 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":["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","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","listOf","aiFormOutputNote","sentences","label","aiJobFormPrompt","job","context","audience","SUBMISSION_WORDS","inbox","aiFormJobAdmission","orgId","org","createAiJobFormStep","deps","readInventory","duplicate","now","signal","modelFor","orgSnapshot","Error","output","extra","resource","versionId","hostSubdomain","load","note","model","draftId","written","outputs","inventory","Promise","all","creation","duplicateOf","forms","some","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,SACEA,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,SAASC,YAAY,QA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B5C,MAAMxC,MAAM;YAC7BvD,qBAAqB;gBACnBqC,MAAM;oBAAEmC,QAAQsH,OAAOhJ,KAAK,CAAC0B,MAAM;oBAAEC,OAAOqH,OAAOhJ,KAAK,CAAC2B,KAAK;gBAAuC;gBACrGkG;YACF;SACD,CACEpF,MAAM,CAAC2C,SACPxG,IAAI,CAAC;QACR,OAAO,aACF4K;YACH5B,SAAS;gBAACV,OAAOwC,OAAO;oBAAEnC,MAAMyB,OAAOhJ,KAAK,CAACuH,IAAI;oBAAEC;gBAAK;aAAG;;IAE/D;AACF;AAEA,OAAO,MAAMmC,mBAAmBlD,sBAAqB;AAErD,6FAA6F,GAC7F,OAAO,SAASmD;IACd/L,kBAAkB,QAAQ8L,kBAAkB;QAAExL,WAAWD;IAA4B;IACrFvB,uBAAuB,QAAQ2J;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 {\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 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":["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,SACEA,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,SAASC,yBAAyB,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A9H;YACA4C,OAAOsB,MAAMtB,KAAK;YAClBM,MAAM;gBACJP,QAAQuB,MAAMvB,MAAM;gBACpBD,YAAYwB,MAAMxB,UAAU;gBAC5BqB,QAAQG,MAAMH,MAAM;gBACpBZ,kBAAkBe,MAAMf,gBAAgB;gBACxC1C,SAASyD,MAAMzD,OAAO;YACxB;YACA2H;QACF;QACA,IAAIiD,MAAMlB,EAAE,KAAK,OAAO;YACtB,IAAIkB,MAAMf,MAAM,KAAK,KAAK,MAAM,IAAI9B,MAAM,CAAC,KAAK,EAAE7C,OAAO,sCAAsC,CAAC;YAChG,OAAO,aAAKwF;gBAAOd,QAAQ7L,cAAc6M,MAAMd,KAAK;;QACtD;QACA,kFAAkF;QAClF,MAAMxB,OAAO;YACX5B,iBAAiBjD,MAAMxC,MAAM;YAC7BvD,qBAAqB;gBACnBqC,MAAM;oBAAEmC,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"}
@@ -40,6 +40,27 @@ export declare function aiPlanCreation(plan: AiJobPlan | null, kind: AiBuildPlan
40
40
  export declare function aiJobBriefLine(job: Pick<AiJob, 'brief'>): string;
41
41
  /** The confirmed plan as reference lines; none when there is no confirmed plan. */
42
42
  export declare function aiPlanReferenceLines(plan: AiJobPlan | null): string[];
43
+ /**
44
+ * The most of a source's tree a build is shown, as JSON characters: about
45
+ * 3,000 tokens, a whole layout or page template, never a site (AGL-3143 §14).
46
+ */
47
+ export declare const AI_COPY_SOURCE_MAX_CHARS = 12000;
48
+ /**
49
+ * The record a plan's copy starts from, as the build that replaces the copy
50
+ * is shown it (AGL-3143 §14): its tree in the node-map shape the tool takes,
51
+ * with the one instruction that makes it a start rather than an example.
52
+ * Empty when there is no tree to show or it is too large to show whole, and
53
+ * the build then starts from the brief and the plan.
54
+ *
55
+ * A copy whose source cannot keep what the plan promised is never minted,
56
+ * because the review after it would refuse it with certainty and the member
57
+ * could only try the same copy again. Measured on 2026-09-22 (job
58
+ * `Pq3pgvMH0D`): "copy the interior layout and add a sidebar" could only end
59
+ * in review. Building from the source keeps what the plan does not change —
60
+ * the firm's header, its footer, their copy — which a build from the brief
61
+ * alone would draw again from nothing.
62
+ */
63
+ export declare function aiCopySourceLines(noun: string, label: string, nodes: Readonly<Record<string, unknown>> | null): string[];
43
64
  /** The reusable components a tree places, by the id each instance names. */
44
65
  export declare function aiPlacedComponentIds(tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>): Set<string>;
45
66
  /**
@@ -15,7 +15,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { REUSABLE_INSTANCE_COMPONENT_ID, REUSABLE_INSTANCE_PROP_VALUES_KEY } from "@aglyn/aglyn/app-utils/reusable-component-keys";
18
+ import { CANVAS_ROOT_ELEMENT_ID } from "@aglyn/aglyn/foundation/constants/canvas";
18
19
  import { AI_BUILD_PLAN_EMBED_HOST_NAMES, AI_PLAN_NEW_REF_PREFIX, isAiPlanNewRef } from "../model/ai-build-plan.js";
20
+ import { isAiUnreadToken } from "../model/ai-template-subjects.js";
19
21
  import { aiAnswerTree } from "../runtime/ai-doctrine.js";
20
22
  import { aiBracketedFacts, aiTreeCopy, walkTree } from "../runtime/ai-doctrine-validators.js";
21
23
  import { AI_INSTANCE_REF_PROP } from "../runtime/ai-node-tree.js";
@@ -62,7 +64,10 @@ import { AI_JOB_BRIEF_MAX_CHARS } from "./ai-job-text-step.js";
62
64
  }
63
65
  for (const entry of plan.create){
64
66
  const from = entry.duplicateOf ? `, from a copy of ${referenceOf(plan, entry.duplicateOf)}` : '';
65
- const fields = entry.fields.length ? ` Fields: ${entry.fields.join(', ')}.` : '';
67
+ // A template's slug or timestamp is filled, never shown, so a build told
68
+ // it is a field prints it (AGL-3143 §16).
69
+ const shown = entry.kind === 'template' ? entry.fields.filter((field)=>!isAiUnreadToken(field)) : entry.fields;
70
+ const fields = shown.length ? ` Fields: ${shown.join(', ')}.` : '';
66
71
  lines.push(`- create the ${entry.kind} "${entry.name}"${from}: ${entry.why}${fields}`);
67
72
  }
68
73
  for (const screen of plan.screens){
@@ -77,6 +82,53 @@ import { AI_JOB_BRIEF_MAX_CHARS } from "./ai-job-text-step.js";
77
82
  }
78
83
  return lines.length > 1 ? lines : [];
79
84
  }
85
+ /**
86
+ * The most of a source's tree a build is shown, as JSON characters: about
87
+ * 3,000 tokens, a whole layout or page template, never a site (AGL-3143 §14).
88
+ */ export const AI_COPY_SOURCE_MAX_CHARS = 12000;
89
+ /**
90
+ * The record a plan's copy starts from, as the build that replaces the copy
91
+ * is shown it (AGL-3143 §14): its tree in the node-map shape the tool takes,
92
+ * with the one instruction that makes it a start rather than an example.
93
+ * Empty when there is no tree to show or it is too large to show whole, and
94
+ * the build then starts from the brief and the plan.
95
+ *
96
+ * A copy whose source cannot keep what the plan promised is never minted,
97
+ * because the review after it would refuse it with certainty and the member
98
+ * could only try the same copy again. Measured on 2026-09-22 (job
99
+ * `Pq3pgvMH0D`): "copy the interior layout and add a sidebar" could only end
100
+ * in review. Building from the source keeps what the plan does not change —
101
+ * the firm's header, its footer, their copy — which a build from the brief
102
+ * alone would draw again from nothing.
103
+ */ export function aiCopySourceLines(noun, label, nodes) {
104
+ if (!nodes || !isRecordNode(nodes[CANVAS_ROOT_ELEMENT_ID])) return [];
105
+ const shaped = {};
106
+ for (const [id, node] of Object.entries(nodes)){
107
+ if (!isRecordNode(node)) continue;
108
+ const { componentId, props, sx, nodes: children } = node;
109
+ shaped[id] = _extends({
110
+ componentId
111
+ }, isRecordNode(props) && Object.keys(props).length ? {
112
+ props
113
+ } : {}, isRecordNode(sx) && Object.keys(sx).length ? {
114
+ sx
115
+ } : {}, Array.isArray(children) && children.length ? {
116
+ nodes: children
117
+ } : {});
118
+ }
119
+ const tree = JSON.stringify({
120
+ rootId: CANVAS_ROOT_ELEMENT_ID,
121
+ nodes: shaped
122
+ });
123
+ if (tree.length > AI_COPY_SOURCE_MAX_CHARS) return [];
124
+ return [
125
+ `The plan starts from a copy of the ${noun} "${label}", which lacks part of what the plan gives it. Build from it: keep every part the plan does not change, and add what the plan adds. Its tree, in the node-map shape the tool takes:`,
126
+ tree
127
+ ];
128
+ }
129
+ function isRecordNode(value) {
130
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
131
+ }
80
132
  /** The reusable components a tree places, by the id each instance names. */ export function aiPlacedComponentIds(tree) {
81
133
  const placed = new Set();
82
134
  const nodes = tree.nodes;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-generation.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 {\n REUSABLE_INSTANCE_COMPONENT_ID,\n REUSABLE_INSTANCE_PROP_VALUES_KEY,\n} from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport {\n AI_BUILD_PLAN_EMBED_HOST_NAMES,\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildPlanCreate,\n type AiBuildPlanCreateKind,\n} from '../model/ai-build-plan'\nimport type {\n AiJob,\n AiJobOutput,\n AiJobPlan,\n AiJobReview,\n AiJobReviewOutlineNode,\n} from '../model/ai-jobs.types'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { aiAnswerTree, type AiGenerationSpend, type AiValidatedTree } from '../runtime/ai-doctrine'\nimport {\n aiBracketedFacts,\n aiTreeCopy,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTree,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { AI_INSTANCE_REF_PROP } from '../runtime/ai-node-tree'\nimport type { AssistTokenUsage } from '../usage/assist-usage'\nimport { AI_JOB_BRIEF_MAX_CHARS, type AiJobStepOutcome } from './ai-job-text-step'\n\n/**\n * What the generation steps share (AGL-2909): reading the plan a member\n * confirmed, stating it to the model as references, and turning what a\n * generation spent or refused into the outcome the machine records.\n *\n * A generation step runs after its job's plan step, once a member confirmed\n * the plan, so the plan is part of what it executes: the records it reuses,\n * and the creation it builds. The plan travels as references — ids, names,\n * reasons — never as a document (AGL-2937).\n */\n\nexport const AI_JOB_ZERO_USAGE: AssistTokenUsage = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n}\n\n/** The job's plan once a member confirmed it; `null` before that, or for a job that never planned. */\nexport function aiConfirmedPlan(job: Pick<AiJob, 'plan'>): AiJobPlan | null {\n return job.plan?.status === 'confirmed' ? job.plan : null\n}\n\n/** The creation of one kind the plan names; the first when it names several. */\nexport function aiPlanCreation(\n plan: AiJobPlan | null,\n kind: AiBuildPlanCreateKind,\n): AiBuildPlanCreate | null {\n return plan?.create.find((entry) => entry.kind === kind) ?? null\n}\n\n/** A plan reference as the model reads it: the id with the name it was planned under. */\nfunction referenceOf(plan: AiJobPlan, ref: string): string {\n const label = plan.labels?.[ref]\n return label ? `${ref} (\"${label}\")` : ref\n}\n\n/** The user turn's opening: the brief, cut at the ceiling every job step keeps. */\nexport function aiJobBriefLine(job: Pick<AiJob, 'brief'>): string {\n return `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`\n}\n\n/** The confirmed plan as reference lines; none when there is no confirmed plan. */\nexport function aiPlanReferenceLines(plan: AiJobPlan | null): string[] {\n if (!plan) return []\n const lines = ['Confirmed plan:']\n for (const entry of plan.reuse) {\n lines.push(`- reuse the ${entry.kind === 'screen' ? 'page' : entry.kind} ${referenceOf(plan, entry.id)}: ${entry.purpose}`)\n }\n for (const entry of plan.create) {\n const from = entry.duplicateOf ? `, from a copy of ${referenceOf(plan, entry.duplicateOf)}` : ''\n const fields = entry.fields.length ? ` Fields: ${entry.fields.join(', ')}.` : ''\n lines.push(`- create the ${entry.kind} \"${entry.name}\"${from}: ${entry.why}${fields}`)\n }\n for (const screen of plan.screens) {\n const sections = screen.sections.map((section) => section.name).join(', ')\n lines.push(`- the page \"${screen.title}\" at ${screen.slug}${sections ? `: ${sections}` : ''}`)\n }\n // The one place a Video embed is admitted (AGL-3433): where the plan lists it, at the brief's link or none.\n for (const embed of plan.embeds ?? []) {\n const where = isAiPlanNewRef(embed.where)\n ? `the component \"${embed.where.slice(AI_PLAN_NEW_REF_PREFIX.length)}\"`\n : embed.where\n const link = embed.url ? `, url ${embed.url}` : ', url left empty for the site owner to paste'\n lines.push(`- embed a ${AI_BUILD_PLAN_EMBED_HOST_NAMES[embed.host]} player (videoEmbed) on ${where}${link}`)\n }\n return lines.length > 1 ? lines : []\n}\n\n/** The reusable components a tree places, by the id each instance names. */\nexport function aiPlacedComponentIds(tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>): Set<string> {\n const placed = new Set<string>()\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n for (const { node } of walkTree({ rootId: tree.rootId, nodes })) {\n const ref = node.props?.[AI_INSTANCE_REF_PROP]\n if (node.componentId === REUSABLE_INSTANCE_COMPONENT_ID && typeof ref === 'string') {\n placed.add(ref)\n }\n }\n return placed\n}\n\n/**\n * Rule 7 on a generated tree: every component the confirmed plan reuses is\n * placed. `noun` names what the tree builds, in the finding.\n */\nexport function aiPlanReuseViolations(\n inventory: AiSiteInventory | null,\n plan: AiJobPlan | null,\n placed: ReadonlySet<string>,\n noun: string,\n): AiDoctrineViolation[] {\n const names = new Map((inventory?.components ?? []).map((component) => [component.id, component.name]))\n const reused = [\n ...new Set(\n (plan?.reuse ?? []).filter((entry) => entry.kind === 'component').map((entry) => entry.id),\n ),\n ]\n const missing = reused.filter((id) => !placed.has(id))\n if (!missing.length) return []\n const listed = missing.map((id) => `\"${names.get(id) ?? id}\"`).join(', ')\n return [\n {\n rule: 7,\n code: 'plan-reuse-not-placed',\n message: `The confirmed plan reuses ${listed}, and the ${noun} does not place ${\n missing.length === 1 ? 'it' : 'them'\n }. Place every component the plan reuses.`,\n },\n ]\n}\n\n/** What a generation spent, as the step's outcome carries it for the meter. */\nexport function aiGenerationSpent(\n spend: AiGenerationSpend,\n): Pick<AiJobStepOutcome, 'outputs' | 'usage' | 'estCostUsd' | 'model' | 'stopReason'> {\n return {\n outputs: [],\n usage: spend.usage,\n estCostUsd: spend.estCostUsd,\n model: spend.model,\n stopReason: spend.stopReason,\n }\n}\n\n/** The most node ids, or plan paths, one finding keeps on its review (AGL-3078). */\nexport const AI_JOB_REVIEW_REFS_MAX = 24\n/** The longest node id or plan path a review keeps, in characters. */\nexport const AI_JOB_REVIEW_REF_MAX_CHARS = 64\n/** How far below a node a finding names its outline goes: the node, its children and theirs. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_DEPTH = 2\n/** The most nodes a review outlines, across all its findings. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_NODES = 40\n/** The most names an outlined node lists of its props, of its sx keys, or of its children. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_NAMES = 16\n/** The most bytes a review's outline takes as JSON, whatever the counts above allow. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_BYTES = 4_096\n\n/** A Grid's layout props, whose written values an outline keeps. */\nconst AI_JOB_REVIEW_GRID_PROPS = [\n 'container',\n 'size',\n 'offset',\n 'direction',\n 'wrap',\n 'spacing',\n 'rowSpacing',\n 'columnSpacing',\n 'columns',\n] as const\n\n/** A node id or plan path a review keeps: no whitespace, slash or quote, so never copy or an address. */\nconst REVIEW_REF = /^[^\\s/\\\\\"'<>]+$/\n/** An element id an outline names. */\nconst OUTLINE_ELEMENT = /^[\\w.-]{1,64}$/\n/** A prop or sx name an outline lists. */\nconst OUTLINE_NAME = /^[A-Za-z_$][\\w$-]{0,39}$/\n/** The longest layout value an outline keeps as written. */\nconst OUTLINE_VALUE_MAX_CHARS = 40\n/**\n * The words a Grid's layout is written in, besides numbers: breakpoints, span\n * words, switch words, directions and wraps. Nothing else is kept, so no copy is.\n */\nconst OUTLINE_LAYOUT_WORDS = new Set([\n 'xs',\n 'sm',\n 'md',\n 'lg',\n 'xl',\n 'auto',\n 'grow',\n 'true',\n 'false',\n 'yes',\n 'no',\n 'on',\n 'off',\n 'row',\n 'row-reverse',\n 'column',\n 'column-reverse',\n 'wrap',\n 'nowrap',\n 'wrap-reverse',\n])\n/** A number a layout value is written in, with a CSS length unit where it has one. */\nconst OUTLINE_LAYOUT_NUMBER = /^[-+]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:px|rem|em|%)?$/i\n/** What stands between the words of a layout value, as in `xs:12 md:4` or `{ xs: 12, md: 4 }`. */\nconst OUTLINE_LAYOUT_SEPARATORS = /[\\s,:;=/{}()[\\]\"']+/\n/** A binding token, which a component's Grid may carry for a layout value. */\nconst OUTLINE_BINDING = /^\\{\\{\\s*[\\w.-]+\\s*\\}\\}$/\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Whether text is a layout value: a binding token, or only layout words and numbers. */\nfunction isLayoutText(value: string): boolean {\n if (value.length > OUTLINE_VALUE_MAX_CHARS) return false\n if (OUTLINE_BINDING.test(value.trim())) return true\n return value\n .split(OUTLINE_LAYOUT_SEPARATORS)\n .every((word) => word === '' || OUTLINE_LAYOUT_WORDS.has(word.toLowerCase()) || OUTLINE_LAYOUT_NUMBER.test(word))\n}\n\n/** An id or a path as a review keeps it: cut to its ceiling, and `?` for one it cannot show. */\nfunction reviewRef(ref: string): string {\n const cut = ref.slice(0, AI_JOB_REVIEW_REF_MAX_CHARS)\n return REVIEW_REF.test(cut) ? cut : '?'\n}\n\nfunction reviewRefs(refs: readonly string[]): string[] {\n return refs.slice(0, AI_JOB_REVIEW_REFS_MAX).map(reviewRef)\n}\n\n/** A written layout value as an outline keeps it; text that is no layout value is kept as a marker. */\nfunction outlineValue(value: unknown): string | number | boolean | null {\n if (value === null) return null\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string') return isLayoutText(value) ? value : '<text>'\n return Array.isArray(value) ? '<list>' : '<object>'\n}\n\nfunction childIdsOf(node: Record<string, unknown>): string[] {\n return Array.isArray(node['nodes']) ? node['nodes'].filter((child): child is string => typeof child === 'string') : []\n}\n\nfunction elementOf(node: unknown): string {\n const componentId = isRecord(node) ? node['componentId'] : undefined\n return typeof componentId === 'string' && OUTLINE_ELEMENT.test(componentId) ? componentId : '?'\n}\n\n/** One node of an outline: where it sits, what it is and the names of what it sets, never a copy value. */\nfunction outlineNodeOf(\n id: string,\n depth: number,\n node: Record<string, unknown>,\n nodes: Readonly<Record<string, unknown>>,\n): AiJobReviewOutlineNode {\n const props = isRecord(node['props']) ? node['props'] : {}\n const sx = isRecord(node['sx']) ? node['sx'] : isRecord(props['sx']) ? props['sx'] : {}\n const names = (keys: string[]) =>\n keys.filter((key) => OUTLINE_NAME.test(key)).slice(0, AI_JOB_REVIEW_OUTLINE_MAX_NAMES)\n const componentId = elementOf(node)\n const grid =\n componentId === 'muiGrid'\n ? Object.fromEntries(\n AI_JOB_REVIEW_GRID_PROPS.filter((name) => props[name] !== undefined).map((name) => [\n name,\n outlineValue(props[name]),\n ]),\n )\n : {}\n const sxNames = names(Object.keys(sx))\n return {\n id: reviewRef(id),\n depth,\n componentId,\n props: names(Object.keys(props).filter((key) => key !== 'sx')),\n ...(sxNames.length ? { sx: sxNames } : {}),\n ...(Object.keys(grid).length ? { grid } : {}),\n children: childIdsOf(node)\n .filter((child) => isRecord(nodes[child]))\n .slice(0, AI_JOB_REVIEW_OUTLINE_MAX_NAMES)\n .map((child) => elementOf(nodes[child])),\n }\n}\n\n/**\n * The parts of a refused answer its findings name, as a review keeps them\n * (AGL-3078): each node a finding names by id, with the nodes below it to\n * `AI_JOB_REVIEW_OUTLINE_MAX_DEPTH`, in document order and each once. A node\n * keeps its id, its element, the names of its props and sx keys and its\n * children's elements, and a Grid the values of its layout props as written;\n * no copy, and no address, is kept. The outline stops at\n * `AI_JOB_REVIEW_OUTLINE_MAX_NODES` nodes or `AI_JOB_REVIEW_OUTLINE_MAX_BYTES`\n * bytes, whichever comes first. An answer that is no node map, and findings\n * that name no node, outline nothing.\n */\nexport function aiDoctrineReviewOutline(\n answer: Record<string, unknown> | null | undefined,\n violations: readonly AiDoctrineViolation[],\n): AiJobReviewOutlineNode[] {\n const outline: AiJobReviewOutlineNode[] = []\n const tree = answer ? aiAnswerTree(answer) : null\n const nodes = isRecord(tree) && isRecord(tree['nodes']) ? tree['nodes'] : null\n if (!nodes) return outline\n const encoder = new TextEncoder()\n const seen = new Set<string>()\n let bytes = 2\n // False once the outline is full, which ends the walk.\n const add = (id: string, depth: number): boolean => {\n const node = nodes[id]\n if (seen.has(id) || !isRecord(node)) return true\n seen.add(id)\n const entry = outlineNodeOf(id, depth, node, nodes)\n const size = encoder.encode(JSON.stringify(entry)).length + 1\n if (outline.length === AI_JOB_REVIEW_OUTLINE_MAX_NODES || bytes + size > AI_JOB_REVIEW_OUTLINE_MAX_BYTES) {\n return false\n }\n outline.push(entry)\n bytes += size\n return depth === AI_JOB_REVIEW_OUTLINE_MAX_DEPTH || childIdsOf(node).every((child) => add(child, depth + 1))\n }\n const named = violations.flatMap((violation) => (violation.nodeIds ?? []).slice(0, AI_JOB_REVIEW_REFS_MAX))\n for (const id of new Set(named)) {\n if (!add(id, 0)) break\n }\n return outline\n}\n\n/**\n * The review a generation stops its job for when the re-ask still broke a\n * rule: the sentence a person reads, each finding with the nodes or plan\n * entries it names, and an outline of those parts of the answer it was found\n * in (AGL-3078), so why a job stopped can be read back from the job once the\n * answer itself is gone.\n */\nexport function aiDoctrineReview(result: {\n message: string\n violations: readonly AiDoctrineViolation[]\n /** The refused answer, whose nodes the findings name by id; outlined, never kept. */\n answer?: Record<string, unknown> | null\n}): AiJobReview {\n const outline = aiDoctrineReviewOutline(result.answer, result.violations)\n return {\n reason: 'doctrine',\n message: result.message,\n findings: result.violations.map(({ rule, code, message, nodeIds, paths }) => ({\n rule,\n code,\n message,\n ...(nodeIds?.length ? { nodeIds: reviewRefs(nodeIds) } : {}),\n ...(paths?.length ? { paths: reviewRefs(paths) } : {}),\n })),\n ...(outline.length ? { outline } : {}),\n }\n}\n\n/** The review a step stops its job for when the site cannot take the draft. */\nexport function aiLimitReview(message: string): AiJobReview {\n return { reason: 'limit', message, findings: [] }\n}\n\n/**\n * An outcome that reached no model: a draft an earlier run already wrote, a\n * copy the plan asked for, or a person asked before anything was spent.\n */\nexport function aiUnspentOutcome(\n model: string,\n rest: { outputs?: AiJobOutput[]; review?: AiJobReview } = {},\n): AiJobStepOutcome {\n return {\n outputs: rest.outputs ?? [],\n usage: AI_JOB_ZERO_USAGE,\n estCostUsd: 0,\n model,\n stopReason: null,\n ...(rest.review ? { review: rest.review } : {}),\n }\n}\n\n/** Node ids as the MODEL wrote them, from the minted ids a check reads. */\nexport function aiModelNodeIds(\n ids: readonly string[],\n sourceIds: Readonly<Record<string, string>>,\n): string[] {\n return ids.map((id) => sourceIds[id] ?? id)\n}\n\n/** The most facts a note names before it counts the rest. */\nconst AI_NOTE_MAX_FACTS = 8\n\n/** Facts as a sentence lists them: \"a, b and c\", the ones past the cap counted. */\nfunction factList(facts: readonly string[]): string {\n const shown = facts.slice(0, AI_NOTE_MAX_FACTS)\n const items = facts.length > shown.length ? [...shown, `${facts.length - shown.length} more`] : shown\n return items.length <= 1 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\n/**\n * What a draft asks the member to fill in before it is published (AGL-3056),\n * in the words the job's output note shows: the facts in square brackets its\n * copy holds, which the brief did not give (rule 14), each once. A page's\n * placed components show their own defaults wherever the page sets no value\n * of its own, so a component whose defaults hold such facts is named once,\n * however often the page places it. `copy` is what the draft shows beside its\n * tree, such as a component's defaults. `null` when there is nothing to fill.\n */\nexport function aiBracketedFactsNote(input: {\n tree: AiDoctrineTree\n inventory: AiSiteInventory | null\n copy?: readonly string[]\n}): string | null {\n const components = input.inventory?.components ?? []\n const componentProps = Object.fromEntries(components.map((component) => [component.id, component.props]))\n const facts = aiBracketedFacts([\n ...aiTreeCopy(input.tree, { componentProps }).map((sample) => sample.text),\n ...(input.copy ?? []),\n ])\n const listed = new Set(facts.map((fact) => fact.toLowerCase()))\n const byComponent = new Map<string, string[]>()\n for (const { node } of walkTree(input.tree)) {\n const component = components.find((row) => row.id === node.props?.[AI_INSTANCE_REF_PROP])\n if (node.componentId !== REUSABLE_INSTANCE_COMPONENT_ID || !component?.bracketedDefaults) continue\n const values = node.props?.[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n const set = (name: string): boolean => {\n const value = values && typeof values === 'object' ? (values as Record<string, unknown>)[name] : undefined\n return value !== undefined && value !== null && String(value).trim() !== ''\n }\n const shown = byComponent.get(component.name) ?? []\n for (const [name, defaults] of Object.entries(component.bracketedDefaults)) {\n if (set(name)) continue\n for (const fact of defaults) {\n if (!listed.has(fact.toLowerCase()) && !shown.some((known) => known.toLowerCase() === fact.toLowerCase())) {\n shown.push(fact)\n }\n }\n }\n if (shown.length) byComponent.set(component.name, shown)\n }\n const sentences = [\n ...(facts.length\n ? [`Before you publish, replace the facts in square brackets, which the brief did not give: ${factList(facts)}.`]\n : []),\n ...[...byComponent.entries()].map(\n ([name, shown]) =>\n `The \"${name}\" component on this page shows ${factList(shown)} until you replace ${shown.length === 1 ? 'it' : 'them'}.`,\n ),\n ]\n return sentences.length ? sentences.join(' ') : null\n}\n"],"names":["REUSABLE_INSTANCE_COMPONENT_ID","REUSABLE_INSTANCE_PROP_VALUES_KEY","AI_BUILD_PLAN_EMBED_HOST_NAMES","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","aiAnswerTree","aiBracketedFacts","aiTreeCopy","walkTree","AI_INSTANCE_REF_PROP","AI_JOB_BRIEF_MAX_CHARS","AI_JOB_ZERO_USAGE","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","aiConfirmedPlan","job","plan","status","aiPlanCreation","kind","create","find","entry","referenceOf","ref","label","labels","aiJobBriefLine","brief","slice","aiPlanReferenceLines","lines","reuse","push","id","purpose","from","duplicateOf","fields","length","join","name","why","screen","screens","sections","map","section","title","slug","embed","embeds","where","link","url","host","aiPlacedComponentIds","tree","placed","Set","nodes","node","rootId","props","componentId","add","aiPlanReuseViolations","inventory","noun","names","Map","components","component","reused","filter","missing","has","listed","get","rule","code","message","aiGenerationSpent","spend","outputs","usage","estCostUsd","model","stopReason","AI_JOB_REVIEW_REFS_MAX","AI_JOB_REVIEW_REF_MAX_CHARS","AI_JOB_REVIEW_OUTLINE_MAX_DEPTH","AI_JOB_REVIEW_OUTLINE_MAX_NODES","AI_JOB_REVIEW_OUTLINE_MAX_NAMES","AI_JOB_REVIEW_OUTLINE_MAX_BYTES","AI_JOB_REVIEW_GRID_PROPS","REVIEW_REF","OUTLINE_ELEMENT","OUTLINE_NAME","OUTLINE_VALUE_MAX_CHARS","OUTLINE_LAYOUT_WORDS","OUTLINE_LAYOUT_NUMBER","OUTLINE_LAYOUT_SEPARATORS","OUTLINE_BINDING","isRecord","value","Array","isArray","isLayoutText","test","trim","split","every","word","toLowerCase","reviewRef","cut","reviewRefs","refs","outlineValue","Number","isFinite","childIdsOf","child","elementOf","undefined","outlineNodeOf","depth","sx","keys","key","grid","Object","fromEntries","sxNames","children","aiDoctrineReviewOutline","answer","violations","outline","encoder","TextEncoder","seen","bytes","size","encode","JSON","stringify","named","flatMap","violation","nodeIds","aiDoctrineReview","result","reason","findings","paths","aiLimitReview","aiUnspentOutcome","rest","review","aiModelNodeIds","ids","sourceIds","AI_NOTE_MAX_FACTS","factList","facts","shown","items","aiBracketedFactsNote","input","componentProps","sample","text","copy","fact","byComponent","row","bracketedDefaults","values","set","String","defaults","entries","some","known","sentences"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,EAC9BC,iCAAiC,QAC5B,iDAAgD;AACvD,SACEC,8BAA8B,EAC9BC,sBAAsB,EACtBC,cAAc,QAGT,4BAAwB;AAS/B,SAASC,YAAY,QAAsD,4BAAwB;AACnG,SACEC,gBAAgB,EAChBC,UAAU,EACVC,QAAQ,QAIH,uCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,6BAAyB;AAE9D,SAASC,sBAAsB,QAA+B,wBAAoB;AAElF;;;;;;;;;CASC,GAED,OAAO,MAAMC,oBAAsC;IACjDC,aAAa;IACbC,cAAc;IACdC,iBAAiB;IACjBC,kBAAkB;AACpB,EAAC;AAED,oGAAoG,GACpG,OAAO,SAASC,gBAAgBC,GAAwB;QAC/CA;IAAP,OAAOA,EAAAA,YAAAA,IAAIC,IAAI,qBAARD,UAAUE,MAAM,MAAK,cAAcF,IAAIC,IAAI,GAAG;AACvD;AAEA,8EAA8E,GAC9E,OAAO,SAASE,eACdF,IAAsB,EACtBG,IAA2B;;IAE3B,eAAOH,wBAAAA,KAAMI,MAAM,CAACC,IAAI,CAAC,CAACC,QAAUA,MAAMH,IAAI,KAAKA,wBAAS;AAC9D;AAEA,uFAAuF,GACvF,SAASI,YAAYP,IAAe,EAAEQ,GAAW;QACjCR;IAAd,MAAMS,SAAQT,eAAAA,K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AAMtI,IAAI,CAAC8I;gBACb;YACF;QACF;QACA,IAAIR,MAAMhI,MAAM,EAAEyI,YAAYI,GAAG,CAAC5G,UAAU/B,IAAI,EAAE8H;IACpD;IACA,MAAMmB,YAAY;WACZpB,MAAM/H,MAAM,GACZ;YAAC,CAAC,wFAAwF,EAAE8H,SAASC,OAAO,CAAC,CAAC;SAAC,GAC/G,EAAE;WACH;eAAIU,YAAYO,OAAO;SAAG,CAACzI,GAAG,CAC/B,CAAC,CAACL,MAAM8H,MAAM,GACZ,CAAC,KAAK,EAAE9H,KAAK,+BAA+B,EAAE4H,SAASE,OAAO,mBAAmB,EAAEA,MAAMhI,MAAM,KAAK,IAAI,OAAO,OAAO,CAAC,CAAC;KAE7H;IACD,OAAOmJ,UAAUnJ,MAAM,GAAGmJ,UAAUlJ,IAAI,CAAC,OAAO;AAClD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-generation.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 {\n REUSABLE_INSTANCE_COMPONENT_ID,\n REUSABLE_INSTANCE_PROP_VALUES_KEY,\n} from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport {\n AI_BUILD_PLAN_EMBED_HOST_NAMES,\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildPlanCreate,\n type AiBuildPlanCreateKind,\n} from '../model/ai-build-plan'\nimport type {\n AiJob,\n AiJobOutput,\n AiJobPlan,\n AiJobReview,\n AiJobReviewOutlineNode,\n} from '../model/ai-jobs.types'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { isAiUnreadToken } from '../model/ai-template-subjects'\nimport { aiAnswerTree, type AiGenerationSpend, type AiValidatedTree } from '../runtime/ai-doctrine'\nimport {\n aiBracketedFacts,\n aiTreeCopy,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTree,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { AI_INSTANCE_REF_PROP } from '../runtime/ai-node-tree'\nimport type { AssistTokenUsage } from '../usage/assist-usage'\nimport { AI_JOB_BRIEF_MAX_CHARS, type AiJobStepOutcome } from './ai-job-text-step'\n\n/**\n * What the generation steps share (AGL-2909): reading the plan a member\n * confirmed, stating it to the model as references, and turning what a\n * generation spent or refused into the outcome the machine records.\n *\n * A generation step runs after its job's plan step, once a member confirmed\n * the plan, so the plan is part of what it executes: the records it reuses,\n * and the creation it builds. The plan travels as references — ids, names,\n * reasons — never as a document (AGL-2937).\n */\n\nexport const AI_JOB_ZERO_USAGE: AssistTokenUsage = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n}\n\n/** The job's plan once a member confirmed it; `null` before that, or for a job that never planned. */\nexport function aiConfirmedPlan(job: Pick<AiJob, 'plan'>): AiJobPlan | null {\n return job.plan?.status === 'confirmed' ? job.plan : null\n}\n\n/** The creation of one kind the plan names; the first when it names several. */\nexport function aiPlanCreation(\n plan: AiJobPlan | null,\n kind: AiBuildPlanCreateKind,\n): AiBuildPlanCreate | null {\n return plan?.create.find((entry) => entry.kind === kind) ?? null\n}\n\n/** A plan reference as the model reads it: the id with the name it was planned under. */\nfunction referenceOf(plan: AiJobPlan, ref: string): string {\n const label = plan.labels?.[ref]\n return label ? `${ref} (\"${label}\")` : ref\n}\n\n/** The user turn's opening: the brief, cut at the ceiling every job step keeps. */\nexport function aiJobBriefLine(job: Pick<AiJob, 'brief'>): string {\n return `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`\n}\n\n/** The confirmed plan as reference lines; none when there is no confirmed plan. */\nexport function aiPlanReferenceLines(plan: AiJobPlan | null): string[] {\n if (!plan) return []\n const lines = ['Confirmed plan:']\n for (const entry of plan.reuse) {\n lines.push(`- reuse the ${entry.kind === 'screen' ? 'page' : entry.kind} ${referenceOf(plan, entry.id)}: ${entry.purpose}`)\n }\n for (const entry of plan.create) {\n const from = entry.duplicateOf ? `, from a copy of ${referenceOf(plan, entry.duplicateOf)}` : ''\n // A template's slug or timestamp is filled, never shown, so a build told\n // it is a field prints it (AGL-3143 §16).\n const shown = entry.kind === 'template' ? entry.fields.filter((field) => !isAiUnreadToken(field)) : entry.fields\n const fields = shown.length ? ` Fields: ${shown.join(', ')}.` : ''\n lines.push(`- create the ${entry.kind} \"${entry.name}\"${from}: ${entry.why}${fields}`)\n }\n for (const screen of plan.screens) {\n const sections = screen.sections.map((section) => section.name).join(', ')\n lines.push(`- the page \"${screen.title}\" at ${screen.slug}${sections ? `: ${sections}` : ''}`)\n }\n // The one place a Video embed is admitted (AGL-3433): where the plan lists it, at the brief's link or none.\n for (const embed of plan.embeds ?? []) {\n const where = isAiPlanNewRef(embed.where)\n ? `the component \"${embed.where.slice(AI_PLAN_NEW_REF_PREFIX.length)}\"`\n : embed.where\n const link = embed.url ? `, url ${embed.url}` : ', url left empty for the site owner to paste'\n lines.push(`- embed a ${AI_BUILD_PLAN_EMBED_HOST_NAMES[embed.host]} player (videoEmbed) on ${where}${link}`)\n }\n return lines.length > 1 ? lines : []\n}\n\n/**\n * The most of a source's tree a build is shown, as JSON characters: about\n * 3,000 tokens, a whole layout or page template, never a site (AGL-3143 §14).\n */\nexport const AI_COPY_SOURCE_MAX_CHARS = 12_000\n\n/**\n * The record a plan's copy starts from, as the build that replaces the copy\n * is shown it (AGL-3143 §14): its tree in the node-map shape the tool takes,\n * with the one instruction that makes it a start rather than an example.\n * Empty when there is no tree to show or it is too large to show whole, and\n * the build then starts from the brief and the plan.\n *\n * A copy whose source cannot keep what the plan promised is never minted,\n * because the review after it would refuse it with certainty and the member\n * could only try the same copy again. Measured on 2026-09-22 (job\n * `Pq3pgvMH0D`): \"copy the interior layout and add a sidebar\" could only end\n * in review. Building from the source keeps what the plan does not change —\n * the firm's header, its footer, their copy — which a build from the brief\n * alone would draw again from nothing.\n */\nexport function aiCopySourceLines(noun: string, label: string, nodes: Readonly<Record<string, unknown>> | null): string[] {\n if (!nodes || !isRecordNode(nodes[CANVAS_ROOT_ELEMENT_ID])) return []\n const shaped: Record<string, Record<string, unknown>> = {}\n for (const [id, node] of Object.entries(nodes)) {\n if (!isRecordNode(node)) continue\n const { componentId, props, sx, nodes: children } = node\n shaped[id] = {\n componentId,\n ...(isRecordNode(props) && Object.keys(props).length ? { props } : {}),\n ...(isRecordNode(sx) && Object.keys(sx).length ? { sx } : {}),\n ...(Array.isArray(children) && children.length ? { nodes: children } : {}),\n }\n }\n const tree = JSON.stringify({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: shaped })\n if (tree.length > AI_COPY_SOURCE_MAX_CHARS) return []\n return [\n `The plan starts from a copy of the ${noun} \"${label}\", which lacks part of what the plan gives it. Build from it: keep every part the plan does not change, and add what the plan adds. Its tree, in the node-map shape the tool takes:`,\n tree,\n ]\n}\n\nfunction isRecordNode(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The reusable components a tree places, by the id each instance names. */\nexport function aiPlacedComponentIds(tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>): Set<string> {\n const placed = new Set<string>()\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n for (const { node } of walkTree({ rootId: tree.rootId, nodes })) {\n const ref = node.props?.[AI_INSTANCE_REF_PROP]\n if (node.componentId === REUSABLE_INSTANCE_COMPONENT_ID && typeof ref === 'string') {\n placed.add(ref)\n }\n }\n return placed\n}\n\n/**\n * Rule 7 on a generated tree: every component the confirmed plan reuses is\n * placed. `noun` names what the tree builds, in the finding.\n */\nexport function aiPlanReuseViolations(\n inventory: AiSiteInventory | null,\n plan: AiJobPlan | null,\n placed: ReadonlySet<string>,\n noun: string,\n): AiDoctrineViolation[] {\n const names = new Map((inventory?.components ?? []).map((component) => [component.id, component.name]))\n const reused = [\n ...new Set(\n (plan?.reuse ?? []).filter((entry) => entry.kind === 'component').map((entry) => entry.id),\n ),\n ]\n const missing = reused.filter((id) => !placed.has(id))\n if (!missing.length) return []\n const listed = missing.map((id) => `\"${names.get(id) ?? id}\"`).join(', ')\n return [\n {\n rule: 7,\n code: 'plan-reuse-not-placed',\n message: `The confirmed plan reuses ${listed}, and the ${noun} does not place ${\n missing.length === 1 ? 'it' : 'them'\n }. Place every component the plan reuses.`,\n },\n ]\n}\n\n/** What a generation spent, as the step's outcome carries it for the meter. */\nexport function aiGenerationSpent(\n spend: AiGenerationSpend,\n): Pick<AiJobStepOutcome, 'outputs' | 'usage' | 'estCostUsd' | 'model' | 'stopReason'> {\n return {\n outputs: [],\n usage: spend.usage,\n estCostUsd: spend.estCostUsd,\n model: spend.model,\n stopReason: spend.stopReason,\n }\n}\n\n/** The most node ids, or plan paths, one finding keeps on its review (AGL-3078). */\nexport const AI_JOB_REVIEW_REFS_MAX = 24\n/** The longest node id or plan path a review keeps, in characters. */\nexport const AI_JOB_REVIEW_REF_MAX_CHARS = 64\n/** How far below a node a finding names its outline goes: the node, its children and theirs. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_DEPTH = 2\n/** The most nodes a review outlines, across all its findings. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_NODES = 40\n/** The most names an outlined node lists of its props, of its sx keys, or of its children. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_NAMES = 16\n/** The most bytes a review's outline takes as JSON, whatever the counts above allow. */\nexport const AI_JOB_REVIEW_OUTLINE_MAX_BYTES = 4_096\n\n/** A Grid's layout props, whose written values an outline keeps. */\nconst AI_JOB_REVIEW_GRID_PROPS = [\n 'container',\n 'size',\n 'offset',\n 'direction',\n 'wrap',\n 'spacing',\n 'rowSpacing',\n 'columnSpacing',\n 'columns',\n] as const\n\n/** A node id or plan path a review keeps: no whitespace, slash or quote, so never copy or an address. */\nconst REVIEW_REF = /^[^\\s/\\\\\"'<>]+$/\n/** An element id an outline names. */\nconst OUTLINE_ELEMENT = /^[\\w.-]{1,64}$/\n/** A prop or sx name an outline lists. */\nconst OUTLINE_NAME = /^[A-Za-z_$][\\w$-]{0,39}$/\n/** The longest layout value an outline keeps as written. */\nconst OUTLINE_VALUE_MAX_CHARS = 40\n/**\n * The words a Grid's layout is written in, besides numbers: breakpoints, span\n * words, switch words, directions and wraps. Nothing else is kept, so no copy is.\n */\nconst OUTLINE_LAYOUT_WORDS = new Set([\n 'xs',\n 'sm',\n 'md',\n 'lg',\n 'xl',\n 'auto',\n 'grow',\n 'true',\n 'false',\n 'yes',\n 'no',\n 'on',\n 'off',\n 'row',\n 'row-reverse',\n 'column',\n 'column-reverse',\n 'wrap',\n 'nowrap',\n 'wrap-reverse',\n])\n/** A number a layout value is written in, with a CSS length unit where it has one. */\nconst OUTLINE_LAYOUT_NUMBER = /^[-+]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:px|rem|em|%)?$/i\n/** What stands between the words of a layout value, as in `xs:12 md:4` or `{ xs: 12, md: 4 }`. */\nconst OUTLINE_LAYOUT_SEPARATORS = /[\\s,:;=/{}()[\\]\"']+/\n/** A binding token, which a component's Grid may carry for a layout value. */\nconst OUTLINE_BINDING = /^\\{\\{\\s*[\\w.-]+\\s*\\}\\}$/\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Whether text is a layout value: a binding token, or only layout words and numbers. */\nfunction isLayoutText(value: string): boolean {\n if (value.length > OUTLINE_VALUE_MAX_CHARS) return false\n if (OUTLINE_BINDING.test(value.trim())) return true\n return value\n .split(OUTLINE_LAYOUT_SEPARATORS)\n .every((word) => word === '' || OUTLINE_LAYOUT_WORDS.has(word.toLowerCase()) || OUTLINE_LAYOUT_NUMBER.test(word))\n}\n\n/** An id or a path as a review keeps it: cut to its ceiling, and `?` for one it cannot show. */\nfunction reviewRef(ref: string): string {\n const cut = ref.slice(0, AI_JOB_REVIEW_REF_MAX_CHARS)\n return REVIEW_REF.test(cut) ? cut : '?'\n}\n\nfunction reviewRefs(refs: readonly string[]): string[] {\n return refs.slice(0, AI_JOB_REVIEW_REFS_MAX).map(reviewRef)\n}\n\n/** A written layout value as an outline keeps it; text that is no layout value is kept as a marker. */\nfunction outlineValue(value: unknown): string | number | boolean | null {\n if (value === null) return null\n if (typeof value === 'boolean') return value\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string') return isLayoutText(value) ? value : '<text>'\n return Array.isArray(value) ? '<list>' : '<object>'\n}\n\nfunction childIdsOf(node: Record<string, unknown>): string[] {\n return Array.isArray(node['nodes']) ? node['nodes'].filter((child): child is string => typeof child === 'string') : []\n}\n\nfunction elementOf(node: unknown): string {\n const componentId = isRecord(node) ? node['componentId'] : undefined\n return typeof componentId === 'string' && OUTLINE_ELEMENT.test(componentId) ? componentId : '?'\n}\n\n/** One node of an outline: where it sits, what it is and the names of what it sets, never a copy value. */\nfunction outlineNodeOf(\n id: string,\n depth: number,\n node: Record<string, unknown>,\n nodes: Readonly<Record<string, unknown>>,\n): AiJobReviewOutlineNode {\n const props = isRecord(node['props']) ? node['props'] : {}\n const sx = isRecord(node['sx']) ? node['sx'] : isRecord(props['sx']) ? props['sx'] : {}\n const names = (keys: string[]) =>\n keys.filter((key) => OUTLINE_NAME.test(key)).slice(0, AI_JOB_REVIEW_OUTLINE_MAX_NAMES)\n const componentId = elementOf(node)\n const grid =\n componentId === 'muiGrid'\n ? Object.fromEntries(\n AI_JOB_REVIEW_GRID_PROPS.filter((name) => props[name] !== undefined).map((name) => [\n name,\n outlineValue(props[name]),\n ]),\n )\n : {}\n const sxNames = names(Object.keys(sx))\n return {\n id: reviewRef(id),\n depth,\n componentId,\n props: names(Object.keys(props).filter((key) => key !== 'sx')),\n ...(sxNames.length ? { sx: sxNames } : {}),\n ...(Object.keys(grid).length ? { grid } : {}),\n children: childIdsOf(node)\n .filter((child) => isRecord(nodes[child]))\n .slice(0, AI_JOB_REVIEW_OUTLINE_MAX_NAMES)\n .map((child) => elementOf(nodes[child])),\n }\n}\n\n/**\n * The parts of a refused answer its findings name, as a review keeps them\n * (AGL-3078): each node a finding names by id, with the nodes below it to\n * `AI_JOB_REVIEW_OUTLINE_MAX_DEPTH`, in document order and each once. A node\n * keeps its id, its element, the names of its props and sx keys and its\n * children's elements, and a Grid the values of its layout props as written;\n * no copy, and no address, is kept. The outline stops at\n * `AI_JOB_REVIEW_OUTLINE_MAX_NODES` nodes or `AI_JOB_REVIEW_OUTLINE_MAX_BYTES`\n * bytes, whichever comes first. An answer that is no node map, and findings\n * that name no node, outline nothing.\n */\nexport function aiDoctrineReviewOutline(\n answer: Record<string, unknown> | null | undefined,\n violations: readonly AiDoctrineViolation[],\n): AiJobReviewOutlineNode[] {\n const outline: AiJobReviewOutlineNode[] = []\n const tree = answer ? aiAnswerTree(answer) : null\n const nodes = isRecord(tree) && isRecord(tree['nodes']) ? tree['nodes'] : null\n if (!nodes) return outline\n const encoder = new TextEncoder()\n const seen = new Set<string>()\n let bytes = 2\n // False once the outline is full, which ends the walk.\n const add = (id: string, depth: number): boolean => {\n const node = nodes[id]\n if (seen.has(id) || !isRecord(node)) return true\n seen.add(id)\n const entry = outlineNodeOf(id, depth, node, nodes)\n const size = encoder.encode(JSON.stringify(entry)).length + 1\n if (outline.length === AI_JOB_REVIEW_OUTLINE_MAX_NODES || bytes + size > AI_JOB_REVIEW_OUTLINE_MAX_BYTES) {\n return false\n }\n outline.push(entry)\n bytes += size\n return depth === AI_JOB_REVIEW_OUTLINE_MAX_DEPTH || childIdsOf(node).every((child) => add(child, depth + 1))\n }\n const named = violations.flatMap((violation) => (violation.nodeIds ?? []).slice(0, AI_JOB_REVIEW_REFS_MAX))\n for (const id of new Set(named)) {\n if (!add(id, 0)) break\n }\n return outline\n}\n\n/**\n * The review a generation stops its job for when the re-ask still broke a\n * rule: the sentence a person reads, each finding with the nodes or plan\n * entries it names, and an outline of those parts of the answer it was found\n * in (AGL-3078), so why a job stopped can be read back from the job once the\n * answer itself is gone.\n */\nexport function aiDoctrineReview(result: {\n message: string\n violations: readonly AiDoctrineViolation[]\n /** The refused answer, whose nodes the findings name by id; outlined, never kept. */\n answer?: Record<string, unknown> | null\n}): AiJobReview {\n const outline = aiDoctrineReviewOutline(result.answer, result.violations)\n return {\n reason: 'doctrine',\n message: result.message,\n findings: result.violations.map(({ rule, code, message, nodeIds, paths }) => ({\n rule,\n code,\n message,\n ...(nodeIds?.length ? { nodeIds: reviewRefs(nodeIds) } : {}),\n ...(paths?.length ? { paths: reviewRefs(paths) } : {}),\n })),\n ...(outline.length ? { outline } : {}),\n }\n}\n\n/** The review a step stops its job for when the site cannot take the draft. */\nexport function aiLimitReview(message: string): AiJobReview {\n return { reason: 'limit', message, findings: [] }\n}\n\n/**\n * An outcome that reached no model: a draft an earlier run already wrote, a\n * copy the plan asked for, or a person asked before anything was spent.\n */\nexport function aiUnspentOutcome(\n model: string,\n rest: { outputs?: AiJobOutput[]; review?: AiJobReview } = {},\n): AiJobStepOutcome {\n return {\n outputs: rest.outputs ?? [],\n usage: AI_JOB_ZERO_USAGE,\n estCostUsd: 0,\n model,\n stopReason: null,\n ...(rest.review ? { review: rest.review } : {}),\n }\n}\n\n/** Node ids as the MODEL wrote them, from the minted ids a check reads. */\nexport function aiModelNodeIds(\n ids: readonly string[],\n sourceIds: Readonly<Record<string, string>>,\n): string[] {\n return ids.map((id) => sourceIds[id] ?? id)\n}\n\n/** The most facts a note names before it counts the rest. */\nconst AI_NOTE_MAX_FACTS = 8\n\n/** Facts as a sentence lists them: \"a, b and c\", the ones past the cap counted. */\nfunction factList(facts: readonly string[]): string {\n const shown = facts.slice(0, AI_NOTE_MAX_FACTS)\n const items = facts.length > shown.length ? [...shown, `${facts.length - shown.length} more`] : shown\n return items.length <= 1 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\n/**\n * What a draft asks the member to fill in before it is published (AGL-3056),\n * in the words the job's output note shows: the facts in square brackets its\n * copy holds, which the brief did not give (rule 14), each once. A page's\n * placed components show their own defaults wherever the page sets no value\n * of its own, so a component whose defaults hold such facts is named once,\n * however often the page places it. `copy` is what the draft shows beside its\n * tree, such as a component's defaults. `null` when there is nothing to fill.\n */\nexport function aiBracketedFactsNote(input: {\n tree: AiDoctrineTree\n inventory: AiSiteInventory | null\n copy?: readonly string[]\n}): string | null {\n const components = input.inventory?.components ?? []\n const componentProps = Object.fromEntries(components.map((component) => [component.id, component.props]))\n const facts = aiBracketedFacts([\n ...aiTreeCopy(input.tree, { componentProps }).map((sample) => sample.text),\n ...(input.copy ?? []),\n ])\n const listed = new Set(facts.map((fact) => fact.toLowerCase()))\n const byComponent = new Map<string, string[]>()\n for (const { node } of walkTree(input.tree)) {\n const component = components.find((row) => row.id === node.props?.[AI_INSTANCE_REF_PROP])\n if (node.componentId !== REUSABLE_INSTANCE_COMPONENT_ID || !component?.bracketedDefaults) continue\n const values = node.props?.[REUSABLE_INSTANCE_PROP_VALUES_KEY]\n const set = (name: string): boolean => {\n const value = values && typeof values === 'object' ? (values as Record<string, unknown>)[name] : undefined\n return value !== undefined && value !== null && String(value).trim() !== ''\n }\n const shown = byComponent.get(component.name) ?? []\n for (const [name, defaults] of Object.entries(component.bracketedDefaults)) {\n if (set(name)) continue\n for (const fact of defaults) {\n if (!listed.has(fact.toLowerCase()) && !shown.some((known) => known.toLowerCase() === fact.toLowerCase())) {\n shown.push(fact)\n }\n }\n }\n if (shown.length) byComponent.set(component.name, shown)\n }\n const sentences = [\n ...(facts.length\n ? [`Before you publish, replace the facts in square brackets, which the brief did not give: ${factList(facts)}.`]\n : []),\n ...[...byComponent.entries()].map(\n ([name, shown]) =>\n `The \"${name}\" component on this page shows ${factList(shown)} until you replace ${shown.length === 1 ? 'it' : 'them'}.`,\n ),\n ]\n return sentences.length ? sentences.join(' ') : null\n}\n"],"names":["REUSABLE_INSTANCE_COMPONENT_ID","REUSABLE_INSTANCE_PROP_VALUES_KEY","CANVAS_ROOT_ELEMENT_ID","AI_BUILD_PLAN_EMBED_HOST_NAMES","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","isAiUnreadToken","aiAnswerTree","aiBracketedFacts","aiTreeCopy","walkTree","AI_INSTANCE_REF_PROP","AI_JOB_BRIEF_MAX_CHARS","AI_JOB_ZERO_USAGE","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","aiConfirmedPlan","job","plan","status","aiPlanCreation","kind","create","find","entry","referenceOf","ref","label","labels","aiJobBriefLine","brief","slice","aiPlanReferenceLines","lines","reuse","push","id","purpose","from","duplicateOf","shown","fields","filter","field","length","join","name","why","screen","screens","sections","map","section","title","slug","embed","embeds","where","link","url","host","AI_COPY_SOURCE_MAX_CHARS","aiCopySourceLines","noun","nodes","isRecordNode","shaped","node","Object","entries","componentId","props","sx","children","keys","Array","isArray","tree","JSON","stringify","rootId","value","aiPlacedComponentIds","placed","Set","add","aiPlanReuseViolations","inventory","names","Map","components","component","reused","missing","has","listed","get","rule","code","message","aiGenerationSpent","spend","outputs","usage","estCostUsd","model","stopReason","AI_JOB_REVIEW_REFS_MAX","AI_JOB_REVIEW_REF_MAX_CHARS","AI_JOB_REVIEW_OUTLINE_MAX_DEPTH","AI_JOB_REVIEW_OUTLINE_MAX_NODES","AI_JOB_REVIEW_OUTLINE_MAX_NAMES","AI_JOB_REVIEW_OUTLINE_MAX_BYTES","AI_JOB_REVIEW_GRID_PROPS","REVIEW_REF","OUTLINE_ELEMENT","OUTLINE_NAME","OUTLINE_VALUE_MAX_CHARS","OUTLINE_LAYOUT_WORDS","OUTLINE_LAYOUT_NUMBER","OUTLINE_LAYOUT_SEPARATORS","OUTLINE_BINDING","isRecord","isLayoutText","test","trim","split","every","word","toLowerCase","reviewRef","cut","reviewRefs","refs","outlineValue","Number","isFinite","childIdsOf","child","elementOf","undefined","outlineNodeOf","depth","key","grid","fromEntries","sxNames","aiDoctrineReviewOutline","answer","violations","outline","encoder","TextEncoder","seen","bytes","size","encode","named","flatMap","violation","nodeIds","aiDoctrineReview","result","reason","findings","paths","aiLimitReview","aiUnspentOutcome","rest","review","aiModelNodeIds","ids","sourceIds","AI_NOTE_MAX_FACTS","factList","facts","items","aiBracketedFactsNote","input","componentProps","sample","text","copy","fact","byComponent","row","bracketedDefaults","values","set","String","defaults","some","known","sentences"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,EAC9BC,iCAAiC,QAC5B,iDAAgD;AACvD,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,8BAA8B,EAC9BC,sBAAsB,EACtBC,cAAc,QAGT,4BAAwB;AAS/B,SAASC,eAAe,QAAQ,mCAA+B;AAC/D,SAASC,YAAY,QAAsD,4BAAwB;AACnG,SACEC,gBAAgB,EAChBC,UAAU,EACVC,QAAQ,QAIH,uCAAmC;AAC1C,SAASC,oBAAoB,QAAQ,6BAAyB;AAE9D,SAASC,sBAAsB,QAA+B,wBAAoB;AAElF;;;;;;;;;CASC,GAED,OAAO,MAAMC,oBAAsC;IACjDC,aAAa;IACbC,cAAc;IACdC,iBAAiB;IACjBC,kBAAkB;AACpB,EAAC;AAED,oGAAoG,GACpG,OAAO,SAASC,gBAAgBC,GAAwB;QAC/CA;IAAP,OAAOA,EAAAA,YAAAA,IAAIC,IAAI,qBAARD,UAAUE,MAAM,MAAK,cAAcF,IAAIC,IAAI,GAAG;AACvD;AAEA,8EAA8E,GAC9E,OAAO,SAASE,eACdF,IAAsB,EACtBG,IAA2B;;IAE3B,eAAOH,wBAAAA,KAAMI,MAAM,CAACC,IAAI,CAAC,CAACC,QAAUA,MAAMH,IAAI,K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,GAAG,CAACyF,KAAKtD,WAAW,OAAO,CAACzF,MAAMuJ,IAAI,CAAC,CAACC,QAAUA,MAAM/D,WAAW,OAAOsD,KAAKtD,WAAW,KAAK;oBACzGzF,MAAML,IAAI,CAACoJ;gBACb;YACF;QACF;QACA,IAAI/I,MAAMI,MAAM,EAAE4I,YAAYI,GAAG,CAACjG,UAAU7C,IAAI,EAAEN;IACpD;IACA,MAAMyJ,YAAY;WACZlB,MAAMnI,MAAM,GACZ;YAAC,CAAC,wFAAwF,EAAEkI,SAASC,OAAO,CAAC,CAAC;SAAC,GAC/G,EAAE;WACH;eAAIS,YAAYnH,OAAO;SAAG,CAAClB,GAAG,CAC/B,CAAC,CAACL,MAAMN,MAAM,GACZ,CAAC,KAAK,EAAEM,KAAK,+BAA+B,EAAEgI,SAAStI,OAAO,mBAAmB,EAAEA,MAAMI,MAAM,KAAK,IAAI,OAAO,OAAO,CAAC,CAAC;KAE7H;IACD,OAAOqJ,UAAUrJ,MAAM,GAAGqJ,UAAUpJ,IAAI,CAAC,OAAO;AAClD"}
@@ -20,7 +20,7 @@ import { AI_ACCEPTABLE_USE_BLOCK, runAiRequest } from "../runtime/ai-runtime.js"
20
20
  import { AI_GENERATION_MAX_ATTEMPTS } from "../runtime/ai-generation-bounds.js";
21
21
  import { checkAiInsightAnswer } from "../runtime/ai-insight-check.js";
22
22
  import { AI_INSIGHT_ANSWER_TOOL_NAME, AI_INSIGHT_READ_TOOL_NAME, aiInsightAnswerTool, aiInsightReadTool, parseAiInsightAnswer, parseAiInsightReads } from "../tools/ai-insight-tool.js";
23
- import { aiDatasetCatalog } from "../insights/ai-figure-readers.js";
23
+ import { aiDatasetCatalog } from "../insights/ai-dataset-catalog.js";
24
24
  import { aiInsightDatasetCatalog, aiInsightReaderCatalog, aiInsightReaderDays, aiInsightReaders, aiInsightTableText, readAiInsightTables } from "../insights/ai-insight-readers.js";
25
25
  import { assistExchangeExpiry } from "../usage/assist-usage.js";
26
26
  import { registerAiJobAdmission } from "./ai-job-admission.js";