@case-framework/survey-assistant 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -3
- package/dist/{attachments-B0hg3vpT.mjs → attachments-BuNni5vB.mjs} +1 -1
- package/dist/{attachments-B0hg3vpT.mjs.map → attachments-BuNni5vB.mjs.map} +1 -1
- package/dist/{authoring-references-BJQ_1nMX.mjs → authoring-references-CmwLc_C8.mjs} +49 -32
- package/dist/authoring-references-CmwLc_C8.mjs.map +1 -0
- package/dist/capabilities-D55dq-fO.mjs +582 -0
- package/dist/capabilities-D55dq-fO.mjs.map +1 -0
- package/dist/capabilities-default.d.mts +5 -12
- package/dist/capabilities-default.d.mts.map +1 -1
- package/dist/capabilities-default.mjs +2 -411
- package/dist/capabilities-z95e1mti.d.mts +117 -0
- package/dist/capabilities-z95e1mti.d.mts.map +1 -0
- package/dist/{constants-0UHGFcRJ.mjs → constants-Ct-vv9cu.mjs} +1 -1
- package/dist/{constants-0UHGFcRJ.mjs.map → constants-Ct-vv9cu.mjs.map} +1 -1
- package/dist/{constants-Be91Gay9.d.mts → constants-HL_klgJl.d.mts} +7 -28
- package/dist/constants-HL_klgJl.d.mts.map +1 -0
- package/dist/{controller-proxy-BH05e-C2.mjs → controller-proxy-BQ1YsVxJ.mjs} +12 -21
- package/dist/controller-proxy-BQ1YsVxJ.mjs.map +1 -0
- package/dist/controller-proxy-Cmzdr9tV.d.mts +65 -0
- package/dist/controller-proxy-Cmzdr9tV.d.mts.map +1 -0
- package/dist/default-D22AKTqE.mjs +233 -0
- package/dist/default-D22AKTqE.mjs.map +1 -0
- package/dist/{digest-SJmoYVaK.d.mts → digest-FnTTDBq2.d.mts} +2 -3
- package/dist/digest-FnTTDBq2.d.mts.map +1 -0
- package/dist/digest.d.mts +1 -1
- package/dist/digest.mjs.map +1 -1
- package/dist/engine-D950TfvC.mjs +3098 -0
- package/dist/engine-D950TfvC.mjs.map +1 -0
- package/dist/engine.d.mts +4 -3
- package/dist/engine.mjs +3 -3
- package/dist/{fair-guidance-CRYCRxQm.mjs → fair-guidance-BmO4PswW.mjs} +1 -1
- package/dist/{fair-guidance-CRYCRxQm.mjs.map → fair-guidance-BmO4PswW.mjs.map} +1 -1
- package/dist/{index-l_EK4yK7.d.mts → index-B8TLBd1G.d.mts} +18 -72
- package/dist/index-B8TLBd1G.d.mts.map +1 -0
- package/dist/index-CaX3hZmr.d.mts +23813 -0
- package/dist/index-CaX3hZmr.d.mts.map +1 -0
- package/dist/{index-x0qprHgK.d.mts → index-CeUlGkoU.d.mts} +58 -28
- package/dist/index-CeUlGkoU.d.mts.map +1 -0
- package/dist/{index-nhrgbgO5.d.mts → index-DYHdvSE8.d.mts} +347 -88
- package/dist/index-DYHdvSE8.d.mts.map +1 -0
- package/dist/lifecycle-DFzxVxpq.d.mts +54346 -0
- package/dist/lifecycle-DFzxVxpq.d.mts.map +1 -0
- package/dist/{memory-thread-repository-KWHQWFEW.mjs → memory-thread-repository-DmLadygY.mjs} +60 -30
- package/dist/memory-thread-repository-DmLadygY.mjs.map +1 -0
- package/dist/protocol-BQ7uIDYT.mjs +569 -0
- package/dist/protocol-BQ7uIDYT.mjs.map +1 -0
- package/dist/protocol.d.mts +4 -4
- package/dist/protocol.mjs +4 -3
- package/dist/{react-B3ybjJ-X.mjs → react-DybJ5pWw.mjs} +159 -46
- package/dist/react-DybJ5pWw.mjs.map +1 -0
- package/dist/react-integration.d.mts +2 -2
- package/dist/react-integration.mjs +2 -2
- package/dist/react.d.mts +3 -3
- package/dist/react.mjs +3 -3
- package/dist/references/assistant-operations.md +224 -180
- package/dist/references/core-rules.md +6 -3
- package/dist/references/element-types.md +189 -0
- package/dist/references/expressions.md +307 -168
- package/dist/references/fair-by-design.md +9 -9
- package/dist/references/follow-ups.md +151 -0
- package/dist/references/localization.md +26 -12
- package/dist/references/response-variables.md +38 -0
- package/dist/references/rich-text-content.md +22 -43
- package/dist/references/source-material-surveys.md +20 -24
- package/dist/references/survey-data-model.md +36 -102
- package/dist/{request-context-CG4SWijt.mjs → request-context-KVh8VjgH.mjs} +4 -10
- package/dist/request-context-KVh8VjgH.mjs.map +1 -0
- package/dist/{request-guardrails-TmgQtqp4.mjs → request-guardrails-C0ugBOp0.mjs} +6 -5
- package/dist/request-guardrails-C0ugBOp0.mjs.map +1 -0
- package/dist/server-agent.d.mts +62 -43
- package/dist/server-agent.d.mts.map +1 -1
- package/dist/server-agent.mjs +73 -40
- package/dist/server-agent.mjs.map +1 -1
- package/dist/server-runtime.d.mts +24 -42
- package/dist/server-runtime.d.mts.map +1 -1
- package/dist/server-runtime.mjs +12 -12
- package/dist/server-runtime.mjs.map +1 -1
- package/dist/server-tasks.d.mts +2 -2
- package/dist/server-tasks.mjs +2 -313
- package/dist/server-tools.d.mts +1 -1
- package/dist/server-tools.mjs +1 -1
- package/dist/server.d.mts +14 -36
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +5 -5
- package/dist/server.mjs.map +1 -1
- package/dist/storage-postgres.d.mts +9 -25
- package/dist/storage-postgres.d.mts.map +1 -1
- package/dist/storage-postgres.mjs +5 -4
- package/dist/storage-postgres.mjs.map +1 -1
- package/dist/tasks-Coh5N027.mjs +397 -0
- package/dist/tasks-Coh5N027.mjs.map +1 -0
- package/dist/{tasks-CYqrcaRO.d.mts → tasks-wb9M-bak.d.mts} +25 -41
- package/dist/tasks-wb9M-bak.d.mts.map +1 -0
- package/dist/thread-documents-DrHbaXqP.d.mts +119 -0
- package/dist/thread-documents-DrHbaXqP.d.mts.map +1 -0
- package/dist/{thread-handlers-DBAaU7BA.d.mts → thread-handlers-C3Iya92v.d.mts} +9 -40
- package/dist/thread-handlers-C3Iya92v.d.mts.map +1 -0
- package/dist/{tools-BvSovehT.mjs → tools-D0KBDolR.mjs} +677 -459
- package/dist/tools-D0KBDolR.mjs.map +1 -0
- package/dist/turn-survey-draft-B34lggSG.d.mts +185 -0
- package/dist/turn-survey-draft-B34lggSG.d.mts.map +1 -0
- package/dist/ui.css +1 -1
- package/dist/ui.d.mts +15 -54
- package/dist/ui.d.mts.map +1 -1
- package/dist/ui.mjs +203 -156
- package/dist/ui.mjs.map +1 -1
- package/docs/integration.md +11 -1
- package/package.json +41 -36
- package/dist/authoring-references-BJQ_1nMX.mjs.map +0 -1
- package/dist/capabilities-1KNnNO1_.mjs +0 -73
- package/dist/capabilities-1KNnNO1_.mjs.map +0 -1
- package/dist/capabilities-DVTfogjv.d.mts +0 -193
- package/dist/capabilities-DVTfogjv.d.mts.map +0 -1
- package/dist/capabilities-default.mjs.map +0 -1
- package/dist/constants-Be91Gay9.d.mts.map +0 -1
- package/dist/controller-proxy-BH05e-C2.mjs.map +0 -1
- package/dist/controller-proxy-Bd0ZHBPF.d.mts +0 -85
- package/dist/controller-proxy-Bd0ZHBPF.d.mts.map +0 -1
- package/dist/digest-SJmoYVaK.d.mts.map +0 -1
- package/dist/engine-Bo85Oyj0.mjs +0 -6723
- package/dist/engine-Bo85Oyj0.mjs.map +0 -1
- package/dist/index-Tnqv-yKW.d.mts +0 -777
- package/dist/index-Tnqv-yKW.d.mts.map +0 -1
- package/dist/index-l_EK4yK7.d.mts.map +0 -1
- package/dist/index-nhrgbgO5.d.mts.map +0 -1
- package/dist/index-x0qprHgK.d.mts.map +0 -1
- package/dist/lifecycle-Bx0aq_4S.d.mts +0 -529
- package/dist/lifecycle-Bx0aq_4S.d.mts.map +0 -1
- package/dist/memory-thread-repository-KWHQWFEW.mjs.map +0 -1
- package/dist/protocol-BhzQbx81.mjs +0 -1173
- package/dist/protocol-BhzQbx81.mjs.map +0 -1
- package/dist/react-B3ybjJ-X.mjs.map +0 -1
- package/dist/references/embedded-forms.md +0 -126
- package/dist/references/item-types.md +0 -407
- package/dist/request-context-CG4SWijt.mjs.map +0 -1
- package/dist/request-guardrails-TmgQtqp4.mjs.map +0 -1
- package/dist/server-tasks.mjs.map +0 -1
- package/dist/tasks-CYqrcaRO.d.mts.map +0 -1
- package/dist/thread-documents-rmd6nyX9.d.mts +0 -107
- package/dist/thread-documents-rmd6nyX9.d.mts.map +0 -1
- package/dist/thread-handlers-DBAaU7BA.d.mts.map +0 -1
- package/dist/tools-BvSovehT.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine-D950TfvC.mjs","names":["pointer","isRecord","exhaustive","isRecord","exhaustive"],"sources":["../src/engine/survey-model.ts","../src/engine/context.ts","../src/engine/expression-validation.ts","../src/engine/definition-diagnostics.ts","../src/engine/expression-reference-integrity.ts","../src/engine/expression-mutations.ts","../src/engine/inspection.ts","../src/engine/normalization.ts","../src/engine/reference-diagnostics.ts","../src/engine/operation-execution.ts","../src/engine/authoring-content.ts","../src/engine/operations.ts","../src/engine/operation-state.ts","../src/engine/audit.ts","../src/engine/mutation-recovery.ts","../src/engine/turn-survey-draft.ts","../src/engine/task-context.ts","../src/engine/task-result-cache.ts"],"sourcesContent":["import {\n Survey,\n SurveyStateGraph,\n DefinitionError,\n getDefaultProjectionIssues,\n type CompositionSurvey,\n type ElementRegistry,\n} from \"@case-framework/survey-core\";\nimport { defaultElementRegistry } from \"@case-framework/survey-items\";\nimport type { SurveyAssistantCapabilitySet } from \"./capabilities\";\n\n/** One trusted headless definition registry, shared with the editor/player/exporter.\n * Unknown types reject; serialized capabilities never install slot or runtime behavior.\n */\nexport function createAssistantSurvey(\n raw: CompositionSurvey,\n capabilities?: Pick<SurveyAssistantCapabilitySet, \"registry\">,\n): Survey {\n const registry: ElementRegistry = capabilities?.registry ?? defaultElementRegistry;\n // Authors may leave broken references to repair later. The assistant can inspect and edit such\n // drafts; proposals are rejected when they introduce new ones (see getIntroducedDefinitionIssues).\n return Survey.parse(raw, registry, { admission: \"draft\" });\n}\nexport function getAssistantVisibilityIssues(survey: Survey) {\n try {\n new SurveyStateGraph(survey, { admission: \"draft\" });\n return [];\n } catch (error) {\n return error instanceof DefinitionError\n ? [...error.diagnostics]\n : [\n {\n severity: \"error\" as const,\n code: \"invalid-expression-graph\",\n path: [],\n message: error instanceof Error ? error.message : String(error),\n },\n ];\n }\n}\nexport function getAssistantResponseSchemaIssues(\n raw: CompositionSurvey,\n capabilities?: Pick<SurveyAssistantCapabilitySet, \"registry\">,\n) {\n try {\n const survey = createAssistantSurvey(raw, capabilities);\n return [\n ...getAssistantVisibilityIssues(survey),\n ...getDefaultProjectionIssues(survey).map((message) => ({\n severity: \"error\" as const,\n code: \"invalid-response-export\",\n message,\n })),\n ];\n } catch (error) {\n return error instanceof DefinitionError\n ? [...error.diagnostics]\n : [\n {\n severity: \"error\" as const,\n code: \"invalid-response-schema\",\n message: error instanceof Error ? error.message : String(error),\n },\n ];\n }\n}\n","import { createAssistantSurvey } from \"./survey-model\";\nimport {\n ValueType,\n getContentPlainText,\n ownValue,\n type CompositionSurvey,\n type Survey,\n type ContentOwner,\n type FlowItem,\n type ReadonlyResponseSlotDefinition,\n} from \"@case-framework/survey-core\";\nimport type {\n SurveyAssistantCapabilityManifest,\n SurveyDocumentSnapshot,\n SurveyDocumentVersion,\n} from \"../protocol\";\nimport {\n assertSurveyAssistantCapabilities,\n type SurveyAssistantCapabilitySet,\n} from \"./capabilities\";\n\nexport type SurveyAssistantResponseSlotTypes = Record<string, ValueType | undefined>;\n\nexport interface SurveyAssistantInspectionOutlineNode {\n itemId: string;\n parentId?: string;\n depth: number;\n itemType: string;\n editorName: string;\n breadcrumb: string;\n itemLabel?: string;\n childCount: number;\n}\n\nexport interface SurveyAssistantInspectionFocus {\n focusItemId: string;\n parentItemId?: string;\n pathItemIds: string[];\n siblingItemIds: string[];\n childItemIds: string[];\n}\n\nexport interface SurveyAssistantInspectionItemNode {\n itemId: string;\n itemType: string;\n editorName: string;\n breadcrumb: string;\n itemLabel?: string;\n siblingNames: string[];\n translations: Array<{ locale: string; ownerId: string; role: string; text: string }>;\n elements: Array<{ elementId: string; elementType: string; owners: ContentOwner[] }>;\n descendants: SurveyAssistantInspectionItemNode[];\n}\n\nexport interface SurveyAssistantInspectionItemEntry {\n itemId: string;\n itemType: string;\n editorName: string;\n breadcrumb: string;\n itemLabel?: string;\n path: string[];\n}\n\n/** Deterministic, request-local lookup data derived from the canonical document. */\nexport interface SurveyAssistantInspectionIndex {\n surveyKey?: string;\n locales: string[];\n /** All survey items except the structural root group. */\n itemCount: number;\n outline: SurveyAssistantInspectionOutlineNode[];\n focus?: SurveyAssistantInspectionFocus;\n focusItem?: SurveyAssistantInspectionItemNode;\n itemIndex: SurveyAssistantInspectionItemEntry[];\n responseSlots: string[];\n focusItemTreeTruncated: boolean;\n}\n\n/** Request-local derived state built from one authoritative survey document. */\nexport interface SurveyAssistantEngineContext {\n document: SurveyDocumentSnapshot;\n version: SurveyDocumentVersion;\n survey: CompositionSurvey;\n /** Exact trusted parsed revision; shared owners, slots and expression locations. */\n model: Survey;\n ui: SurveyDocumentSnapshot[\"ui\"];\n capabilities: SurveyAssistantCapabilityManifest;\n responseSlotTypes: SurveyAssistantResponseSlotTypes;\n responseVariables: readonly ReadonlyResponseSlotDefinition[];\n inspection: SurveyAssistantInspectionIndex;\n trustedCapabilities?: SurveyAssistantCapabilitySet;\n}\n\nexport interface CreateSurveyAssistantEngineContextOptions {\n focusItemId?: string;\n}\n\nconst getChildIds = (item: FlowItem): string[] =>\n item.itemType === \"group\" ? item.config.items : [];\n\nexport const deriveResponseSlotTypes = (\n survey: CompositionSurvey,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n): SurveyAssistantResponseSlotTypes =>\n Object.fromEntries(\n createAssistantSurvey(survey, trustedCapabilities).slots.definitions.map((slot) => [\n slot.slotId,\n slot.valueType,\n ]),\n );\n\nconst buildDerivedContext = (\n snapshot: SurveyDocumentSnapshot,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n requestedFocusItemId?: string,\n) => {\n const rawItems = snapshot.survey.surveyItems;\n const itemsById = new Map(rawItems.map((item) => [item.id, item]));\n const parentById = new Map<string, string>();\n for (const item of rawItems) {\n for (const childId of getChildIds(item)) {\n if (itemsById.has(childId) && !parentById.has(childId)) parentById.set(childId, item.id);\n }\n }\n\n const model = createAssistantSurvey(snapshot.survey, trustedCapabilities);\n const name = (id: string) => model.resolveItemEditorName(id, snapshot.ui.selectedLocale);\n const getNamePath = (id: string) => {\n const names = [name(id)];\n const seen = new Set([id]);\n let parent = parentById.get(id);\n while (parent && !seen.has(parent)) {\n seen.add(parent);\n names.unshift(name(parent));\n parent = parentById.get(parent);\n }\n return names;\n };\n\n const outline: SurveyAssistantInspectionOutlineNode[] = [];\n const visited = new Set<string>();\n const visit = (itemId: string, depth: number) => {\n if (visited.has(itemId)) return;\n const item = itemsById.get(itemId);\n if (!item) return;\n visited.add(itemId);\n outline.push({\n itemId,\n parentId: parentById.get(itemId),\n depth,\n itemType: item.itemType,\n editorName: name(item.id),\n breadcrumb: getNamePath(itemId).join(\" / \"),\n itemLabel: item.metadata?.itemLabel,\n childCount: getChildIds(item).length,\n });\n for (const childId of getChildIds(item)) visit(childId, depth + 1);\n };\n\n const explicitRoot = rawItems.find(\n (item) => item.itemType === \"group\" && item.config.isRoot === true,\n );\n if (explicitRoot) visit(explicitRoot.id, 0);\n for (const item of [...rawItems].sort((left, right) => left.id.localeCompare(right.id))) {\n if (!visited.has(item.id)) visit(item.id, 0);\n }\n\n const itemIndex: SurveyAssistantInspectionItemEntry[] = outline.map((node) => ({\n itemId: node.itemId,\n itemType: node.itemType,\n editorName: node.editorName,\n breadcrumb: node.breadcrumb,\n itemLabel: node.itemLabel,\n path: getNamePath(node.itemId),\n }));\n\n const buildFocusNode = (\n itemId: string,\n budget: { remaining: number },\n ): SurveyAssistantInspectionItemNode => {\n const item = itemsById.get(itemId)!;\n budget.remaining -= 1;\n const owners = [...model.owners.values()].filter((owner) => owner.itemId === itemId);\n const translationSnippets = Object.entries(model.data.translations ?? {})\n .flatMap(([locale, translations]) =>\n owners.flatMap((owner) =>\n Object.entries(ownValue(translations.content, owner.id) ?? {}).map(([role, content]) => ({\n locale,\n ownerId: owner.id,\n role,\n text: getContentPlainText(content).slice(0, 120),\n })),\n ),\n )\n .slice(0, 40);\n return {\n itemId,\n itemType: item.itemType,\n editorName: name(item.id),\n breadcrumb: getNamePath(itemId).join(\" / \"),\n itemLabel: item.metadata?.itemLabel,\n siblingNames: rawItems\n .filter(\n (candidate) =>\n candidate.id !== itemId && parentById.get(candidate.id) === parentById.get(itemId),\n )\n .map((candidate) => name(candidate.id)),\n translations: translationSnippets,\n elements: [...model.elements.values()]\n .filter((element) => element.itemId === itemId)\n .map((element) => ({\n elementId: element.node.id,\n elementType: element.node.elementType,\n owners: owners.filter((owner) => owner.elementId === element.node.id),\n })),\n descendants: getChildIds(item)\n .filter((childId) => itemsById.has(childId) && budget.remaining > 0)\n .map((childId) => buildFocusNode(childId, budget)),\n };\n };\n\n const focusItemId = requestedFocusItemId ?? snapshot.ui.focusItemId ?? snapshot.ui.selectedItemId;\n let focus: SurveyAssistantInspectionFocus | undefined;\n let focusItem: SurveyAssistantInspectionItemNode | undefined;\n let focusItemTreeTruncated = false;\n if (focusItemId && itemsById.has(focusItemId)) {\n const pathItemIds: string[] = [];\n let currentId: string | undefined = focusItemId;\n const pathSeen = new Set<string>();\n while (currentId && !pathSeen.has(currentId)) {\n pathSeen.add(currentId);\n pathItemIds.unshift(currentId);\n currentId = parentById.get(currentId);\n }\n const parentItemId = parentById.get(focusItemId);\n focus = {\n focusItemId,\n parentItemId,\n pathItemIds,\n siblingItemIds: rawItems\n .filter(\n (candidate) =>\n candidate.id !== focusItemId && parentById.get(candidate.id) === parentItemId,\n )\n .map((candidate) => candidate.id),\n childItemIds: getChildIds(itemsById.get(focusItemId)!),\n };\n const budget = { remaining: 120 };\n focusItem = buildFocusNode(focusItemId, budget);\n focusItemTreeTruncated = budget.remaining === 0;\n }\n\n const responseSlotTypes = Object.fromEntries(\n model.slots.definitions.map((slot) => [slot.slotId, slot.valueType]),\n );\n const locales = [\n snapshot.ui.selectedLocale,\n ...Object.keys(snapshot.survey.translations ?? {}).filter(\n (locale) => locale !== snapshot.ui.selectedLocale,\n ),\n ].filter((locale, index, values) => locale.length > 0 && values.indexOf(locale) === index);\n\n const inspection: SurveyAssistantInspectionIndex = {\n surveyKey: snapshot.survey.metadata?.surveyKey,\n locales,\n itemCount: rawItems.filter((item) => item.id !== explicitRoot?.id).length,\n outline,\n focus,\n focusItem,\n itemIndex,\n responseSlots: model.slots.definitions.map((slot) => slot.slotId),\n focusItemTreeTruncated,\n };\n\n return {\n inspection,\n model,\n responseSlotTypes,\n responseVariables: model.slots.definitions,\n };\n};\n\nexport const createSurveyAssistantEngineContext = (\n document: SurveyDocumentSnapshot,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n options?: CreateSurveyAssistantEngineContextOptions,\n): SurveyAssistantEngineContext => {\n assertSurveyAssistantCapabilities({\n manifest: document.capabilities,\n trustedCapabilities,\n versionDigest: document.version.capabilityDigest,\n });\n const { inspection, model, responseSlotTypes, responseVariables } = buildDerivedContext(\n document,\n trustedCapabilities,\n options?.focusItemId,\n );\n return {\n document,\n version: document.version,\n survey: model.serialize(),\n model,\n ui: document.ui,\n capabilities: document.capabilities,\n responseSlotTypes,\n responseVariables,\n inspection,\n trustedCapabilities,\n };\n};\n","import {\n collectExpressionDependencies,\n expressionIssues,\n expressionSchema,\n inferExpressionReturnType,\n functionTypeIssues,\n type ResponseSlotTypeLookup,\n transformExpression,\n unreachable,\n type JsonExpression,\n type ValueType,\n} from \"@case-framework/survey-core\";\nimport type { SurveyValidationIssue } from \"../protocol\";\n\nexport {\n inferExpressionReturnType,\n type ResponseSlotTypeLookup,\n} from \"@case-framework/survey-core\";\n\nexport const validateExpression = ({\n expression,\n expectedReturnType,\n issues,\n operationIndex,\n responseSlotTypes,\n stateTargets,\n scope,\n}: {\n expression: JsonExpression | undefined;\n expectedReturnType?: ValueType;\n issues: SurveyValidationIssue[];\n operationIndex: number;\n responseSlotTypes: ResponseSlotTypeLookup;\n /** All structural owners in the exact trusted definition, including inherited state targets. */\n stateTargets: ReadonlySet<string>;\n scope: string;\n}) => {\n const report = (code: string, message: string) =>\n issues.push({ severity: \"error\", code, message: `${scope}: ${message}`, operationIndex });\n if (!expression) {\n report(\"missing-expression\", \"An expression is required.\");\n return;\n }\n const parsed = expressionSchema.safeParse(expression);\n if (!parsed.success) {\n report(\"invalid-expression\", `Invalid expression JSON: ${parsed.error.message}`);\n return;\n }\n for (const dependency of collectExpressionDependencies(parsed.data)) {\n switch (dependency.kind) {\n case \"answer\":\n if (!Object.hasOwn(responseSlotTypes, dependency.slotId))\n report(\n \"unknown-response-ref\",\n `Unknown response slot \"${dependency.slotId}\". Inspect response slots before using it.`,\n );\n break;\n case \"state\":\n if (!stateTargets.has(dependency.targetRef.ownerId))\n report(\n \"unknown-state-ref\",\n `Unknown disabled-state owner \"${dependency.targetRef.ownerId}\". Inspect structural owners before using it.`,\n );\n break;\n default:\n unreachable(dependency);\n }\n }\n for (const issue of expressionIssues(parsed.data))\n report(\n \"expression-function-signature-mismatch\",\n `${issue.message} at ${JSON.stringify(issue.path)}.`,\n );\n transformExpression(parsed.data, {\n const: (node) => node,\n responseVariable: (node) => node,\n ownerState: (node) => node,\n contextVariable: (node) => node,\n function: (node, path) => {\n functionTypeIssues(node, responseSlotTypes).forEach((message) =>\n report(\"expression-function-signature-mismatch\", `${message} at ${JSON.stringify(path)}.`),\n );\n return node;\n },\n });\n const inferred = inferExpressionReturnType(parsed.data, responseSlotTypes);\n if (expectedReturnType && inferred && inferred !== expectedReturnType)\n report(\n \"expression-return-type-mismatch\",\n `Must return ${expectedReturnType}, but this expression returns ${inferred}.`,\n );\n};\n","import {\n getDefinitionDiagnostics,\n ownerAtPath,\n type SchemaPath,\n type Survey,\n} from \"@case-framework/survey-core\";\nimport type { SurveyValidationIssue } from \"../protocol/operations\";\nimport { stableStringify } from \"../protocol/digest\";\n\nexport const getDiagnosticLocation = (survey: Survey, path?: SchemaPath, ownerId?: string) => {\n const owner = ownerId ? survey.owners.get(ownerId) : path ? ownerAtPath(survey, path) : undefined;\n return owner && path && owner.path.every((part, index) => part === path[index])\n ? { ownerId: owner.id, path: path.slice(owner.path.length) }\n : { path };\n};\n\nexport const getIntroducedDefinitionIssues = (\n before: Survey,\n after: Survey,\n locale?: string,\n): SurveyValidationIssue[] => {\n const key = (survey: Survey, issue: ReturnType<typeof getDefinitionDiagnostics>[number]) =>\n stableStringify([\n issue.code,\n getDiagnosticLocation(survey, issue.path, issue.ownerId),\n issue.message,\n ]);\n const prior = new Set(\n getDefinitionDiagnostics(before, locale).map((issue) => key(before, issue)),\n );\n return getDefinitionDiagnostics(after, locale)\n .filter((issue) => !prior.has(key(after, issue)))\n .map((issue) => ({\n severity: issue.severity,\n code: issue.code,\n // Human editors may leave broken references to repair later; assistant changes may not.\n message:\n issue.kind === \"reference\"\n ? `${JSON.stringify(issue.path)}: ${issue.message}. Repair or remove this reference in the same change.`\n : issue.message,\n itemId: issue.ownerItemId,\n }));\n};\n","import {\n DefinitionError,\n getDefinitionDiagnostics,\n type CompositionSurvey,\n type LocatedDefinitionDiagnostic,\n} from \"@case-framework/survey-core\";\nimport { createAssistantSurvey } from \"./survey-model\";\nimport type { SurveyAssistantCapabilitySet } from \"./capabilities\";\n\n/** Includes the same answer/state/dependency/quality checks the editor presents. */\nexport const analyzeSurveyAssistantExpressionReferences = (\n survey: CompositionSurvey,\n trustedCapabilities?: SurveyAssistantCapabilitySet,\n locale?: string,\n): LocatedDefinitionDiagnostic[] => {\n try {\n return getDefinitionDiagnostics(createAssistantSurvey(survey, trustedCapabilities), locale);\n } catch (error) {\n if (error instanceof DefinitionError) return [...error.diagnostics];\n return [\n {\n severity: \"error\",\n code: \"invalid-survey-schema\",\n path: [],\n message: error instanceof Error ? error.message : String(error),\n },\n ];\n }\n};\nexport const getSurveyAssistantExpressionDiagnosticGuidance = (\n diagnostic: Pick<LocatedDefinitionDiagnostic, \"code\" | \"severity\" | \"kind\">,\n): string => {\n if (diagnostic.kind === \"reference\")\n return \"This reference points at content that no longer exists, usually after the author deleted or changed it. Inspect the owning item, current response slots and options, then retarget it to the intended replacement or remove the dependent condition, rule, prefill or setting if it no longer applies. Do not guess a replacement from spelling.\";\n if (diagnostic.code.includes(\"cycle\"))\n return \"Break the answer/state dependency cycle using an independent controlling answer or recorded context. A child inherits its ancestors' disabled state; prefills do not break cycles.\";\n if (diagnostic.code === \"external-checkbox-lock\")\n return \"Use visibility for answers that stop applying. Disabled checkboxes keep selected values and cannot be unticked. Use selected-and-enabled only when inherited locking should also exclude the option from this expression.\";\n return diagnostic.severity === \"error\"\n ? \"Repair this located definition error using current owner and slot IDs before claiming success.\"\n : \"Review this author warning in the selected language; preserve intentional survey logic.\";\n};\n","import { z } from \"zod\";\nimport {\n SurveyStateGraph,\n applyJsonPatch,\n inspectAnnotated,\n encodeJsonPointerSegment,\n parseJsonPointer,\n expressionSchema,\n slotPrefillSchema,\n templateValueSchema,\n validationRuleSchema,\n unreachable,\n ownValue,\n setOwnValue,\n Survey,\n type JsonExpression,\n type JsonPatchOperation,\n type SchemaPath,\n type ValueType,\n} from \"@case-framework/survey-core\";\nimport { jsonValueSchema } from \"../protocol/content\";\nimport type { SurveyValidationIssue } from \"../protocol\";\nimport { validateExpression } from \"./expression-validation\";\n\n// One expression grammar for storage, the editor, runtime and assistant contracts.\nexport { expressionSchema } from \"@case-framework/survey-core\";\nconst id = z.string().min(1);\nexport const expressionMutationSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"set-condition\"),\n ownerId: id,\n property: z.enum([\"visibility\", \"disabled\"]),\n expression: expressionSchema,\n }),\n z.strictObject({\n kind: z.literal(\"clear-condition\"),\n ownerId: id,\n property: z.enum([\"visibility\", \"disabled\"]),\n }),\n z.strictObject({\n kind: z.literal(\"set-config-expression\"),\n elementId: id,\n path: z.string().startsWith(\"/\"),\n expression: expressionSchema,\n }),\n z.strictObject({\n kind: z.literal(\"clear-config-expression\"),\n elementId: id,\n path: z.string().startsWith(\"/\"),\n }),\n z.strictObject({\n kind: z.literal(\"set-validation-rule\"),\n itemId: id,\n rule: validationRuleSchema,\n }),\n z.strictObject({ kind: z.literal(\"remove-validation-rule\"), itemId: id, ruleId: id }),\n z.strictObject({\n kind: z.literal(\"set-prefill\"),\n elementId: id,\n slotId: id,\n prefill: slotPrefillSchema,\n }),\n z.strictObject({ kind: z.literal(\"clear-prefill\"), elementId: id, slotId: id, prefillId: id }),\n z.strictObject({\n kind: z.literal(\"set-template-value\"),\n templateKey: id,\n templateValue: templateValueSchema,\n }),\n z.strictObject({ kind: z.literal(\"clear-template-value\"), templateKey: id }),\n]);\nexport type ExpressionMutation = z.infer<typeof expressionMutationSchema>;\nconst pointer = (path: SchemaPath) =>\n path.length ? `/${path.map((part) => encodeJsonPointerSegment(String(part))).join(\"/\")}` : \"\";\nconst readAt = (root: unknown, path: SchemaPath) =>\n path.reduce<unknown>(\n (value, part) =>\n value && typeof value === \"object\" ? (value as Record<string, unknown>)[part] : undefined,\n root,\n );\nconst isLiteral = (value: unknown) => typeof value === \"number\" || typeof value === \"string\";\n\n/** Compile against the exact trusted registry and one detached accepted revision.\n * Conditions are located through annotated owners, including custom components.\n * Only the final batch graph is compiled, so a multi-step cycle repair is atomic.\n * The turn draft and normal editor apply path remain responsible for publishing.\n */\nexport function buildExpressionMutationBatch(\n mutations: readonly ExpressionMutation[],\n definition: Survey,\n): { issues: SurveyValidationIssue[]; patches: JsonPatchOperation[] } {\n const issues: SurveyValidationIssue[] = [];\n const patches: JsonPatchOperation[] = [];\n let working = definition;\n for (const [operationIndex, input] of mutations.entries()) {\n const pending: JsonPatchOperation[] = [];\n const report = (code: string, message: string, severity: \"error\" | \"warning\" = \"error\") =>\n issues.push({ severity, code, message, operationIndex });\n const put = (path: SchemaPath, value: unknown) =>\n pending.push({ op: \"add\", path: pointer(path), value: jsonValueSchema.parse(value) });\n const remove = (path: SchemaPath, exists: boolean) =>\n exists\n ? pending.push({ op: \"remove\", path: pointer(path) })\n : report(\n \"expression-location-already-empty\",\n `${pointer(path)} is already empty.`,\n \"warning\",\n );\n const check = (\n expression: JsonExpression | undefined,\n scope: string,\n expectedReturnType?: ValueType,\n ) =>\n validateExpression({\n expression,\n scope,\n expectedReturnType,\n issues,\n operationIndex,\n responseSlotTypes: Object.fromEntries(\n working.slots.definitions.map((slot) => [slot.slotId, slot.valueType]),\n ),\n stateTargets: new Set(working.owners.keys()),\n });\n try {\n const mutation = expressionMutationSchema.parse(input);\n switch (mutation.kind) {\n case \"set-config-expression\":\n case \"clear-config-expression\": {\n const element = working.elements.get(mutation.elementId);\n if (!element) throw new Error(`Unknown element \"${mutation.elementId}\".`);\n const path = [...element.path, \"config\", ...parseJsonPointer(mutation.path)];\n const location = pointer(path);\n // Declared bounds (`boundField`) are a literal or `{ expression, fallback? }`.\n const boundPath = path.at(-1) === \"expression\" ? path.slice(0, -1) : undefined;\n const bound = boundPath && readAt(working.serialize(), boundPath);\n const declaredBound =\n !!boundPath &&\n inspectAnnotated(working.registry.elementSchema, element.node).some(\n (visit) =>\n visit.annotation.kind === \"bound\" &&\n pointer([...element.path, ...visit.path]) === pointer(boundPath),\n );\n if (mutation.kind === \"set-config-expression\") {\n check(mutation.expression, `element ${mutation.elementId} config ${mutation.path}`);\n // A fixed bound turns dynamic with its old value as the fallback. An absent parent\n // is created; the registered-schema check below rejects it where it does not fit.\n if (boundPath && (bound === undefined || (declaredBound && isLiteral(bound))))\n put(boundPath, {\n expression: mutation.expression,\n ...(bound === undefined ? {} : { fallback: bound }),\n });\n else put(path, mutation.expression);\n // Validate the real registered schema, then verify this exact location\n // is a declared expression root. Opaque config JSON is not an escape hatch.\n const candidate = Survey.parse(\n applyJsonPatch(working.serialize(), pending),\n working.registry,\n { admission: \"draft\" },\n );\n if (!candidate.expressions.some((entry) => pointer(entry.path) === location))\n throw new Error(\n `Config path \"${mutation.path}\" is not a registered expression field.`,\n );\n } else {\n if (!working.expressions.some((entry) => pointer(entry.path) === location))\n throw new Error(\n `Config path \"${mutation.path}\" does not contain a registered expression field.`,\n );\n // Clearing a declared bound restores its fallback, or removes the bound. In any\n // other config only the expression is removed.\n const fallback = declaredBound ? (bound as { fallback?: unknown }).fallback : undefined;\n if (boundPath && declaredBound)\n if (isLiteral(fallback)) put(boundPath, fallback);\n else remove(boundPath, true);\n else remove(path, true);\n }\n break;\n }\n case \"set-condition\":\n case \"clear-condition\": {\n const owner = working.owners.get(mutation.ownerId);\n if (!owner)\n throw new Error(\n `Unknown structural owner \"${mutation.ownerId}\". Inspect owners before editing a condition.`,\n );\n const path = [...owner.path, mutation.property];\n if (mutation.kind === \"set-condition\") {\n check(mutation.expression, `${mutation.property} of ${mutation.ownerId}`, \"boolean\");\n put(path, mutation.expression);\n } else remove(path, owner[mutation.property] !== undefined);\n break;\n }\n case \"set-validation-rule\":\n case \"remove-validation-rule\": {\n const item = working.flowItems.get(mutation.itemId);\n const owner = working.owners.get(mutation.itemId);\n if (!item || item.itemType !== \"content\" || !owner)\n throw new Error(`Validation rules require a content item: \"${mutation.itemId}\".`);\n const path = [...owner.path, \"config\", \"validationRules\"];\n const rules = [...(item.config.validationRules ?? [])];\n const ruleId =\n mutation.kind === \"set-validation-rule\" ? mutation.rule.id : mutation.ruleId;\n const index = rules.findIndex((rule) => rule.id === ruleId);\n if (mutation.kind === \"set-validation-rule\") {\n check(mutation.rule.expression, `validation ${ruleId}`, \"boolean\");\n if (mutation.rule.when)\n check(mutation.rule.when, `validation ${ruleId} condition`, \"boolean\");\n if (index < 0) rules.push(mutation.rule);\n else rules[index] = mutation.rule;\n put(path, rules);\n } else if (index >= 0) {\n remove([...path, index], true);\n // A removed rule owns its message in every locale, not just the current one.\n for (const [locale, translations] of Object.entries(working.data.translations ?? {}))\n if (Object.hasOwn(translations.content, ruleId))\n remove([\"translations\", locale, \"content\", ruleId], true);\n } else\n report(\n \"expression-location-already-empty\",\n `Validation \"${ruleId}\" is already absent.`,\n \"warning\",\n );\n break;\n }\n case \"set-prefill\":\n case \"clear-prefill\": {\n const element = working.elements.get(mutation.elementId);\n const slot = working.slots.get(mutation.slotId);\n if (!element || !slot || slot.elementId !== mutation.elementId || slot.computed)\n throw new Error(\n `Prefill target \"${mutation.slotId}\" must be a stored slot owned by element \"${mutation.elementId}\".`,\n );\n const prefills = structuredClone(element.node.prefills ?? {});\n const entries = ownValue(prefills, mutation.slotId) ?? [];\n const prefillId =\n mutation.kind === \"set-prefill\" ? mutation.prefill.id : mutation.prefillId;\n const index = entries.findIndex((prefill) => prefill.id === prefillId);\n if (mutation.kind === \"set-prefill\") {\n if (mutation.prefill.when)\n check(mutation.prefill.when, `prefill ${prefillId} condition`, \"boolean\");\n if (mutation.prefill.source.type === \"expression\")\n check(\n mutation.prefill.source.expression,\n `prefill ${prefillId} value`,\n slot.valueType,\n );\n if (index < 0) entries.push(mutation.prefill);\n else entries[index] = mutation.prefill;\n } else if (index >= 0) entries.splice(index, 1);\n else\n report(\n \"expression-location-already-empty\",\n `Prefill \"${prefillId}\" is already absent.`,\n \"warning\",\n );\n if (entries.length) setOwnValue(prefills, mutation.slotId, entries);\n else delete prefills[mutation.slotId];\n put([...element.path, \"prefills\"], prefills);\n break;\n }\n case \"set-template-value\":\n case \"clear-template-value\": {\n if (mutation.kind === \"set-template-value\") {\n if (mutation.templateValue.expression)\n check(\n mutation.templateValue.expression,\n `template ${mutation.templateKey}`,\n mutation.templateValue.type === \"formatDate\"\n ? \"date\"\n : mutation.templateValue.returnType,\n );\n put([\"templateValues\"], {\n ...working.data.templateValues,\n [mutation.templateKey]: mutation.templateValue,\n });\n } else\n remove(\n [\"templateValues\", mutation.templateKey],\n Object.hasOwn(working.data.templateValues ?? {}, mutation.templateKey),\n );\n break;\n }\n default:\n unreachable(mutation);\n }\n if (issues.some((issue) => issue.severity === \"error\")) return { issues, patches: [] };\n // Existing author-left broken references stay editable; new ones are rejected by `check`\n // and by the proposal's introduced-diagnostics comparison.\n working = Survey.parse(applyJsonPatch(working.serialize(), pending), definition.registry, {\n admission: \"draft\",\n });\n patches.push(...pending);\n } catch (error) {\n report(\n \"expression-mutation-transition-failed\",\n error instanceof Error ? error.message : String(error),\n );\n return { issues, patches: [] };\n }\n }\n try {\n // Unrelated unfinished author drafts remain editable. Every new operand above\n // was checked, and all structural/state/follow-up/prefill cycles still reject.\n new SurveyStateGraph(working, { admission: \"draft\" });\n } catch (error) {\n issues.push({\n severity: \"error\",\n code: \"invalid-expression-graph\",\n message: error instanceof Error ? error.message : String(error),\n });\n return { issues, patches: [] };\n }\n return { issues, patches };\n}\n","import {\n getContentPlainText,\n encodeJsonPointerSegment,\n collectExpressionDependencies,\n ownValue,\n stringRecord,\n type Survey,\n type CompositionSurvey,\n type FlowItem,\n} from \"@case-framework/survey-core\";\nimport type { SurveyAssistantEngineContext } from \"./context\";\nimport { jsonValueSchema } from \"../protocol/content\";\nimport { z } from \"zod\";\n\nexport const DEFAULT_LIMIT = 12;\nexport const MAX_LIMIT = 50;\n\nexport const itemSummarySchema = z.object({\n itemId: z.string(),\n itemType: z.string(),\n editorName: z.string(),\n breadcrumb: z.string(),\n itemLabel: z.string().optional(),\n parentId: z.string().optional(),\n depth: z.number().int().nonnegative().optional(),\n childCount: z.number().int().nonnegative().optional(),\n path: z.array(z.string()).optional(),\n siblingNames: z.array(z.string()).optional(),\n});\n\nexport type ItemSummary = z.infer<typeof itemSummarySchema>;\n\nexport const translationEntrySchema = z.object({\n locale: z.string(),\n ownerId: z.string(),\n role: z.string(),\n text: z.string(),\n});\n\nexport type TranslationEntry = z.infer<typeof translationEntrySchema>;\n\nconst schemaPath = z.array(z.union([z.string(), z.number()]));\nexport const contentOwnerDetailsSchema = z.object({\n ownerId: z.string(),\n kind: z.string(),\n position: z.number().int().positive().optional(),\n parentId: z.string().optional(),\n elementId: z.string().optional(),\n path: schemaPath,\n roles: z.array(\n z.object({\n role: z.string(),\n policy: z.enum([\"inline\", \"block\"]),\n recommended: z.boolean().optional(),\n }),\n ),\n visibility: z.boolean(),\n disabled: z.boolean(),\n followUpTriggerId: z.string().optional(),\n});\nexport const elementDetailsSchema = z.object({\n elementId: z.string(),\n elementType: z.string(),\n position: z.number().int().positive().optional(),\n path: schemaPath,\n configPath: z.string(),\n config: jsonValueSchema,\n responseSlotIds: z.array(z.string()),\n owners: z.array(contentOwnerDetailsSchema),\n});\nexport const itemConfigDetailsSchema = z.object({\n kind: z.enum([\"content\", \"group\", \"page-break\"]),\n summary: z.array(z.string()),\n listOrdering: stringRecord(z.string(), z.string()),\n elements: z.array(elementDetailsSchema),\n owners: z.array(contentOwnerDetailsSchema),\n bodyLocations: z.array(\n z.object({ ownerId: z.string(), path: schemaPath, followUp: z.boolean() }),\n ),\n});\nexport type ItemConfigDetails = z.infer<typeof itemConfigDetailsSchema>;\n\nexport type SurveyInspectionIndex = SurveyAssistantEngineContext[\"inspection\"];\nexport type SurveyOutlineNode = SurveyInspectionIndex[\"outline\"][number];\nexport type SurveyItemIndexEntry = SurveyInspectionIndex[\"itemIndex\"][number];\nexport type SurveyFocusItemNode = NonNullable<SurveyInspectionIndex[\"focusItem\"]>;\n\nexport const normalizeText = (value: string | undefined) => value?.trim().toLowerCase() ?? \"\";\n\nexport const clampLimit = (limit: number | undefined) =>\n Math.min(MAX_LIMIT, Math.max(1, limit ?? DEFAULT_LIMIT));\n\nexport const parseCursor = (cursor: string | undefined): number => {\n if (!cursor) {\n return 0;\n }\n\n const parsed = Number.parseInt(cursor, 10);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;\n};\n\nexport const unique = <T>(values: T[]): T[] => Array.from(new Set(values));\n\nexport const sliceWithCursor = <T>(\n values: readonly T[],\n input: { cursor?: string; limit?: number },\n) => {\n const offset = parseCursor(input.cursor);\n const limit = clampLimit(input.limit);\n const nextOffset = offset + limit;\n const items = values.slice(offset, nextOffset);\n\n return {\n items,\n nextCursor: nextOffset < values.length ? String(nextOffset) : undefined,\n truncated: nextOffset < values.length,\n };\n};\n\nexport const mapOutlineById = (snapshot: SurveyAssistantEngineContext) =>\n new Map(snapshot.inspection.outline.map((item) => [item.itemId, item]));\n\nexport const mapItemIndexById = (snapshot: SurveyAssistantEngineContext) =>\n new Map(snapshot.inspection.itemIndex.map((item) => [item.itemId, item]));\n\n/** The full-survey item index, regardless of the (possibly focus-scoped) outline. */\nexport const getItemIndexEntries = (\n snapshot: SurveyAssistantEngineContext,\n): SurveyItemIndexEntry[] => snapshot.inspection.itemIndex;\n\nexport const getRawSurvey = (snapshot: SurveyAssistantEngineContext): CompositionSurvey =>\n snapshot.survey;\nexport const getRawSurveyItems = (snapshot: SurveyAssistantEngineContext): FlowItem[] =>\n snapshot.survey.surveyItems;\nexport const mapRawItemsById = (snapshot: SurveyAssistantEngineContext) =>\n new Map(getRawSurveyItems(snapshot).map((item) => [item.id, item]));\n\nexport const summarizeRawItem = (item: FlowItem): ItemSummary => ({\n itemId: item.id,\n itemType: item.itemType,\n editorName: item.metadata?.itemLabel?.trim() || item.id,\n breadcrumb: item.id,\n itemLabel: item.metadata?.itemLabel,\n});\n\nexport const buildItemTranslationEntries = (\n snapshot: SurveyAssistantEngineContext,\n itemId: string,\n input: { locales?: string[]; textLimit?: number },\n): TranslationEntry[] => {\n const localeFilter = input.locales?.length ? new Set(input.locales) : undefined;\n const textLimit = input.textLimit ?? 400;\n const entries: TranslationEntry[] = [];\n const owners = [...snapshot.model.owners.values()].filter((owner) => owner.itemId === itemId);\n for (const [locale, translations] of Object.entries(snapshot.model.data.translations ?? {})) {\n if (localeFilter && !localeFilter.has(locale)) continue;\n for (const owner of owners)\n for (const [role, content] of Object.entries(\n ownValue(translations.content, owner.id) ?? {},\n )) {\n const text = getContentPlainText(content).trim();\n if (text)\n entries.push({\n locale,\n ownerId: owner.id,\n role,\n text: text.length > textLimit ? `${text.slice(0, textLimit)}...` : text,\n });\n }\n }\n return entries;\n};\n\nexport const summarizeOutlineNode = (node: SurveyOutlineNode): ItemSummary => ({\n itemId: node.itemId,\n itemType: node.itemType,\n editorName: node.editorName,\n breadcrumb: node.breadcrumb,\n itemLabel: node.itemLabel,\n parentId: node.parentId,\n depth: node.depth,\n childCount: node.childCount,\n});\n\nexport const summarizeItemIndexEntry = (\n entry: SurveyItemIndexEntry,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary => {\n const outlineNode = outlineById.get(entry.itemId);\n\n return {\n itemId: entry.itemId,\n itemType: entry.itemType,\n editorName: entry.editorName,\n breadcrumb: entry.breadcrumb,\n itemLabel: entry.itemLabel,\n parentId: outlineNode?.parentId,\n depth: outlineNode?.depth,\n childCount: outlineNode?.childCount,\n path: entry.path,\n };\n};\n\nexport const summarizeItemIndexEntries = (\n entries: SurveyItemIndexEntry[],\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary[] => entries.map((entry) => summarizeItemIndexEntry(entry, outlineById));\n\n/** Components and follow-ups come from the registry's declared ownership, not type-name scanners. */\nexport const buildItemConfigDetails = (item: FlowItem, model: Survey): ItemConfigDetails => {\n const owners = [...model.owners.values()]\n .filter((owner) => owner.itemId === item.id)\n .map((owner) => ({\n ownerId: owner.id,\n kind: owner.kind,\n position:\n owner.kind !== \"item\" && typeof owner.path.at(-1) === \"number\"\n ? Number(owner.path.at(-1)) + 1\n : undefined,\n parentId: owner.parentId,\n elementId: owner.elementId,\n path: [...owner.path],\n roles: [...owner.roles],\n visibility: owner.visibility !== undefined,\n disabled: owner.disabled !== undefined,\n followUpTriggerId: owner.followUpTriggerId,\n }));\n const elements = [...model.elements.values()]\n .filter((element) => element.itemId === item.id)\n .map((element) => ({\n elementId: element.node.id,\n elementType: element.node.elementType,\n position:\n typeof element.path.at(-1) === \"number\" ? Number(element.path.at(-1)) + 1 : undefined,\n path: [...element.path],\n configPath: `/${[...element.path, \"config\"].map((part) => encodeJsonPointerSegment(String(part))).join(\"/\")}`,\n config: jsonValueSchema.parse(element.node.config),\n responseSlotIds: element.facts.slots.map((slot) => slot.slotId),\n owners: owners.filter((owner) => owner.elementId === element.node.id),\n }));\n return {\n kind: item.itemType,\n listOrdering: {\n elements:\n \"Authored depth-first traversal, including follow-ups; position is one-based within each element's own layout, not this flattened list.\",\n owners:\n \"Declared content-owner traversal. A position is one-based within the array identified by path; consult the element's shuffle configuration before interpreting it as respondent-visible order.\",\n bodyLocations:\n \"Authored body traversal; follow-ups stay directly under their triggering owner, not after the entire element.\",\n },\n summary:\n item.itemType === \"content\"\n ? [`${elements.length} elements in vertically ordered layouts and sections`]\n : item.itemType === \"group\"\n ? [`${item.config.items.length} flow children`]\n : [\"Page break\"],\n elements,\n owners,\n bodyLocations: [...model.bodies.values()]\n .filter((body) => model.owners.get(body.ownerId)?.itemId === item.id)\n .map((body) => ({ ...body, path: [...body.path] })),\n };\n};\nexport const buildConfigSearchText = (item: FlowItem, model: Survey): string[] => {\n const details = buildItemConfigDetails(item, model);\n const values = [\n ...details.summary,\n ...details.elements.flatMap((element) => [\n element.elementId,\n element.elementType,\n JSON.stringify(element.config),\n ]),\n ];\n for (const slot of model.slots.definitions.filter((slot) => slot.itemId === item.id))\n values.push(slot.slotId, slot.variableName, ...Object.values(slot.referenceValueKeys ?? {}));\n const itemPath = model.owners.get(item.id)?.path;\n if (itemPath)\n for (const entry of model.expressions)\n if (itemPath.every((part, index) => entry.path[index] === part))\n for (const reference of collectExpressionDependencies(entry.expression))\n values.push(reference.kind === \"answer\" ? reference.slotId : reference.targetRef.ownerId);\n return values;\n};\n\nexport const summarizeFocusItemNode = (\n node: SurveyFocusItemNode,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary => {\n const outlineNode = outlineById.get(node.itemId);\n\n return {\n itemId: node.itemId,\n itemType: node.itemType,\n editorName: node.editorName,\n breadcrumb: node.breadcrumb,\n itemLabel: node.itemLabel,\n parentId: outlineNode?.parentId,\n depth: outlineNode?.depth,\n childCount: outlineNode?.childCount ?? node.descendants.length,\n siblingNames: node.siblingNames,\n };\n};\n\nexport const summarizeItemById = (\n itemId: string,\n indexById: Map<string, SurveyItemIndexEntry>,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary | undefined => {\n const outlineNode = outlineById.get(itemId);\n if (outlineNode) {\n return summarizeOutlineNode(outlineNode);\n }\n\n const indexEntry = indexById.get(itemId);\n if (indexEntry) {\n return summarizeItemIndexEntry(indexEntry, outlineById);\n }\n\n return undefined;\n};\n\n/** Resolve only persistent item IDs. Search can discover names and breadcrumbs. */\nexport const resolveItemSummary = (\n identifier: string,\n indexById: Map<string, SurveyItemIndexEntry>,\n outlineById: Map<string, SurveyOutlineNode>,\n): ItemSummary | undefined => {\n const direct = summarizeItemById(identifier, indexById, outlineById);\n return direct;\n};\n\nexport const itemMatchesQuery = (item: ItemSummary, query: string) => {\n const haystack = [\n item.itemId,\n item.itemType,\n item.editorName,\n item.breadcrumb,\n item.itemLabel,\n ...(item.path ?? []),\n ...(item.siblingNames ?? []),\n ]\n .filter(Boolean)\n .join(\" \")\n .toLowerCase();\n\n return haystack.includes(query);\n};\n\n/**\n * Direct children of `parentId` derived from the full-survey item index.\n * This works for any item, selected or not.\n */\nexport const findDirectChildrenByParentId = (\n entries: SurveyItemIndexEntry[],\n outlineById: Map<string, SurveyOutlineNode>,\n parentId: string,\n): ItemSummary[] => {\n return entries\n .filter((entry) => outlineById.get(entry.itemId)?.parentId === parentId)\n .map((entry) => summarizeItemIndexEntry(entry, outlineById));\n};\n","import { ContentType, ownValue } from \"@case-framework/survey-core\";\nimport { surveyContentSchema } from \"../protocol\";\nimport { stableStringify } from \"../protocol/digest\";\n\ntype LooseRecord = Record<string, unknown>;\n\ntype RichTextStyle = {\n weight?: \"strong\" | \"normal\";\n italic?: \"italic\" | \"normal\";\n underline?: \"underline\" | \"none\";\n color?: \"primary\" | \"accent\" | \"default\";\n};\ntype RichTextTextInline = { type: \"text\"; text: string; style?: RichTextStyle };\ntype RichTextTemplateInline = { type: \"template\"; key: string; style?: RichTextStyle };\ntype RichTextLineBreakInline = { type: \"lineBreak\" };\ntype RichTextLinkInline = {\n type: \"link\";\n href: string;\n children: Array<RichTextTextInline | RichTextTemplateInline | RichTextLineBreakInline>;\n};\ntype RichTextInline =\n | RichTextTextInline\n | RichTextTemplateInline\n | RichTextLineBreakInline\n | RichTextLinkInline;\ntype RichTextParagraphBlock = { type: \"paragraph\"; children: RichTextInline[] };\n\ntype SurveyChangeNormalizationIssue = {\n path: string;\n message: string;\n};\n\nconst isRecord = (value: unknown): value is LooseRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getString = (value: unknown) => (typeof value === \"string\" ? value.trim() : undefined);\n\nconst textInline = (text: string, style?: RichTextStyle): RichTextTextInline => ({\n type: \"text\",\n text,\n ...(style ? { style } : {}),\n});\n\nconst paragraphBlock = (text: string, style?: RichTextStyle): RichTextParagraphBlock => ({\n type: \"paragraph\",\n children: [textInline(text, style)],\n});\n\nconst parseCanonicalRichTextBlocks = (blocks: unknown[]) => {\n const parsed = surveyContentSchema.safeParse({\n type: ContentType.richText,\n version: 1,\n doc: { type: \"doc\", blocks },\n });\n\n return parsed.success &&\n parsed.data.type === ContentType.richText &&\n // Parsing strips unknown keys, including supported shorthand style aliases.\n // Only bypass normalization when parsing preserves the complete input.\n stableStringify(parsed.data.doc.blocks) === stableStringify(blocks)\n ? parsed.data.doc.blocks\n : undefined;\n};\n\n// Visible rich-text runs may intentionally start or end with whitespace.\nconst getBlockText = (block: LooseRecord) =>\n [block.text, block.content, block.label].find(\n (value): value is string => typeof value === \"string\",\n );\n\n// Levels are passed through unchanged so the content grammar rejects invalid\n// ones and the model repairs the mistake instead of it being silently rewritten.\nconst getShorthandHeadingLevel = (value: LooseRecord): unknown => {\n if (value.level !== undefined) return value.level;\n const typeLevel = getString(value.type)\n ?.toLowerCase()\n .match(/^h([1-6])$/)?.[1];\n return typeLevel ? Number(typeLevel) : 2;\n};\n\nconst normalizeRichTextStyle = (value: LooseRecord): RichTextStyle | undefined => {\n const rawStyle = isRecord(value.style) ? value.style : {};\n const style: RichTextStyle = {};\n const weight = rawStyle.weight ?? value.weight;\n const italic = rawStyle.italic ?? value.italic;\n const underline = rawStyle.underline ?? value.underline;\n const color = rawStyle.color ?? value.color;\n\n if (value.strong === true || value.bold === true || weight === \"strong\" || weight === \"bold\") {\n style.weight = \"strong\";\n } else if (weight === \"normal\") {\n style.weight = \"normal\";\n }\n\n if (value.italic === true || italic === \"italic\") {\n style.italic = \"italic\";\n } else if (italic === \"normal\") {\n style.italic = \"normal\";\n }\n\n if (value.underline === true || underline === \"underline\") {\n style.underline = \"underline\";\n } else if (underline === \"none\") {\n style.underline = \"none\";\n }\n\n if (color === \"primary\" || color === \"accent\" || color === \"default\") {\n style.color = color;\n }\n\n return Object.keys(style).length > 0 ? style : undefined;\n};\n\nconst richTextShorthandNodeTypes: Readonly<Record<string, string>> = {\n \"bullet-list\": \"bulletList\",\n bulletlist: \"bulletList\",\n list: \"bulletList\",\n bullets: \"bulletList\",\n infobox: \"infoBox\",\n \"info-box\": \"infoBox\",\n note: \"infoBox\",\n footnote: \"infoBox\",\n divider: \"separator\",\n rule: \"separator\",\n linebreak: \"lineBreak\",\n \"line-break\": \"lineBreak\",\n break: \"lineBreak\",\n listitem: \"listItem\",\n inlineextension: \"inlineExtension\",\n blockextension: \"blockExtension\",\n};\n\nconst resolveRichTextShorthandNodeType = (value: unknown) => {\n const type = getString(value)?.toLowerCase();\n return type\n ? (ownValue(richTextShorthandNodeTypes, type) ?? (/^h[1-6]$/.test(type) ? \"heading\" : type))\n : undefined;\n};\n\nconst normalizeRichTextInline = (value: unknown, allowLink = true): unknown => {\n if (typeof value === \"string\") {\n return textInline(value);\n }\n\n if (!isRecord(value)) {\n return value;\n }\n\n const type = resolveRichTextShorthandNodeType(value.type);\n const canonicalParagraph = parseCanonicalRichTextBlocks([\n { type: \"paragraph\", children: [value] },\n ])?.[0];\n const canonicalInline =\n canonicalParagraph?.type === \"paragraph\" ? canonicalParagraph.children[0] : undefined;\n if (canonicalInline && (allowLink || canonicalInline.type !== \"link\")) {\n return canonicalInline;\n }\n\n if (type === \"lineBreak\") {\n return { type: \"lineBreak\" };\n }\n\n if (type === \"link\" && allowLink) {\n const href = getString(value.href) ?? getString(value.url);\n if (!href) {\n return undefined;\n }\n\n const childValues =\n value.children === undefined ? [getBlockText(value) ?? href] : value.children;\n const children = Array.isArray(childValues)\n ? childValues.map((child) => normalizeRichTextInline(child, false))\n : childValues;\n\n return { ...value, type: \"link\", href, children };\n }\n\n if (type && type !== \"text\") {\n return value;\n }\n\n const text = getBlockText(value);\n return text === undefined ? value : textInline(text, normalizeRichTextStyle(value));\n};\n\nconst normalizeRichTextChildren = (value: LooseRecord) => {\n if (!Array.isArray(value.children)) {\n return undefined;\n }\n\n const children = value.children.map((child) => normalizeRichTextInline(child));\n return children;\n};\n\n// Containers in the canonical grammar accept paragraphs, not arbitrary blocks.\n// Leave unsupported nesting intact for validation rather than recursively coercing it.\nconst normalizeRichTextParagraph = (value: unknown): unknown =>\n typeof value === \"string\" ||\n (isRecord(value) && (!value.type || getString(value.type)?.toLowerCase() === \"paragraph\"))\n ? normalizeRichTextBlock(value)\n : value;\n\nconst normalizeRichTextBlock = (value: unknown): unknown => {\n if (typeof value === \"string\") {\n return paragraphBlock(value);\n }\n\n if (!isRecord(value)) {\n return value;\n }\n\n const canonicalBlock = parseCanonicalRichTextBlocks([value])?.[0];\n if (canonicalBlock) {\n return canonicalBlock;\n }\n\n const type = resolveRichTextShorthandNodeType(value.type);\n const text = getBlockText(value);\n const style = normalizeRichTextStyle(value);\n const children = normalizeRichTextChildren(value);\n\n if (type === \"heading\") {\n return {\n ...value,\n type: \"heading\",\n level: getShorthandHeadingLevel(value),\n children:\n value.children !== undefined\n ? (children ?? value.children)\n : text !== undefined\n ? [textInline(text, style)]\n : undefined,\n };\n }\n\n if (type === \"bulletList\") {\n if (!Array.isArray(value.items)) return value;\n return {\n ...value,\n type: \"bulletList\",\n items: value.items.map((item) => {\n const itemText =\n typeof item === \"string\" ? item : isRecord(item) ? getBlockText(item) : undefined;\n if (isRecord(item) && Array.isArray(item.children)) {\n return {\n type: \"listItem\",\n ...item,\n children: item.children.map(normalizeRichTextParagraph),\n };\n }\n return itemText !== undefined\n ? {\n type: \"listItem\" as const,\n ...(isRecord(item) ? item : {}),\n children: [paragraphBlock(itemText)],\n }\n : item;\n }),\n };\n }\n\n if (type === \"infoBox\") {\n return {\n ...value,\n type: \"infoBox\",\n title:\n typeof value.title === \"string\"\n ? [textInline(value.title)]\n : Array.isArray(value.title)\n ? value.title.map((inline) => normalizeRichTextInline(inline))\n : value.title,\n children: Array.isArray(value.children)\n ? value.children.map(normalizeRichTextParagraph)\n : value.children !== undefined\n ? value.children\n : text !== undefined\n ? [paragraphBlock(text)]\n : undefined,\n };\n }\n\n if (type === \"image\") {\n return {\n ...value,\n type: \"image\",\n caption: Array.isArray(value.caption)\n ? value.caption.map(normalizeRichTextParagraph)\n : value.caption,\n };\n }\n\n if (type === \"separator\") {\n return { ...value, type: \"separator\" };\n }\n\n if (type === \"paragraph\" || !type) {\n if (!children && text === undefined) {\n return value;\n }\n return {\n ...value,\n type: \"paragraph\",\n children:\n value.children !== undefined\n ? (children ?? value.children)\n : [textInline(text ?? \"\", style)],\n };\n }\n\n return value;\n};\n\n// These are input conveniences, not an alternate content schema. The canonical\n// validator still owns node shapes; inspection prevents its unknown-key stripping\n// from silently losing body content or a model-authored link.\nconst RICH_TEXT_BODY_KEYS = [\"text\", \"content\", \"label\", \"children\", \"items\", \"blocks\"];\nconst MAX_RICH_TEXT_NORMALIZATION_ISSUES = 32;\nconst INSPECTABLE_RICH_TEXT_NODE_TYPES = new Set([\n \"paragraph\",\n \"heading\",\n \"bulletList\",\n \"listItem\",\n \"image\",\n \"infoBox\",\n \"separator\",\n \"blockExtension\",\n \"text\",\n \"template\",\n \"link\",\n \"lineBreak\",\n \"inlineExtension\",\n]);\n\nconst inspectRichTextNode = (\n value: unknown,\n path: string,\n issues: SurveyChangeNormalizationIssue[],\n shorthand: boolean,\n implicitType = \"paragraph\",\n depth = 0,\n) => {\n if (!isRecord(value) || issues.length >= MAX_RICH_TEXT_NORMALIZATION_ISSUES) return;\n const report = (field: string, message: string) => {\n if (issues.length < MAX_RICH_TEXT_NORMALIZATION_ISSUES) {\n issues.push({ path: field ? `${path}.${field}` : path, message });\n }\n };\n if (depth > 8) {\n report(\n \"\",\n \"Rich-text nesting exceeds the supported node structure. Use the documented block and inline grammar.\",\n );\n return;\n }\n const type = shorthand\n ? (resolveRichTextShorthandNodeType(value.type) ?? implicitType)\n : getString(value.type);\n // Unknown types belong to the canonical discriminator validator, whose error\n // lists valid alternatives. Body diagnostics would obscure that recovery path.\n if (!type || !INSPECTABLE_RICH_TEXT_NODE_TYPES.has(type)) return;\n const textBody =\n type === \"text\" ||\n (shorthand && [\"paragraph\", \"heading\", \"infoBox\", \"listItem\", \"link\"].includes(type ?? \"\"));\n const acceptsChildren = [\"paragraph\", \"heading\", \"infoBox\", \"listItem\", \"link\"].includes(\n type ?? \"\",\n );\n const bodyKeys = RICH_TEXT_BODY_KEYS.filter((key) => value[key] !== undefined);\n if (bodyKeys.length > 1) {\n report(\n \"\",\n `Conflicting rich-text body representations: ${bodyKeys.join(\", \")}. Provide one body representation; preserve all intended content in it.`,\n );\n }\n for (const key of bodyKeys) {\n const accepted =\n key === \"children\"\n ? acceptsChildren\n : key === \"items\"\n ? type === \"bulletList\"\n : key === \"blocks\"\n ? false\n : textBody && (shorthand || key === \"text\");\n if (!accepted) {\n report(\n key,\n key === \"blocks\"\n ? \"Nested blocks is not a supported node body. Use children for canonical nested content, items for a bulletList, or text for a simple shorthand body.\"\n : `The ${type ?? \"untyped\"} node does not support the ${key} body field. Use the documented node structure; image captions use caption paragraph blocks and separators have no body.`,\n );\n }\n if ([\"text\", \"content\", \"label\"].includes(key) && typeof value[key] !== \"string\") {\n report(\n key,\n \"Rich-text shorthand text must be a string. Use the documented children structure for nested content.\",\n );\n }\n }\n for (const key of [\"href\", \"url\"]) {\n if (value[key] !== undefined && (type !== \"link\" || (!shorthand && key === \"url\"))) {\n report(\n key,\n \"Links must use a link inline node with href and children (or text shorthand). A URL on another node is not rendered as a link.\",\n );\n }\n }\n for (const key of [\"title\", \"caption\"]) {\n if (\n value[key] !== undefined &&\n !(key === \"title\" ? type === \"infoBox\" || type === \"link\" : type === \"image\")\n ) {\n report(\n key,\n `The ${type ?? \"untyped\"} node does not support ${key}. Use the documented node structure to preserve this content.`,\n );\n }\n }\n for (const key of [\"children\", \"items\", \"title\", \"caption\"]) {\n const children = value[key];\n if (Array.isArray(children)) {\n const childType =\n key === \"items\"\n ? \"listItem\"\n : key === \"title\" ||\n (key === \"children\" && [\"paragraph\", \"heading\", \"link\"].includes(type ?? \"\"))\n ? \"text\"\n : \"paragraph\";\n for (\n let index = 0;\n index < children.length && issues.length < MAX_RICH_TEXT_NORMALIZATION_ISSUES;\n index++\n ) {\n inspectRichTextNode(\n children[index],\n `${path}.${key}.${index}`,\n issues,\n shorthand,\n childType,\n depth + 1,\n );\n }\n }\n }\n};\n\nconst normalizeRichTextContent = (\n value: unknown,\n path: string,\n issues: SurveyChangeNormalizationIssue[],\n): unknown => {\n if (!isRecord(value)) {\n return value;\n }\n\n if (value.type === ContentType.richText && isRecord(value.doc) && value.version === 1) {\n if (Array.isArray(value.doc.blocks)) {\n for (\n let index = 0;\n index < value.doc.blocks.length && issues.length < MAX_RICH_TEXT_NORMALIZATION_ISSUES;\n index++\n ) {\n inspectRichTextNode(value.doc.blocks[index], `${path}.doc.blocks.${index}`, issues, false);\n }\n }\n return value;\n }\n\n const candidateBlocks = Array.isArray(value.richTextBlocks)\n ? value.richTextBlocks\n : Array.isArray(value.blocks)\n ? value.blocks\n : undefined;\n if (!candidateBlocks) {\n return value;\n }\n\n const shorthandKey = Array.isArray(value.richTextBlocks) ? \"richTextBlocks\" : \"blocks\";\n const issueCount = issues.length;\n for (\n let index = 0;\n index < candidateBlocks.length && issues.length < MAX_RICH_TEXT_NORMALIZATION_ISSUES;\n index++\n ) {\n inspectRichTextNode(candidateBlocks[index], `${path}.${shorthandKey}.${index}`, issues, true);\n }\n // Rejected input never reaches staging. Avoid further traversal/allocation once\n // inspection has found loss or has exhausted the diagnostic budget.\n if (issues.length > issueCount || issues.length >= MAX_RICH_TEXT_NORMALIZATION_ISSUES)\n return value;\n const blocks = candidateBlocks.map(normalizeRichTextBlock);\n\n return {\n type: ContentType.richText,\n version: 1,\n doc: {\n type: \"doc\",\n blocks,\n },\n };\n};\n\nconst inspectTranslationRepresentations = (\n value: unknown,\n path: string,\n issues: SurveyChangeNormalizationIssue[],\n) => {\n if (!isRecord(value)) {\n return;\n }\n\n const shorthandKeys = ([\"richTextBlocks\", \"blocks\"] as const).filter((key) =>\n Object.prototype.hasOwnProperty.call(value, key),\n );\n if (value.plainText !== undefined && value.content !== undefined) {\n issues.push({\n path,\n message: \"Do not combine plainText with content; provide one representation.\",\n });\n }\n\n if (shorthandKeys.length === 0) {\n return;\n }\n\n if (shorthandKeys.length > 1) {\n issues.push({\n path,\n message: \"Provide only richTextBlocks; do not combine it with the blocks alias.\",\n });\n }\n\n const shorthandKey = shorthandKeys[0];\n const shorthand = value[shorthandKey];\n if (!Array.isArray(shorthand)) {\n issues.push({\n path: `${path}.${shorthandKey}`,\n message: `${shorthandKey} must be an array of rich-text blocks.`,\n });\n } else if (shorthand.length === 0) {\n issues.push({\n path: `${path}.${shorthandKey}`,\n message: `${shorthandKey} must contain at least one block. Use an explicit canonical content value when intentionally clearing a surface.`,\n });\n }\n\n if (value.plainText !== undefined || value.content !== undefined) {\n issues.push({\n path,\n message:\n \"Do not combine richTextBlocks with plainText or content; provide one representation.\",\n });\n }\n};\n\n/** Accept unambiguous model-facing shorthand without changing the canonical document grammar. */\nexport const normalizeSurveyChangeOperations = (operations: unknown[], defaultLocale: string) => {\n const issues: SurveyChangeNormalizationIssue[] = [];\n const text = (value: unknown, path: string): unknown => {\n if (!isRecord(value)) return value;\n const candidate = { ...value };\n // Wording aliases never retarget an owner or infer a locale from the wording itself.\n const aliases = [\"text\", \"label\"].filter((key) => Object.hasOwn(candidate, key));\n const explicit = [\"plainText\", \"content\", \"richTextBlocks\", \"blocks\"].some((key) =>\n Object.hasOwn(candidate, key),\n );\n if (aliases.length > 1 || (aliases.length && explicit)) {\n issues.push({\n path,\n message:\n \"Provide one content representation; do not combine text/label with plainText, content or richTextBlocks.\",\n });\n } else if (aliases.length === 1 && typeof candidate[aliases[0]] === \"string\") {\n candidate.plainText = candidate[aliases[0]];\n delete candidate[aliases[0]];\n }\n // A bare string content is the same unformatted wording, not Markdown or rich text.\n if (typeof candidate.content === \"string\" && candidate.plainText === undefined) {\n candidate.plainText = candidate.content;\n delete candidate.content;\n }\n inspectTranslationRepresentations(candidate, path, issues);\n const content = normalizeRichTextContent(\n candidate.content ??\n (Array.isArray(candidate.richTextBlocks) || Array.isArray(candidate.blocks)\n ? candidate\n : undefined),\n `${path}.content`,\n issues,\n );\n const { richTextBlocks: _rich, blocks: _blocks, ...rest } = candidate;\n return {\n ...rest,\n locale: candidate.locale ?? defaultLocale,\n ...(content !== undefined ? { content } : {}),\n };\n };\n const translations = (value: unknown, path: string): unknown => {\n if (Array.isArray(value)) return value.map((entry, index) => text(entry, `${path}.${index}`));\n if (!isRecord(value)) return value;\n const result: unknown[] = [];\n // Mirror the canonical locale/owner/role map. No old dotted content-key interpretation.\n for (const [locale, branch] of Object.entries(value)) {\n if (!isRecord(branch)) {\n issues.push({\n path: `${path}.${locale}`,\n message: \"Expected a map of exact owner IDs and their content roles.\",\n });\n continue;\n }\n const owners = Object.hasOwn(branch, \"content\") ? branch.content : branch;\n if (\n !isRecord(owners) ||\n (Object.hasOwn(branch, \"content\") && Object.keys(branch).length !== 1)\n ) {\n issues.push({\n path: `${path}.${locale}`,\n message:\n \"Use an owner-role content map only; survey-level translations need their own typed operation.\",\n });\n continue;\n }\n for (const [ownerId, roles] of Object.entries(owners)) {\n if (!isRecord(roles)) {\n issues.push({\n path: `${path}.${locale}.${ownerId}`,\n message: \"Expected a map from content roles to translated values.\",\n });\n continue;\n }\n for (const [role, content] of Object.entries(roles)) {\n const leafPath = `${path}.${locale}.${ownerId}.${role}`;\n const leaf =\n typeof content === \"string\"\n ? { plainText: content }\n : content === null\n ? { content: null }\n : isRecord(content) && typeof content.type === \"string\"\n ? { content }\n : content;\n if (!isRecord(leaf)) {\n issues.push({\n path: leafPath,\n message: \"Expected text, canonical content, richTextBlocks, or null to clear.\",\n });\n continue;\n }\n // Map keys are authoritative; do not discard conflicting targeting information.\n if ([\"ownerId\", \"role\", \"locale\"].some((key) => Object.hasOwn(leaf, key))) {\n issues.push({\n path: leafPath,\n message:\n \"Put ownerId, role and locale either in array entries or in map keys, not both.\",\n });\n continue;\n }\n result.push(text({ ...leaf, ownerId, role, locale }, leafPath));\n }\n }\n }\n return result;\n };\n return {\n operations: operations.map((value, index) => {\n if (!isRecord(value)) return value;\n const candidate = { ...value };\n if (typeof candidate.op === \"string\") {\n if (candidate.kind !== undefined && candidate.kind !== candidate.op)\n issues.push({\n path: String(index),\n message: \"Conflicting operation kind and op alias; provide one intended operation.\",\n });\n else {\n candidate.kind = candidate.op;\n delete candidate.op;\n }\n }\n const normalized =\n candidate.kind === \"update-content\" || candidate.kind === \"update-survey-translation\"\n ? text(candidate, String(index))\n : candidate;\n if (isRecord(normalized) && normalized.translations !== undefined)\n normalized.translations = translations(normalized.translations, `${index}.translations`);\n if (isRecord(normalized) && normalized.kind === \"create-item\" && isRecord(normalized.item)) {\n const item = normalized.item;\n // A matching redundant target does not change intent. Never choose between IDs.\n if (Object.hasOwn(normalized, \"itemId\")) {\n if (typeof item.id === \"string\" && normalized.itemId === item.id) {\n delete normalized.itemId;\n } else {\n issues.push({\n path: `${index}.itemId`,\n message:\n \"Conflicting create-item itemId and item.id; use item.id for the new item identity.\",\n });\n }\n }\n // Preserve the model-facing creation-envelope tolerance using only current\n // owner-role translations. Other unknown item/operation fields stay strict.\n if (Object.hasOwn(item, \"translations\")) {\n const nested = translations(item.translations, `${index}.item.translations`);\n const outer = normalized.translations ?? [];\n if (Array.isArray(nested) && Array.isArray(outer)) {\n const combined: unknown[] = [];\n const byTarget = new Map<string, unknown>();\n for (const entry of [...outer, ...nested]) {\n if (\n !isRecord(entry) ||\n ![entry.locale, entry.ownerId, entry.role].every(\n (value) => typeof value === \"string\",\n )\n ) {\n combined.push(entry);\n continue;\n }\n const key = JSON.stringify([entry.locale, entry.ownerId, entry.role]);\n if (byTarget.has(key)) {\n if (stableStringify(byTarget.get(key)) !== stableStringify(entry)) {\n issues.push({\n path: `${index}.item.translations`,\n message: `Conflicting translations for owner \"${entry.ownerId}\", role \"${entry.role}\", locale \"${entry.locale}\"; provide one intended value beside item.`,\n });\n }\n continue;\n }\n byTarget.set(key, entry);\n combined.push(entry);\n }\n const { translations: _nested, ...canonicalItem } = item;\n normalized.item = canonicalItem;\n normalized.translations = combined;\n } else {\n issues.push({\n path: `${index}.item.translations`,\n message:\n \"Creation translations must be an owner-role entry array or locale/owner/role map; put them beside item.\",\n });\n }\n }\n }\n return normalized;\n }),\n issues,\n };\n};\n","// Suggestions are diagnostic only. Callers must still reject an unknown reference;\n// a similar spelling is never authorization to retarget a mutation.\nconst MAX_REFERENCE_LENGTH = 256;\nconst MAX_DISTANCE = 3;\n\nconst spellingDistance = (left: string, right: string): number => {\n if (Math.abs(left.length - right.length) > MAX_DISTANCE) return Infinity;\n let previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n for (let row = 1; row <= left.length; row++) {\n const current = [row];\n for (let column = 1; column <= right.length; column++) {\n current[column] = Math.min(\n current[column - 1] + 1,\n previous[column] + 1,\n previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1),\n );\n }\n if (Math.min(...current) > MAX_DISTANCE) return Infinity;\n previous = current;\n }\n return previous[right.length];\n};\n\nexport const suggestExactReferences = (supplied: string, known: Iterable<string>): string[] => {\n if (supplied.length > MAX_REFERENCE_LENGTH) return [];\n const candidates: Array<{ value: string; distance: number }> = [];\n for (const value of new Set(known)) {\n if (value.length > MAX_REFERENCE_LENGTH || value === supplied) continue;\n // Content namespaces differ between item capabilities. An exact suffix is\n // useful evidence for feedback, but must not silently rewrite the key.\n const distance = supplied.endsWith(`.${value}`) ? 0 : spellingDistance(supplied, value);\n if (distance <= MAX_DISTANCE) candidates.push({ value, distance });\n }\n candidates.sort(\n (left, right) => left.distance - right.distance || left.value.localeCompare(right.value),\n );\n return candidates\n .filter((entry) => entry.distance === candidates[0]?.distance)\n .slice(0, 3)\n .map(({ value }) => value);\n};\n\nexport const formatExactReferenceSuggestions = (\n supplied: string,\n known: Iterable<string>,\n label: string,\n): string => {\n const suggestions = suggestExactReferences(supplied, known);\n return suggestions.length\n ? ` Similar valid ${label}: ${suggestions.map((value) => JSON.stringify(value)).join(\", \")}. Confirm the intended target and copy its exact identifier.`\n : \"\";\n};\n","import { formatExactReferenceSuggestions } from \"./reference-diagnostics\";\nimport { SurveyEditor, getAnswerTypeChangeDiagnostics } from \"@case-framework/survey-core/editor\";\nimport {\n DefinitionError,\n annotatedReferences,\n applyJsonPatch,\n contentOwnerIds,\n inspectAnnotated,\n encodeJsonPointerSegment,\n setOwnValue,\n type CompositionSurvey,\n type Content,\n type JsonPatchOperation,\n type LocalizationRef,\n type Survey,\n} from \"@case-framework/survey-core\";\nimport type { AnswerTypeReservations } from \"@case-framework/survey-core/schema\";\nimport type { SurveyOperation } from \"../protocol/operations\";\nimport type { SurveyAssistantCapabilitySet } from \"./capabilities\";\nimport { createAssistantSurvey } from \"./survey-model\";\n\nconst pointer = (parts: readonly (string | number)[]) =>\n `/${parts.map((part) => encodeJsonPointerSegment(String(part))).join(\"/\")}`;\nconst buildContent = (value: {\n plainText?: string;\n content?: Content | null;\n}): Content | undefined =>\n value.content === null\n ? undefined\n : (value.content ??\n (value.plainText !== undefined ? { type: \"plain\", content: value.plainText } : undefined));\nconst metadata = { label: \"Assistant change\", source: \"assistant\" as const };\n/** Private validation simulation. Accepted results still enter the host's normal editor transaction. */\nexport class SurveyOperationExecutionSession {\n private editor: SurveyEditor;\n private readonly baseline: Survey;\n /** Identities removed while other content still referenced them. */\n private readonly removedDependencies = new Set<string>();\n constructor(\n survey: CompositionSurvey,\n capabilities?: SurveyAssistantCapabilitySet,\n answerTypes?: AnswerTypeReservations,\n ) {\n this.editor = new SurveyEditor(createAssistantSurvey(survey, capabilities), { answerTypes });\n this.baseline = this.model;\n }\n get model() {\n return this.editor.survey;\n }\n getAnswerTypes() {\n return this.editor.getAnswerTypes();\n }\n hasLocale(locale: string) {\n return Object.hasOwn(this.model.data.translations ?? {}, locale);\n }\n private writeContent(\n ref: LocalizationRef,\n value: { locale: string; plainText?: string; content?: Content | null },\n ) {\n if (ref.scope === \"content\") {\n const owner = this.model.owners.get(ref.ownerId);\n if (!owner)\n throw new Error(\n `Unknown content owner \"${ref.ownerId}\".${formatExactReferenceSuggestions(ref.ownerId, this.model.owners.keys(), \"owner IDs\")}`,\n );\n if (!owner.roles.some((role) => role.role === ref.role))\n throw new Error(\n `Unknown content role \"${ref.role}\" on owner \"${ref.ownerId}\".${formatExactReferenceSuggestions(\n ref.role,\n owner.roles.map((role) => role.role),\n \"content roles\",\n )}`,\n );\n }\n this.editor.setLocalizedContent(ref, value.locale, buildContent(value), metadata);\n }\n private translations(values: Extract<SurveyOperation, { kind: \"create-item\" }>[\"translations\"]) {\n for (const entry of values ?? [])\n this.writeContent({ scope: \"content\", ownerId: entry.ownerId, role: entry.role }, entry);\n }\n /**\n * The editor lets people leave broken references to repair later; the assistant never does.\n * Remember what a removal leaves dangling, so repairs may follow later in the same change.\n */\n private recordRemoval(id: string) {\n for (const reference of this.editor.deletionImpact(id))\n this.removedDependencies.add(reference.id);\n }\n /** Reject a change that still leaves references to content it removed. */\n assertNoDanglingRemovals() {\n if (!this.removedDependencies.size) return;\n const survey = this.model;\n const references = annotatedReferences(\n inspectAnnotated(survey.registry.surveySchema, survey.data),\n ).filter(\n (reference) =>\n reference.path[0] !== \"translations\" &&\n this.removedDependencies.has(reference.id) &&\n !survey.identities.has(reference.id),\n );\n if (!references.length) return;\n throw new DefinitionError(\n references.map((reference) => ({\n severity: \"error\",\n code: \"deletion-has-dependencies\",\n path: [...reference.path],\n message: `This reference to ${reference.target} \"${reference.id}\" depends on the content being removed. Update or remove this exact reference in the same change; inspect expression-diagnostics and the owning item for context.`,\n })),\n );\n }\n private patch(patches: JsonPatchOperation[], cleanOwnedContent = false) {\n this.editor.transact(metadata, (draft) => {\n const patched = this.model.registry.surveySchema.parse(applyJsonPatch(draft, patches));\n if (cleanOwnedContent) {\n const remaining = contentOwnerIds(this.model.registry.surveySchema, patched);\n for (const translation of Object.values(patched.translations ?? {}))\n for (const id of this.model.owners.keys())\n if (!remaining.has(id)) delete translation.content[id];\n }\n for (const key of Object.keys(draft)) Reflect.deleteProperty(draft, key);\n Object.assign(draft, patched);\n });\n }\n apply(operation: SurveyOperation): void {\n this.editor.runAction(() => {\n switch (operation.kind) {\n case \"insert-preset\":\n throw new Error(\"Materialize trusted presets before executing a change set\");\n case \"create-item\": {\n const parent = this.model.getItem(operation.target.parentItemId);\n if (parent?.itemType !== \"group\")\n throw new DefinitionError([\n {\n severity: \"error\",\n code: \"target-parent-not-found\",\n path: [],\n message: `The target must be an existing group. Current group IDs: ${this.model.data.surveyItems\n .filter((item) => item.itemType === \"group\")\n .map((item) => JSON.stringify(item.id))\n .join(\", \")}.`,\n },\n ]);\n if (\n operation.target.index !== undefined &&\n operation.target.index > parent.config.items.length\n )\n throw new Error(\"Insertion index exceeds the current sibling count\");\n this.editor.addItem(\n { parentId: parent.id, index: operation.target.index },\n operation.item,\n );\n this.translations(operation.translations);\n break;\n }\n case \"insert-element\": {\n const path = this.model.identities.get(operation.target.layoutId)?.path.slice(0, -1);\n if (!path || this.model.identities.get(operation.target.layoutId)?.kind !== \"layout\")\n throw new Error(\"Unknown layout target\");\n const elements = this.model.elements;\n const length = [...elements.values()].filter(\n (element) =>\n element.path.length === path.length + 2 &&\n path.every((part, index) => element.path[index] === part),\n ).length;\n if (operation.target.index !== undefined && operation.target.index > length)\n throw new Error(\"Insertion index exceeds the layout child count\");\n this.editor.insertElement(operation.element, operation.target, metadata);\n this.translations(operation.translations);\n break;\n }\n case \"insert-blocks\": {\n const body = this.model.bodies.get(operation.bodyOwnerId);\n if (!body) throw new Error(\"Unknown body owner\");\n const position = operation.index;\n // JSON Patch rejects indices beyond the end and retains each inserted block's ID.\n this.patch(\n operation.body.blocks.map((block, index) => ({\n op: \"add\",\n path: `${pointer(body.path)}/blocks/${position === undefined ? \"-\" : position + index}`,\n value: block,\n })),\n false,\n );\n this.translations(operation.translations);\n break;\n }\n case \"update-content\":\n this.writeContent(operation.ref, operation);\n break;\n case \"update-survey-translation\":\n this.writeContent(\n { scope: \"survey\", surface: operation.surface, contentKey: operation.contentKey },\n operation,\n );\n break;\n case \"patch-element-config\": {\n const element = this.model.elements.get(operation.elementId);\n if (!element)\n throw new Error(\n `Unknown element \"${operation.elementId}\".${formatExactReferenceSuggestions(operation.elementId, this.model.elements.keys(), \"element IDs\")}`,\n );\n this.editor.updateElement(\n operation.elementId,\n (node) => {\n const config = applyJsonPatch(node.config, operation.patches);\n node.config = this.model.registry\n .get(node.elementType)\n .schema.parse({ ...node, config }).config;\n },\n metadata,\n );\n this.translations(operation.translations);\n break;\n }\n case \"patch-item-config\": {\n const owner = this.model.owners.get(operation.itemId);\n if (!this.model.getItem(operation.itemId) || !owner)\n throw new Error(\n `Unknown item \"${operation.itemId}\". Inspect current item IDs before editing.`,\n );\n const root = `${pointer(owner.path)}/config`;\n this.patch(\n operation.patches.map((patch) => ({\n ...patch,\n path: root + patch.path,\n ...(\"from\" in patch ? { from: root + patch.from } : {}),\n })),\n true,\n );\n this.translations(operation.translations);\n break;\n }\n case \"update-item-label\":\n case \"update-item-color\": {\n if (!this.model.getItem(operation.itemId))\n throw new Error(\n `Unknown item \"${operation.itemId}\". Inspect current item IDs before editing.`,\n );\n this.editor.transact(metadata, (draft) => {\n const item = draft.surveyItems.find((item) => item.id === operation.itemId)!;\n item.metadata = {\n ...item.metadata,\n ...(operation.kind === \"update-item-label\"\n ? { itemLabel: operation.itemLabel }\n : { editorItemColor: operation.color }),\n };\n });\n break;\n }\n case \"remove-item\": {\n const item = this.model.getItem(operation.itemId);\n if (!item)\n throw new Error(\n `Unknown item \"${operation.itemId}\". Inspect current item IDs before editing.`,\n );\n if (item.itemType === \"group\" && item.config.items.length && !operation.includeChildren)\n throw new Error(\"Set includeChildren to remove a group and its descendants\");\n this.recordRemoval(item.id);\n this.editor.removeItem(item.id);\n break;\n }\n case \"remove-content\":\n this.recordRemoval(operation.ownerId);\n this.editor.remove(operation.ownerId);\n break;\n case \"move-item\":\n this.editor.moveItem(\n operation.itemId,\n { parentId: operation.target.parentItemId, index: operation.target.index },\n metadata,\n );\n break;\n case \"reorder-items\": {\n const parent = this.model.getItem(operation.parentItemId);\n if (parent?.itemType !== \"group\") throw new Error(\"Unknown parent group\");\n if (\n operation.itemIds.length !== parent.config.items.length ||\n new Set(operation.itemIds).size !== parent.config.items.length ||\n operation.itemIds.some((id) => !parent.config.items.includes(id))\n )\n throw new Error(\"Supply every existing direct child exactly once\");\n this.editor.transact(metadata, (draft) => {\n const item = draft.surveyItems.find((item) => item.id === parent.id)!;\n if (item.itemType === \"group\") item.config.items = [...operation.itemIds];\n });\n break;\n }\n case \"move-element\":\n this.editor.moveElement(\n operation.elementId,\n operation.target.layoutId,\n operation.target.index,\n operation.ruleTransfer,\n );\n break;\n case \"move-block\":\n this.editor.moveBlock(\n operation.blockId,\n operation.bodyOwnerId,\n operation.index,\n operation.ruleTransfer,\n );\n break;\n case \"update-layout\":\n this.editor.updateLayout(operation.layoutId, operation.layout);\n break;\n case \"update-response-settings\":\n this.editor.updateResponseSettings(operation.naming, operation.settings);\n break;\n case \"add-survey-locale\":\n if (!this.editor.addLocale(operation.locale))\n throw new DefinitionError([\n {\n severity: \"error\",\n code: \"survey-locale-already-exists\",\n path: [\"translations\", operation.locale],\n message: \"The survey locale already exists\",\n },\n ]);\n break;\n case \"remove-survey-locale\":\n if (!this.editor.removeLocale(operation.locale))\n throw new DefinitionError([\n {\n severity: \"error\",\n code: \"survey-locale-not-found\",\n path: [\"translations\", operation.locale],\n message: \"Unknown survey locale\",\n },\n ]);\n break;\n case \"update-survey-metadata\":\n this.editor.transact(metadata, (draft) => {\n draft.metadata ??= {};\n for (const [key, value] of Object.entries(operation.values)) {\n if (value === null) delete draft.metadata[key];\n else setOwnValue(draft.metadata, key, value);\n }\n });\n break;\n case \"update-survey-pagination\":\n this.editor.updateMaxItemsPerPage(operation.value ?? undefined);\n break;\n case \"set-image-asset\":\n this.editor.setAsset(operation.assetId, operation.asset);\n break;\n case \"update-image-asset-metadata\": {\n const asset = this.model.getAsset(operation.assetId);\n if (!asset) throw new Error(\"Unknown image asset\");\n const next = structuredClone(asset);\n next.metadata ??= {};\n for (const [key, value] of Object.entries(operation.metadata)) {\n if (value === null) Reflect.deleteProperty(next.metadata, key);\n else if (value !== undefined) setOwnValue(next.metadata, key, value);\n }\n this.editor.setAsset(operation.assetId, next);\n break;\n }\n case \"remove-image-asset\": {\n if (!this.model.hasAsset(operation.assetId)) throw new Error(\"Unknown image asset\");\n if (this.model.getAssetUsages(operation.assetId).length)\n throw new DefinitionError([\n {\n severity: \"error\",\n code: \"image-asset-still-referenced\",\n path: [\"assets\", operation.assetId],\n message: \"Remove image placements before deleting this asset\",\n },\n ]);\n this.editor.removeAsset(operation.assetId);\n break;\n }\n case \"update-placed-image\": {\n const content = this.editor.getLocalizedContent(operation.ref, operation.locale);\n if (content?.type !== \"richText\") throw new Error(\"Image placement is not rich text\");\n const next = structuredClone(content),\n images = next.doc.blocks.filter((block) => block.type === \"image\");\n const image = images[operation.imageIndex];\n if (!image) throw new Error(\"Unknown image placement\");\n if (\n operation.expectedAssetId &&\n (image.source.type !== \"asset\" || image.source.assetId !== operation.expectedAssetId)\n )\n throw new DefinitionError([\n {\n severity: \"error\",\n code: \"placed-image-asset-mismatch\",\n path: [\"imageIndex\"],\n message: \"Image placement changed; inspect it again\",\n },\n ]);\n const changes = operation.changes;\n if (changes.source) image.source = changes.source;\n if (changes.alt === null) delete image.alt;\n else if (changes.alt !== undefined) image.alt = changes.alt;\n if (changes.caption !== undefined) {\n if (!changes.caption) delete image.caption;\n else\n image.caption = [\n { type: \"paragraph\", children: [{ type: \"text\", text: changes.caption }] },\n ];\n }\n const size = { ...image.size };\n for (const key of [\"width\", \"height\", \"maxWidth\", \"maxHeight\"] as const) {\n if (changes[key] === null) delete size[key];\n else if (changes[key] !== undefined) size[key] = changes[key];\n }\n if (Object.keys(size).length) image.size = size;\n else delete image.size;\n if (changes.alignment === null) delete image.alignment;\n else if (changes.alignment) image.alignment = changes.alignment;\n this.editor.setLocalizedContent(operation.ref, operation.locale, next, metadata);\n break;\n }\n case \"survey-json-patch\":\n this.patch(operation.patches);\n break;\n default: {\n const exhaustive: never = operation;\n throw new Error(`Unknown operation ${String(exhaustive)}`);\n }\n }\n const diagnostics = getAnswerTypeChangeDiagnostics(this.baseline, this.model);\n if (diagnostics.length) throw new DefinitionError(diagnostics);\n });\n }\n serialize(): CompositionSurvey {\n return this.model.serialize();\n }\n}\nexport const executeSurveyOperationsOnRawSurvey = ({\n operations,\n survey,\n capabilities,\n answerTypes,\n}: {\n operations: SurveyOperation[];\n survey: CompositionSurvey;\n capabilities?: SurveyAssistantCapabilitySet;\n answerTypes?: AnswerTypeReservations;\n}): CompositionSurvey => {\n const session = new SurveyOperationExecutionSession(survey, capabilities, answerTypes);\n for (const operation of operations) session.apply(operation);\n session.assertNoDanglingRemovals();\n return session.serialize();\n};\n","import {\n getLocalizationEntryKey,\n hasLocalizationText,\n isContentEmpty,\n readLocalizationContent,\n resolveElementName,\n type LocalizationRef,\n type Survey,\n} from \"@case-framework/survey-core\";\nimport type { SurveyValidationIssue } from \"../protocol\";\n\ntype Requirement = {\n elementId: string;\n itemId: string;\n ref?: Extract<LocalizationRef, { scope: \"content\" }>;\n renderable?: boolean;\n};\n\nfunction requirements(survey: Survey) {\n const result = new Map<string, Requirement>();\n for (const { node, itemId, facts } of survey.elements.values()) {\n const add = (ownerId: string, role: string, renderable = false) => {\n const ref = { scope: \"content\" as const, ownerId, role };\n result.set(getLocalizationEntryKey(ref), { elementId: node.id, itemId, ref, renderable });\n };\n if (node.elementType === \"information\" || node.elementType === \"consent\")\n add(node.id, \"body\", true);\n for (const binding of facts.bindings) {\n if (binding.labelRefs) {\n for (const ref of binding.labelRefs) add(ref.ownerId, ref.role);\n } else {\n result.set(JSON.stringify([\"element-name\", node.id]), { elementId: node.id, itemId });\n }\n for (const id of binding.selection?.options ?? [])\n if (survey.owners.get(id)?.roles.some((role) => role.role === \"label\")) add(id, \"label\");\n }\n }\n return result;\n}\n\n/** Changes to existing inputs must not introduce unnamed components or erase naming content.\n * New elements may be blank presets awaiting later authoring; they retain normal warnings.\n * Presence in any actual language counts, separately from translation completeness.\n */\nexport function getIntroducedMissingAuthoringContent(\n before: Survey,\n after: Survey,\n): SurveyValidationIssue[] {\n const previous = requirements(before);\n // Removing an entire locale is an explicit lifecycle operation, not a wording edit.\n const locales = after.locales;\n const present = (survey: Survey, requirement: Requirement) =>\n requirement.ref\n ? locales.some((locale) => {\n const content = readLocalizationContent(survey, requirement.ref!, locale);\n return requirement.renderable ? !isContentEmpty(content) : hasLocalizationText(content);\n })\n : Boolean(resolveElementName(survey, requirement.elementId, locales));\n const issues: SurveyValidationIssue[] = [];\n for (const [key, requirement] of requirements(after)) {\n if (present(after, requirement)) continue;\n const prior = previous.get(key);\n if (prior ? !present(before, prior) : !before.elements.has(requirement.elementId)) continue;\n if (!requirement.ref && prior) {\n const name = resolveElementName(before, requirement.elementId, locales);\n if (\n name &&\n locales.some((locale) =>\n hasLocalizationText(\n readLocalizationContent(\n after,\n { scope: \"content\", ownerId: name.ownerId, role: name.role },\n locale,\n ),\n ),\n )\n )\n continue;\n // A still-authored title becoming ambiguous is an authoring warning, not content loss.\n }\n issues.push({\n severity: \"error\",\n code: \"missing-authoring-content\",\n itemId: requirement.itemId,\n message: requirement.ref\n ? `Provide non-empty localized content for owner \"${requirement.ref.ownerId}\" role \"${requirement.ref.role}\" in the same proposal. Preserve previously authored content unless its control is also removed.`\n : `Element \"${requirement.elementId}\" needs a localized label or an unambiguous enclosing title in the same proposal. Preserve its previously authored naming content.`,\n });\n }\n return issues;\n}\n","import { SurveyEditor } from \"@case-framework/survey-core/editor\";\nimport { z } from \"zod\";\nimport { JsonPatchError } from \"@case-framework/survey-core\";\nimport { elementTransportSchema } from \"../protocol/structure\";\nimport {\n SurveyStateGraph,\n DefinitionError,\n readLocalizationContent,\n parseJsonPointer,\n generateId,\n ownValue,\n type Survey,\n} from \"@case-framework/survey-core\";\nimport {\n surveyOperationSchema,\n type SurveyOperation,\n type SurveyValidationIssue,\n type SurveyValidationResult,\n} from \"../protocol/operations\";\nimport {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n type SurveyDocumentSnapshot,\n type SurveyDocumentVersion,\n} from \"../protocol/document\";\nimport type { SurveyChangeSet } from \"../protocol/lifecycle\";\nimport { stableStringify } from \"../protocol/digest\";\nimport { createSurveyAssistantEngineContext, type SurveyAssistantEngineContext } from \"./context\";\nimport {\n assertSurveyAssistantCapabilities,\n type SurveyAssistantCapabilitySet,\n} from \"./capabilities\";\nimport { defaultSurveyAssistantCapabilitySet } from \"../capabilities/default\";\nimport { SurveyOperationExecutionSession } from \"./operation-execution\";\nimport { validateExpression } from \"./expression-validation\";\nimport { getDefaultProjectionIssues } from \"@case-framework/survey-core\";\nimport { getIntroducedMissingAuthoringContent } from \"./authoring-content\";\nimport { getDiagnosticLocation, getIntroducedDefinitionIssues } from \"./definition-diagnostics\";\nexport { executeSurveyOperationsOnRawSurvey } from \"./operation-execution\";\n\nexport const MAX_SURVEY_ASSISTANT_OPERATIONS_PER_PROPOSAL = 200;\nexport const MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT = 1_000;\nexport const buildSurveyDocumentVersion = (\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot,\n): SurveyDocumentVersion => ({ ...snapshot.version });\n\nfunction materialize(\n operation: SurveyOperation,\n model: Survey,\n caps: SurveyAssistantCapabilitySet,\n): SurveyOperation {\n if (operation.kind !== \"insert-preset\") return operation;\n const capability = caps.byElementType.get(operation.elementType);\n if (\n capability?.manifest.create !== \"deterministic\" ||\n !capability.manifest.creationPresets?.some((preset) => preset.id === operation.presetId) ||\n !capability.materializePreset\n )\n throw new Error(\"This preset is not available from the trusted registry\");\n if (capability.supportsOperation && !capability.supportsOperation(operation))\n throw new Error(\"The host does not permit this preset operation\");\n const created = capability.materializePreset(\n operation.presetId,\n operation.locale,\n new Set(model.slots.definitions.map((slot) => slot.variableName)),\n );\n if (created.element.elementType !== operation.elementType)\n throw new Error(\"Preset returned the wrong element type\");\n for (const ownerId of Object.keys(created.content ?? {}))\n if (model.owners.has(ownerId))\n throw new Error(`Initial localized owner '${ownerId}' already exists`);\n const translations = Object.entries(created.content ?? {}).flatMap(([ownerId, roles]) =>\n Object.entries(roles).map(([role, content]) => ({\n ownerId,\n role,\n locale: operation.locale,\n content,\n })),\n );\n if (\"layoutId\" in operation.target)\n return {\n kind: \"insert-element\",\n id: operation.id,\n target: operation.target,\n element: elementTransportSchema.parse(created.element),\n translations,\n };\n // Freeze the command's result into ordinary proposal operations, so apply/replay\n // preserves its IDs and translations without running the preset factory again.\n const editor = new SurveyEditor(model);\n const { itemId } = editor.insertElement(\n elementTransportSchema.parse(created.element),\n { parentId: operation.target.parentItemId, index: operation.target.index },\n { label: \"Assistant preset\", source: \"assistant\" },\n created.content ? { locale: operation.locale, content: created.content } : undefined,\n );\n return surveyOperationSchema.parse({\n kind: \"create-item\",\n id: operation.id,\n target: operation.target,\n item: editor.survey.getItem(itemId),\n translations,\n });\n}\nfunction elementContext(model: Survey, id: string) {\n const entry = model.elements.get(id);\n if (!entry) return undefined;\n const ancestors = [];\n let owner = model.owners.get(id);\n while (owner) {\n ancestors.push({ id: owner.id, disabled: owner.disabled, visibility: owner.visibility });\n owner = owner.parentId ? model.owners.get(owner.parentId) : undefined;\n }\n const owners = new Set(\n [...model.owners.values()].filter((owner) => owner.elementId === id).map((owner) => owner.id),\n );\n for (const ancestor of ancestors) owners.add(ancestor.id);\n return {\n node: entry.node,\n itemId: entry.itemId,\n ancestors,\n content: Object.fromEntries(\n Object.entries(model.data.translations ?? {}).map(([locale, translation]) => [\n locale,\n Object.fromEntries(\n Object.entries(translation.content).filter(([ownerId]) => owners.has(ownerId)),\n ),\n ]),\n ),\n };\n}\nfunction requireCapabilities(\n operation: SurveyOperation,\n before: Survey,\n after: Survey,\n caps: SurveyAssistantCapabilitySet,\n) {\n // These host-owned operations cannot edit an element definition or its content roles.\n if (\n [\n \"add-survey-locale\",\n \"remove-survey-locale\",\n \"update-survey-metadata\",\n \"update-survey-pagination\",\n \"update-survey-translation\",\n \"set-image-asset\",\n \"update-image-asset-metadata\",\n \"remove-image-asset\",\n \"update-item-label\",\n \"update-item-color\",\n ].includes(operation.kind)\n )\n return;\n const direct = new Set<string>();\n if (\"elementId\" in operation) direct.add(operation.elementId);\n if (operation.kind === \"update-layout\") {\n const path = before.identities.get(operation.layoutId)?.path.slice(0, -1);\n if (path)\n for (const entry of before.elements.values())\n if (path.every((part, index) => entry.path[index] === part)) direct.add(entry.node.id);\n }\n if (operation.kind === \"reorder-items\" || operation.kind === \"move-item\") {\n const affected = operation.kind === \"move-item\" ? [operation.itemId] : operation.itemIds;\n for (const entry of before.elements.values())\n if (affected.includes(entry.itemId)) direct.add(entry.node.id);\n }\n if (operation.kind === \"survey-json-patch\" || operation.kind === \"patch-item-config\") {\n for (const [id, entry] of before.elements)\n if (stableStringify(entry.path) !== stableStringify(after.elements.get(id)?.path))\n direct.add(id);\n }\n if (\"blockId\" in operation || \"ownerId\" in operation) {\n const id = \"blockId\" in operation ? operation.blockId : operation.ownerId;\n const path = before.identities.get(id)?.path.slice(0, -1);\n if (path)\n for (const element of before.elements.values())\n if (path.every((part, index) => element.path[index] === part)) direct.add(element.node.id);\n }\n for (const id of new Set([...before.elements.keys(), ...after.elements.keys()])) {\n if (\n !direct.has(id) &&\n stableStringify(elementContext(before, id)) === stableStringify(elementContext(after, id))\n )\n continue;\n const previous = before.elements.get(id);\n const next = after.elements.get(id);\n const entry = next ?? previous!;\n const changesType =\n previous !== undefined &&\n next !== undefined &&\n previous.node.elementType !== next.node.elementType;\n if (changesType) {\n const sourceCapability = caps.byElementType.get(previous.node.elementType);\n if (\n !sourceCapability?.manifest.supportedOperations.includes(operation.kind) ||\n (sourceCapability.supportsOperation && !sourceCapability.supportsOperation(operation))\n )\n throw new Error(\n `Element '${previous.node.elementType}' does not permit '${operation.kind}' through the assistant`,\n );\n }\n const capability = caps.byElementType.get(entry.node.elementType);\n if (\n !capability?.manifest.supportedOperations.includes(operation.kind) ||\n (capability.supportsOperation && !capability.supportsOperation(operation))\n )\n throw new Error(\n `Element '${entry.node.elementType}' does not permit '${operation.kind}' through the assistant`,\n );\n if ((!previous || changesType) && capability.manifest.create !== \"deterministic\")\n throw new Error(`Element '${entry.node.elementType}' is not deterministically creatable`);\n if (!next || !capability.validateElement) continue;\n const existingErrors = new Map<string, number>();\n if (previous?.node.elementType === next.node.elementType)\n for (const issue of capability.validateElement(previous.node)) {\n if (issue.severity !== \"error\") continue;\n const key = stableStringify(issue);\n existingErrors.set(key, (existingErrors.get(key) ?? 0) + 1);\n }\n // Capability policy above still governs deletion/moves. Validation describes\n // the remaining element: unchanged unfinished configuration must stay editable.\n const errors = capability.validateElement(next.node).filter((issue) => {\n if (issue.severity !== \"error\") return false;\n const key = stableStringify(issue);\n const count = existingErrors.get(key) ?? 0;\n if (!count) return true;\n existingErrors.set(key, count - 1);\n return false;\n });\n if (errors.length) throw new Error(errors.map((issue) => issue.message).join(\"\\n\"));\n }\n}\n/** Preserve sibling wording when a model uses the low-level escape hatch. */\nfunction validateTranslationPatchSafety(\n operation: Extract<SurveyOperation, { kind: \"survey-json-patch\" }>,\n model: Survey,\n) {\n for (const patch of operation.patches) {\n if (patch.op === \"test\") continue;\n for (const path of patch.op === \"move\" ? [patch.path, patch.from] : [patch.path]) {\n const segments = parseJsonPointer(path);\n if (segments[0] !== \"translations\") continue;\n let current: unknown = model.data;\n for (const segment of segments)\n current =\n current && typeof current === \"object\"\n ? ownValue(current as Record<string, unknown>, segment)\n : undefined;\n const container =\n segments.length <= 2 ||\n segments.length === 3 ||\n (segments[2] === \"content\" && segments.length === 4);\n if (container && (segments.length === 1 || current !== undefined))\n throw new Error(\n \"Raw patches cannot replace or remove a translation container. Use update-content for an owner/role leaf or the typed locale operations.\",\n );\n }\n }\n}\nconst expressionsKey = (model: Survey) =>\n stableStringify(\n model.expressions.map((entry) => ({ path: entry.path, expression: entry.expression })),\n );\nexport function validateSurveyOperations({\n allowExpressionJsonPatches = false,\n scope = \"proposal\",\n maxOperations = MAX_SURVEY_ASSISTANT_OPERATIONS_PER_PROPOSAL,\n operations,\n snapshot: input,\n}: {\n allowExpressionJsonPatches?: boolean;\n /** A completed turn combines individually validated proposals, including raw patches. */\n scope?: \"proposal\" | \"turn\";\n maxOperations?: number;\n operations: SurveyOperation[];\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot | undefined;\n}): SurveyValidationResult {\n const issues: SurveyValidationIssue[] = [],\n warnings: SurveyValidationIssue[] = [],\n normalizedOperations: SurveyOperation[] = [];\n const fail = (code: string, message: string, operationIndex?: number) =>\n issues.push({ severity: \"error\", code, message, operationIndex });\n if (!input) {\n fail(\"missing-snapshot\", \"No live editor snapshot was provided\");\n return { valid: false, issues, warnings, normalizedOperations };\n }\n if (!operations.length || operations.length > maxOperations) {\n fail(\n operations.length ? \"too-many-operations\" : \"empty-operations\",\n `Provide 1-${maxOperations} operations`,\n );\n return { valid: false, issues, warnings, normalizedOperations };\n }\n try {\n const caps =\n (\"model\" in input ? input.trustedCapabilities : undefined) ??\n defaultSurveyAssistantCapabilitySet;\n const snapshot = \"model\" in input ? input : createSurveyAssistantEngineContext(input, caps);\n assertSurveyAssistantCapabilities({\n manifest: snapshot.capabilities,\n trustedCapabilities: caps,\n versionDigest: snapshot.version.capabilityDigest,\n });\n const session = new SurveyOperationExecutionSession(\n snapshot.survey,\n caps,\n snapshot.document.answerTypes,\n );\n for (const [operationIndex, unparsed] of operations.entries()) {\n try {\n const operation = materialize(surveyOperationSchema.parse(unparsed), session.model, caps);\n if (operation.kind === \"survey-json-patch\") {\n validateTranslationPatchSafety(operation, session.model);\n if (scope === \"proposal\" && operations.length !== 1) {\n fail(\n \"raw-patch-must-be-single-operation\",\n \"Put all raw patches in one operation\",\n operationIndex,\n );\n break;\n }\n if (\n operation.patches.some((patch) =>\n [patch.path, ...(\"from\" in patch ? [patch.from] : [])].some(\n (path) => path === \"\" || /^\\/(\\$schema|schemaVersion)(\\/|$)/.test(path),\n ),\n )\n ) {\n fail(\n \"survey-schema-is-immutable\",\n \"Raw patches cannot replace the document root or its schema identity\",\n operationIndex,\n );\n break;\n }\n }\n const before = session.model;\n session.apply(operation);\n const after = session.model;\n if (operation.kind === \"update-item-label\" || operation.kind === \"update-item-color\") {\n const key = operation.kind === \"update-item-label\" ? \"itemLabel\" : \"editorItemColor\";\n const previous = before.data.surveyItems.find((item) => item.id === operation.itemId)\n ?.metadata?.[key];\n const current = after.data.surveyItems.find((item) => item.id === operation.itemId)\n ?.metadata?.[key];\n if (previous === current)\n warnings.push({\n severity: \"warning\",\n code: key === \"itemLabel\" ? \"no-label-change\" : \"no-color-change\",\n operationIndex,\n itemId: operation.itemId,\n message: \"The editor metadata already has this value.\",\n });\n }\n if (operation.kind === \"add-survey-locale\")\n warnings.push({\n severity: \"warning\",\n code: \"empty-locale-registration\",\n operationIndex,\n message:\n \"Registering an empty locale does not complete a request to localize or translate the survey. Add the requested localized content as well.\",\n });\n if (operation.kind === \"update-content\" || operation.kind === \"update-survey-translation\") {\n const ref =\n operation.kind === \"update-content\"\n ? operation.ref\n : {\n scope: \"survey\" as const,\n surface: operation.surface,\n contentKey: operation.contentKey,\n };\n if (\n stableStringify(readLocalizationContent(before, ref, operation.locale)) ===\n stableStringify(readLocalizationContent(after, ref, operation.locale))\n )\n warnings.push({\n severity: \"warning\",\n code: \"no-content-change\",\n operationIndex,\n itemId: ref.scope === \"content\" ? after.owners.get(ref.ownerId)?.itemId : undefined,\n message: \"The localized content already has this value.\",\n });\n }\n if (\n !allowExpressionJsonPatches &&\n (operation.kind === \"survey-json-patch\" ||\n operation.kind === \"patch-element-config\" ||\n operation.kind === \"patch-item-config\") &&\n expressionsKey(before) !== expressionsKey(after)\n ) {\n fail(\n \"expression-patch-requires-specialized-tool\",\n \"Use survey_expression for condition, validation, prefill and template expression changes\",\n operationIndex,\n );\n break;\n }\n requireCapabilities(operation, before, after, caps);\n if (operation.kind !== \"add-survey-locale\") {\n for (const locale of Object.keys(after.data.translations ?? {})) {\n if (Object.hasOwn(before.data.translations ?? {}, locale)) continue;\n warnings.push({\n severity: \"warning\",\n code: \"introduced-locale\",\n operationIndex,\n operationId: operation.id,\n message: `Locale \"${locale}\" is not currently present and will be introduced by this translation change. Confirm that this is the intended locale code.`,\n });\n }\n }\n const oldExpressions = new Set(\n before.expressions.map((entry) =>\n stableStringify([getDiagnosticLocation(before, entry.path), entry.expression]),\n ),\n );\n for (const entry of after.expressions)\n if (\n !oldExpressions.has(\n stableStringify([getDiagnosticLocation(after, entry.path), entry.expression]),\n )\n )\n validateExpression({\n expression: entry.expression,\n expectedReturnType:\n [\"visibility\", \"disabled\", \"when\"].includes(String(entry.path.at(-1))) ||\n (entry.path.at(-1) === \"expression\" && entry.path.includes(\"validationRules\"))\n ? \"boolean\"\n : undefined,\n issues,\n operationIndex,\n responseSlotTypes: Object.fromEntries(\n after.slots.definitions.map((slot) => [slot.slotId, slot.valueType]),\n ),\n stateTargets: new Set(after.owners.keys()),\n scope: JSON.stringify(entry.path),\n });\n if (issues.length) break;\n normalizedOperations.push(operation);\n } catch (error) {\n if (error instanceof DefinitionError)\n issues.push(\n ...error.diagnostics\n .filter((issue) => issue.severity === \"error\")\n .map((issue) => ({\n severity: \"error\" as const,\n code: issue.code,\n message: `${JSON.stringify(issue.path)}: ${issue.message}`,\n operationIndex,\n })),\n );\n else if (error instanceof JsonPatchError) {\n const patch =\n \"patches\" in unparsed ? unparsed.patches[error.operationIndex ?? 0] : undefined;\n const location = patch\n ? `${unparsed.kind === \"survey-json-patch\" ? \"Survey\" : \"Config\"} patch ${(error.operationIndex ?? 0) + 1} (${patch.op} ${patch.path}): `\n : \"\";\n const hint =\n error.code === \"path-not-found\" && patch?.op === \"replace\"\n ? \" Use add for a new property; replace requires an existing property.\"\n : \"\";\n fail(error.code, `${location}${error.message}${hint}`, operationIndex);\n } else if (error instanceof z.ZodError)\n fail(\n \"invalid-operation\",\n error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\"\\n\"),\n operationIndex,\n );\n else\n fail(\n \"invalid-operation\",\n error instanceof Error ? error.message : String(error),\n operationIndex,\n );\n break;\n }\n }\n if (!issues.length)\n try {\n session.assertNoDanglingRemovals();\n } catch (error) {\n if (!(error instanceof DefinitionError)) throw error;\n issues.push(\n ...error.diagnostics.map((issue) => ({\n severity: \"error\" as const,\n code: issue.code,\n message: `${JSON.stringify(issue.path)}: ${issue.message}`,\n })),\n );\n }\n if (!issues.length) {\n issues.push(...getIntroducedMissingAuthoringContent(snapshot.model, session.model));\n new SurveyStateGraph(session.model, { admission: \"draft\" });\n const existingExports = new Set(getDefaultProjectionIssues(snapshot.model));\n for (const message of getDefaultProjectionIssues(session.model))\n if (!existingExports.has(message)) fail(\"invalid-response-export\", message);\n for (const issue of getIntroducedDefinitionIssues(\n snapshot.model,\n session.model,\n snapshot.ui.selectedLocale,\n )) {\n if (issue.severity === \"error\") issues.push(issue);\n else warnings.push(issue);\n }\n }\n } catch (error) {\n fail(\"invalid-survey-definition\", error instanceof Error ? error.message : String(error));\n }\n return { valid: issues.length === 0, issues, warnings, normalizedOperations };\n}\nexport const createSurveyChangeSet = ({\n allowExpressionJsonPatches,\n maxOperations,\n operations,\n snapshot,\n summary,\n turnId,\n}: {\n allowExpressionJsonPatches?: boolean;\n maxOperations?: number;\n operations: SurveyOperation[];\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot | undefined;\n summary: string;\n turnId: string;\n}): SurveyChangeSet => {\n const validation = validateSurveyOperations({\n allowExpressionJsonPatches,\n maxOperations,\n operations,\n snapshot,\n });\n return {\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n id: generateId(),\n turnId,\n status: validation.valid ? \"validated\" : \"rejected\",\n summary: summary.trim(),\n operations: validation.normalizedOperations,\n precondition: snapshot ? buildSurveyDocumentVersion(snapshot) : undefined,\n validation,\n createdAt: new Date().toISOString(),\n };\n};\n","import { surveyContentSchema, type Content, type FlowItem } from \"@case-framework/survey-core\";\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nexport const getTrimmedString = (value: unknown) =>\n typeof value === \"string\" && value.trim() ? value.trim() : undefined;\nexport const isContent = (value: unknown): value is Content =>\n surveyContentSchema.safeParse(value).success;\nexport const getGroupChildren = (item: FlowItem | undefined): string[] =>\n item?.itemType === \"group\" ? item.config.items : [];\nexport const isRootItem = (item: FlowItem | undefined) =>\n item?.itemType === \"group\" && item.config.isRoot === true;\n","import { getAssistantResponseSchemaIssues } from \"./survey-model\";\nimport {\n getContentPlainText,\n listLocalizationEntries,\n hasLocalizationText,\n getDefinitionDiagnostics,\n resolveElementName,\n readLocalizationContent,\n ownValue,\n setOwnValue,\n type LocalizationRef,\n type SchemaPath,\n} from \"@case-framework/survey-core\";\nimport type { SurveyAssistantEngineContext } from \"./context\";\nimport { getSurveyAssistantExpressionDiagnosticGuidance } from \"./expression-reference-integrity\";\n\nexport type SurveyAuditSeverity = \"error\" | \"warning\" | \"info\";\nexport type SurveyAuditCategory =\n | \"structure\"\n | \"content\"\n | \"localization\"\n | \"logic\"\n | \"responses\"\n | \"assets\"\n | \"quality\";\n\nexport interface SurveyAuditFinding {\n code: string;\n severity: SurveyAuditSeverity;\n category: SurveyAuditCategory;\n message: string;\n itemId?: string;\n locale?: string;\n localizationRefs?: LocalizationRef[];\n path?: SchemaPath;\n suggestion?: string;\n}\n\nexport interface SurveyQualityReviewPrinciple {\n id: string;\n title: string;\n prompt: string;\n}\n\nexport interface SurveyAuditKeyReviewEntry {\n kind: \"response-variable\" | \"choice-option\";\n slotId: string;\n valueType?: string;\n computed?: boolean;\n itemId: string;\n itemKey: string;\n key: string;\n keySource: \"explicit\" | \"fallback-id\";\n localizationRefs?: LocalizationRef[];\n path?: SchemaPath;\n content?: string;\n}\n\nexport interface SurveyAuditReport {\n summary: Record<SurveyAuditSeverity, number> & { total: number };\n findingCount: number;\n truncated: boolean;\n metrics: {\n itemCount: number;\n localeCount: number;\n responseSlotCount: number;\n assetCount: number;\n itemTypes: Record<string, number>;\n elementTypes: Record<string, number>;\n };\n findings: SurveyAuditFinding[];\n qualityReviewPrinciples: SurveyQualityReviewPrinciple[];\n keyReview: {\n sourceLocale?: string;\n entryCount: number;\n offset: number;\n returnedEntryCount: number;\n truncated: boolean;\n entries: SurveyAuditKeyReviewEntry[];\n note: string;\n };\n note: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst QUALITY_PRINCIPLES: SurveyQualityReviewPrinciple[] = [\n {\n id: \"purpose-alignment\",\n title: \"Purpose and construct alignment\",\n prompt:\n \"Does every question serve a stated objective, and does it measure the intended construct?\",\n },\n {\n id: \"cognitive-burden\",\n title: \"Respondent burden\",\n prompt: \"Is the survey as short and cognitively simple as its purpose allows?\",\n },\n {\n id: \"question-wording\",\n title: \"Clear, neutral wording\",\n prompt:\n \"Are questions specific, neutral, answerable, and limited to one idea without assumptions or double negatives?\",\n },\n {\n id: \"recall\",\n title: \"Recall and reference periods\",\n prompt:\n \"Are recall periods explicit, realistic, and consistent with what respondents can remember?\",\n },\n {\n id: \"response-options\",\n title: \"Response option quality\",\n prompt:\n \"Are options mutually exclusive, collectively sufficient, balanced, ordered, and consistently scaled?\",\n },\n {\n id: \"key-semantic-consistency\",\n title: \"Variable-name and export-code consistency\",\n prompt:\n \"Do response variable names and option export codes follow the survey's established convention and avoid contradicting the content they currently identify? Generic, numeric, or opaque keys are acceptable when that is the survey's consistent pattern; flag descriptive keys when they have become stale or misleading, and mixed conventions when the inconsistency appears accidental.\",\n },\n {\n id: \"flow\",\n title: \"Flow and completeness\",\n prompt:\n \"Does the order move logically from easy/general to specific, with needed instructions and no important objective omitted?\",\n },\n {\n id: \"routing\",\n title: \"Requiredness and routing\",\n prompt:\n \"Do required fields, branching, validation, and not-applicable paths avoid forcing inaccurate answers?\",\n },\n {\n id: \"sensitivity\",\n title: \"Sensitivity and ethics\",\n prompt:\n \"Are sensitive questions justified, respectfully phrased, appropriately optional, and paired with privacy context where needed?\",\n },\n {\n id: \"accessibility\",\n title: \"Accessibility and inclusion\",\n prompt:\n \"Is language plain and inclusive, and are content, controls, and images understandable without avoidable barriers?\",\n },\n {\n id: \"localization\",\n title: \"Cross-language equivalence\",\n prompt:\n \"Do translations preserve meaning and cultural relevance rather than merely matching words?\",\n },\n {\n id: \"testing\",\n title: \"Testing and validation\",\n prompt:\n \"Has the instrument been cognitively tested, piloted, and checked for reliability or validity where the intended use requires it?\",\n },\n];\n\nconst collectKeyReviewEntries = (context: SurveyAssistantEngineContext, sourceLocale: string) => {\n const model = context.model;\n const entries: SurveyAuditKeyReviewEntry[] = [];\n const text = (refs: LocalizationRef[]) =>\n refs\n .map((ref) => getContentPlainText(readLocalizationContent(model, ref, sourceLocale)).trim())\n .filter(Boolean)\n .join(\" / \");\n for (const slot of model.slots.definitions) {\n const element = model.elements.get(slot.elementId)!;\n const binding = element.facts.bindings.find((entry) => entry.slotId === slot.slotId);\n const resolved = resolveElementName(model, slot.elementId, [sourceLocale]);\n const refs: LocalizationRef[] =\n binding?.labelRefs?.map((ref) => ({ scope: \"content\", ...ref })) ??\n (resolved ? [{ scope: \"content\", ownerId: resolved.ownerId, role: resolved.role }] : []);\n entries.push({\n kind: \"response-variable\",\n slotId: slot.slotId,\n valueType: slot.valueType,\n computed: !!slot.computed,\n itemId: slot.itemId,\n itemKey: model.resolveItemEditorName(slot.itemId, sourceLocale),\n key: slot.variableName,\n keySource: \"explicit\",\n localizationRefs: refs,\n content: text(refs),\n });\n const codes = new Map(Object.entries(slot.referenceValueKeys ?? {}));\n const declaredLabels = new Map(\n Object.entries(\n new Map(Object.entries(slot.referenceValueLabels ?? {})).get(sourceLocale) ?? {},\n ),\n );\n const optionIds = new Set([\n ...(slot.allowedValues ?? []).flatMap((value) =>\n value.type === \"reference\"\n ? [value.value]\n : value.type === \"reference[]\"\n ? value.value\n : [],\n ),\n ...codes.keys(),\n ]);\n for (const id of optionIds) {\n const code = codes.get(id);\n const explicit = !!code?.trim();\n // Categorical owners declare their wording roles; no item-relative flattened keys.\n const owner = model.owners.get(id);\n const optionRefs: LocalizationRef[] = owner?.roles.some((role) => role.role === \"label\")\n ? [{ scope: \"content\", ownerId: id, role: \"label\" }]\n : [];\n entries.push({\n kind: \"choice-option\",\n slotId: slot.slotId,\n itemId: slot.itemId,\n itemKey: model.resolveItemEditorName(slot.itemId, sourceLocale),\n key: explicit ? code! : id,\n keySource: explicit ? \"explicit\" : \"fallback-id\",\n localizationRefs: optionRefs,\n content: optionRefs.length ? text(optionRefs) : declaredLabels.get(id),\n });\n }\n }\n return entries;\n};\n\nexport const auditSurvey = (\n context: SurveyAssistantEngineContext,\n options: {\n sourceLocale?: string;\n targetLocales?: string[];\n maxFindings?: number;\n keyReviewOffset?: number;\n keyReviewLimit?: number;\n } = {},\n): SurveyAuditReport => {\n const findings: SurveyAuditFinding[] = [];\n const add = (finding: SurveyAuditFinding) => findings.push(finding);\n const items = context.survey.surveyItems;\n const itemTypes: Record<string, number> = {},\n elementTypes: Record<string, number> = {};\n for (const item of items)\n setOwnValue(itemTypes, item.itemType, (ownValue(itemTypes, item.itemType) ?? 0) + 1);\n for (const element of context.model.elements.values())\n setOwnValue(\n elementTypes,\n element.node.elementType,\n (ownValue(elementTypes, element.node.elementType) ?? 0) + 1,\n );\n\n const locales = context.inspection.locales;\n const sourceLocale = options.sourceLocale ?? context.ui.selectedLocale ?? locales[0];\n const targetLocales =\n options.targetLocales ??\n (options.sourceLocale ? locales.filter((locale) => locale !== sourceLocale) : locales);\n const allKeyReviewEntries = collectKeyReviewEntries(context, sourceLocale);\n const keyReviewOffset = Math.min(options.keyReviewOffset ?? 0, allKeyReviewEntries.length);\n const keyReviewLimit = options.keyReviewLimit ?? 30;\n const keyReviewEntries = allKeyReviewEntries.slice(\n keyReviewOffset,\n keyReviewOffset + keyReviewLimit,\n );\n\n for (const entry of listLocalizationEntries(context.model, {\n sourceLocale: options.sourceLocale,\n })) {\n for (const locale of targetLocales) {\n if (\n !hasLocalizationText(ownValue(entry.contents, locale)) &&\n Object.entries(entry.contents).some(\n ([other, content]) => other !== locale && hasLocalizationText(content),\n )\n )\n add({\n code: \"missing-translation\",\n severity: \"warning\",\n category: \"localization\",\n ...(entry.ref.scope === \"content\"\n ? { itemId: context.model.owners.get(entry.ref.ownerId)?.itemId }\n : {}),\n locale,\n localizationRefs: [entry.ref],\n message: `Content \"${entry.ref.scope === \"content\" ? entry.ref.role : entry.ref.contentKey}\" is available in another language but has no ${locale} translation.`,\n });\n }\n }\n\n for (const element of context.model.elements.values()) {\n const emptyControls = new Set<string>();\n for (const binding of element.facts.bindings) {\n if (\n !binding.selection ||\n binding.selection.options.length ||\n emptyControls.has(binding.controlId)\n )\n continue;\n emptyControls.add(binding.controlId);\n add({\n code: \"choice-without-options\",\n severity: \"error\",\n category: \"content\",\n itemId: element.itemId,\n path: context.model.owners.get(binding.controlId)?.path ?? element.path,\n message: `Choice input \"${binding.controlId}\" has no options.`,\n suggestion: \"Add at least one option with localized wording, or remove the input.\",\n });\n }\n }\n\n // Use the editor's authoritative deterministic diagnostics, including selected-locale\n // accessible names, inherited state cycles and externally locked checkboxes.\n for (const diagnostic of getDefinitionDiagnostics(context.model, sourceLocale))\n add({\n code: diagnostic.code,\n severity: diagnostic.severity,\n category: diagnostic.code.startsWith(\"missing-\") ? \"content\" : \"logic\",\n message: diagnostic.message,\n itemId: diagnostic.ownerItemId,\n path: diagnostic.path,\n suggestion: getSurveyAssistantExpressionDiagnosticGuidance(diagnostic),\n });\n for (const issue of getAssistantResponseSchemaIssues(\n context.survey,\n context.trustedCapabilities,\n )) {\n if (\n !findings.some((finding) => finding.code === issue.code && finding.message === issue.message)\n )\n add({ ...issue, category: \"responses\" });\n }\n\n const assets = context.survey.assets ?? {};\n for (const [assetId, asset] of Object.entries(assets)) {\n const metadata = isRecord(asset.metadata) ? asset.metadata : {};\n if (asset.kind === \"image\" && typeof metadata.alt !== \"string\")\n add({\n code: \"missing-image-alt\",\n severity: \"warning\",\n category: \"assets\",\n message: `Image asset \"${assetId}\" has no alternative text.`,\n suggestion:\n \"Add concise alt text, or an empty alt value when the image is purely decorative.\",\n });\n }\n\n const limited = findings.slice(0, options.maxFindings ?? 200);\n const summary = findings.reduce<Record<SurveyAuditSeverity, number> & { total: number }>(\n (acc, entry) => {\n acc[entry.severity] += 1;\n acc.total += 1;\n return acc;\n },\n { error: 0, warning: 0, info: 0, total: 0 },\n );\n\n return {\n summary,\n findingCount: findings.length,\n truncated: limited.length < findings.length,\n metrics: {\n itemCount: context.inspection.itemCount,\n localeCount: locales.length,\n responseSlotCount: context.inspection.responseSlots.length,\n assetCount: Object.keys(assets).length,\n itemTypes,\n elementTypes,\n },\n findings: limited,\n qualityReviewPrinciples: QUALITY_PRINCIPLES,\n keyReview: {\n sourceLocale,\n entryCount: allKeyReviewEntries.length,\n offset: keyReviewOffset,\n returnedEntryCount: keyReviewEntries.length,\n truncated: keyReviewOffset + keyReviewEntries.length < allKeyReviewEntries.length,\n entries: keyReviewEntries,\n note: \"These key/content pairs are evidence for qualitative review, not deterministic defects. Judge them against the survey's own naming pattern; generic or opaque keys are not inherently problematic.\",\n },\n note: \"Technical findings are deterministic. Quality principles are a structured review rubric; apply them with human/model judgment and domain context, and do not present them as psychometric validation.\",\n };\n};\n","import {\n surveyOperationSchema,\n type SurveyOperation,\n type SurveyDocumentSnapshot,\n type SurveyValidationIssue,\n} from \"../protocol\";\nimport { validateSurveyOperations } from \"./operations\";\nimport { expressionMutationSchema } from \"./expression-mutations\";\nimport type { SurveyAssistantEngineContext } from \"./context\";\n\ntype RecoveryContext = SurveyDocumentSnapshot | SurveyAssistantEngineContext | undefined;\n\nexport const UNIDENTIFIED_MUTATION_TARGET = \"unidentified-mutation\";\nexport const SATISFIED_MUTATION_TARGET = \"satisfied-mutation\";\n\n// Only validator-confirmed no-ops can be acknowledged without a mutation.\nconst SATISFIED_ISSUES = new Set([\n \"survey-locale-already-exists\",\n \"item-already-in-target-parent\",\n \"no-expression-patches\",\n]);\n\n// Retain precise obligations only for errors whose correction changes a value,\n// not the operation's target. New or uncertain errors require a linked non-empty\n// retry by default; they must never silently become impossible fixed identities.\nconst VALUE_ONLY_ISSUES = new Set([\n \"invalid-mutation-value\",\n \"target-index-after-end\",\n \"option-index-after-end\",\n \"missing-create-content\",\n \"missing-choice-options\",\n \"missing-choice-option-label\",\n \"missing-choice-option-labels\",\n \"missing-form-field-content\",\n \"missing-form-field-labels\",\n \"missing-form-select-option-labels\",\n \"missing-embedded-form-field-labels\",\n \"missing-field-groups-wrapper\",\n \"invalid-form-layout-columns\",\n \"missing-expression\",\n \"invalid-expression\",\n \"unknown-response-ref\",\n \"expression-function-signature-mismatch\",\n \"expression-return-type-mismatch\",\n \"missing-date-format\",\n \"image-asset-still-referenced\",\n]);\n\nconst exceptionalRecoveryTarget = (\n operationIndex: number,\n issues: SurveyValidationIssue[],\n): string | undefined => {\n const errors = issues.filter(\n (issue) =>\n issue.severity === \"error\" &&\n (issue.operationIndex === operationIndex || issue.operationIndex === undefined),\n );\n if (errors.length === 0) return undefined;\n if (errors.every((issue) => SATISFIED_ISSUES.has(issue.code))) return SATISFIED_MUTATION_TARGET;\n if (!errors.every((issue) => VALUE_ONLY_ISSUES.has(issue.code)))\n return UNIDENTIFIED_MUTATION_TARGET;\n return undefined;\n};\n\nconst record = (value: unknown): Record<string, unknown> =>\n value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\nconst at = (value: unknown, path: string): unknown =>\n path.split(\".\").reduce<unknown>((entry, key) => record(entry)[key], value);\n\n// These are obligation identities, not stored values or broad preview targets.\n// Read identities even when a value fails parsing (e.g. a numeric itemLabel).\n// Missing identities remain explicitly unresolved instead of matching any edit.\nconst identityFields = {\n \"create-item\": [\"target.parentItemId\", \"item.id\"],\n \"insert-element\": [\"target.layoutId\", \"element.id\"],\n \"insert-preset\": [\n \"elementType\",\n \"presetId\",\n \"locale\",\n \"target.layoutId?\",\n \"target.parentItemId?\",\n \"target.index?\",\n ],\n \"insert-blocks\": [\"bodyOwnerId\"],\n \"update-content\": [\n \"ref.scope\",\n \"ref.ownerId?\",\n \"ref.role?\",\n \"ref.surface?\",\n \"ref.contentKey?\",\n \"locale\",\n ],\n \"update-placed-image\": [\n \"ref.scope\",\n \"ref.ownerId?\",\n \"ref.role?\",\n \"ref.surface?\",\n \"ref.contentKey?\",\n \"locale\",\n \"imageIndex\",\n ],\n \"patch-element-config\": [\"elementId\"],\n \"patch-item-config\": [\"itemId\"],\n \"update-item-label\": [\"itemId\"],\n \"update-item-color\": [\"itemId\"],\n \"remove-item\": [\"itemId\"],\n \"move-item\": [\"itemId\"],\n \"reorder-items\": [\"parentItemId\"],\n \"move-element\": [\"elementId\"],\n \"move-block\": [\"blockId\"],\n \"remove-content\": [\"ownerId\"],\n \"update-layout\": [\"layoutId\"],\n \"update-response-settings\": [\"naming\", \"settings\"],\n \"set-image-asset\": [\"assetId\"],\n \"update-image-asset-metadata\": [\"assetId\"],\n \"remove-image-asset\": [\"assetId\"],\n \"update-survey-metadata\": [],\n \"update-survey-pagination\": [],\n \"update-survey-translation\": [\"locale\", \"surface\", \"contentKey\"],\n \"add-survey-locale\": [\"locale\"],\n \"remove-survey-locale\": [\"locale\"],\n \"survey-json-patch\": [],\n} satisfies Record<SurveyOperation[\"kind\"], string[]>;\n\nconst identities = (\n kind: string,\n value: unknown,\n fields: string[],\n context?: RecoveryContext,\n): unknown[] | undefined => {\n const parts: unknown[] = [kind];\n for (const field of fields) {\n const optional = field.endsWith(\"?\");\n const path = optional ? field.slice(0, -1) : field;\n let part = at(value, path);\n if (typeof part === \"string\" && context && /(?:^|\\.)(?:itemId|parentItemId)$/.test(path)) {\n const direct = context.survey.surveyItems.find((item) => item.id === part);\n if (!direct) return undefined;\n part = direct.id;\n }\n if (part === undefined && optional) parts.push(null);\n else if (\n (typeof part === \"string\" && part.length > 0) ||\n ((path === \"imageIndex\" || path.endsWith(\"index\")) &&\n typeof part === \"number\" &&\n Number.isInteger(part) &&\n part >= 0)\n )\n parts.push(part);\n else return undefined;\n }\n return parts;\n};\n\nexport const collectSurveyOperationRecoveryTargets = (\n operations: unknown[],\n context?: RecoveryContext,\n issues: SurveyValidationIssue[] = [],\n): Set<string> => {\n const targets = operations.flatMap((operation, operationIndex) => {\n const value = record(operation);\n const kind = value.kind;\n if (typeof kind !== \"string\" || !Object.hasOwn(identityFields, kind)) {\n return [UNIDENTIFIED_MUTATION_TARGET];\n }\n // A raw fallback's pointer and verb can both be wrong, including before\n // parsing succeeds. Retargeting always requires a linked non-empty retry.\n if (kind === \"survey-json-patch\" || kind === \"patch-item-config\")\n return [UNIDENTIFIED_MUTATION_TARGET];\n const exceptional = exceptionalRecoveryTarget(operationIndex, issues);\n if (exceptional) return [exceptional];\n if (kind === \"update-response-settings\") {\n const targets = [\"naming\", \"settings\"].flatMap((surface) =>\n Array.isArray(value[surface])\n ? value[surface].map((edit: unknown) => {\n const entry = record(edit);\n const identity = entry.slotId ?? entry.elementId;\n return typeof identity === \"string\" && identity.length\n ? JSON.stringify([kind, surface, identity])\n : UNIDENTIFIED_MUTATION_TARGET;\n })\n : [],\n );\n return targets.length ? targets : [UNIDENTIFIED_MUTATION_TARGET];\n }\n const parts = identities(kind, value, identityFields[kind as SurveyOperation[\"kind\"]], context);\n if (!parts) return [UNIDENTIFIED_MUTATION_TARGET];\n const fields =\n kind === \"update-survey-metadata\"\n ? value.values\n : kind === \"update-image-asset-metadata\"\n ? value.metadata\n : kind === \"update-placed-image\"\n ? value.changes\n : undefined;\n if (\n [\"update-survey-metadata\", \"update-image-asset-metadata\", \"update-placed-image\"].includes(\n kind,\n )\n ) {\n const keys = Object.keys(record(fields));\n return keys.length > 0\n ? keys.map((key) => JSON.stringify([...parts, key]))\n : [UNIDENTIFIED_MUTATION_TARGET];\n }\n return [JSON.stringify(parts)];\n });\n return new Set(targets.length > 0 ? targets : [UNIDENTIFIED_MUTATION_TARGET]);\n};\n\nconst expressionIdentityFields = {\n \"set-condition\": [\"ownerId\", \"property\"],\n \"clear-condition\": [\"ownerId\", \"property\"],\n \"set-config-expression\": [\"elementId\", \"path\"],\n \"clear-config-expression\": [\"elementId\", \"path\"],\n \"set-validation-rule\": [\"itemId\", \"rule.id\"],\n \"remove-validation-rule\": [\"itemId\", \"ruleId\"],\n \"set-prefill\": [\"elementId\", \"slotId\", \"prefill.id\"],\n \"clear-prefill\": [\"elementId\", \"slotId\", \"prefillId\"],\n \"set-template-value\": [\"templateKey\"],\n \"clear-template-value\": [\"templateKey\"],\n} satisfies Record<import(\"./expression-mutations\").ExpressionMutation[\"kind\"], string[]>;\n\nexport const collectExpressionMutationRecoveryTargets = (\n mutations: unknown[],\n context?: RecoveryContext,\n issues: SurveyValidationIssue[] = [],\n): string[] => [\n ...new Set(\n mutations.map((mutation, operationIndex) => {\n const kind = record(mutation).kind;\n if (typeof kind !== \"string\" || !Object.hasOwn(expressionIdentityFields, kind))\n return UNIDENTIFIED_MUTATION_TARGET;\n const parsed = expressionMutationSchema.safeParse(mutation);\n if (\n !parsed.success &&\n !parsed.error.issues.every(\n (issue) =>\n issue.path[0] === \"expression\" ||\n issue.path[0] === \"templateValue\" ||\n (issue.path[0] === \"rule\" && issue.path.length > 1 && issue.path[1] !== \"id\") ||\n (issue.path[0] === \"prefill\" && issue.path.length > 1 && issue.path[1] !== \"id\"),\n )\n )\n return UNIDENTIFIED_MUTATION_TARGET;\n const exceptional = exceptionalRecoveryTarget(operationIndex, issues);\n if (exceptional) return exceptional;\n const parts = identities(\n kind,\n mutation,\n expressionIdentityFields[kind as keyof typeof expressionIdentityFields],\n context,\n );\n return parts ? JSON.stringify(parts) : UNIDENTIFIED_MUTATION_TARGET;\n }),\n ),\n];\n\n/** Classify a malformed batch without staging any of its parseable siblings.\n * The canonical validator sees those siblings in order, retaining dependencies;\n * all diagnostic indexes are mapped back to the original, unfiltered input.\n */\nexport const collectMalformedSurveyOperationRecoveryTargets = (\n operations: unknown[],\n context?: RecoveryContext,\n normalizationIssues: { path: string }[] = [],\n): Set<string> => {\n const parsedOperations: SurveyOperation[] = [];\n const originalIndexes: number[] = [];\n const issues: SurveyValidationIssue[] = [];\n operations.forEach((operation, operationIndex) => {\n const parsed = surveyOperationSchema.safeParse(operation);\n const normalizationFailed = normalizationIssues.some(\n (issue) => Number(issue.path.split(\".\")[0]) === operationIndex,\n );\n if (parsed.success && !normalizationFailed) {\n // Raw fallback calls must stand alone and always require explicit repair.\n // Exclude them so their single-operation guard cannot mask typed siblings.\n if (parsed.data.kind === \"survey-json-patch\") return;\n parsedOperations.push(parsed.data);\n originalIndexes.push(operationIndex);\n return;\n }\n const value = record(operation);\n const kind = value.kind;\n // These editor fields apply to an existing item independently of their\n // payload. Check both schema issue paths and the advertised item capability.\n const valueField =\n kind === \"update-item-label\"\n ? \"itemLabel\"\n : kind === \"update-item-color\"\n ? \"color\"\n : undefined;\n const parts =\n typeof kind === \"string\" && Object.hasOwn(identityFields, kind)\n ? identities(kind, value, identityFields[kind as SurveyOperation[\"kind\"]], context)\n : undefined;\n const item = context?.survey.surveyItems.find((entry) => entry.id === parts?.[1]);\n // Editor names/colors are core item metadata, independent of element authoring grants.\n const supported = !!item;\n const hasHostPredicate = false;\n const valueOnly =\n !hasHostPredicate &&\n !normalizationFailed &&\n !parsed.success &&\n valueField &&\n supported &&\n parsed.error.issues.every((issue) => issue.path[0] === valueField);\n issues.push({\n severity: \"error\",\n operationIndex,\n code: valueOnly ? \"invalid-mutation-value\" : \"invalid-operation-shape\",\n message: \"Malformed operation recovery classification.\",\n });\n });\n if (parsedOperations.length > 0) {\n const validation = validateSurveyOperations({\n operations: parsedOperations,\n snapshot: context,\n });\n issues.push(\n ...validation.issues.map((issue) => ({\n ...issue,\n ...(issue.operationIndex !== undefined\n ? { operationIndex: originalIndexes[issue.operationIndex] }\n : {}),\n })),\n );\n }\n return collectSurveyOperationRecoveryTargets(operations, context, issues);\n};\n\nexport type RecoveryTargetRefinement = { targets: string[]; replacement: string };\n\n/** Later validation can disprove an earlier target assumption. Refine only the\n * same attempted operation's exact identities; this does not discharge work.\n */\nconst collectRecoveryTargetRefinements = (\n values: unknown[],\n context: RecoveryContext,\n issues: SurveyValidationIssue[],\n collect: (\n values: unknown[],\n context: RecoveryContext,\n issues?: SurveyValidationIssue[],\n ) => Iterable<string>,\n): RecoveryTargetRefinement[] =>\n values.flatMap((value, operationIndex) => {\n const operationIssues = issues\n .filter(\n (issue) => issue.operationIndex === operationIndex || issue.operationIndex === undefined,\n )\n .map((issue) => ({ ...issue, operationIndex: 0 }));\n const before = [...collect([value], context)];\n const after = [...collect([value], context, operationIssues)];\n const replacement = after.find(\n (target) => target === UNIDENTIFIED_MUTATION_TARGET || target === SATISFIED_MUTATION_TARGET,\n );\n const targets = before.filter(\n (target) => target !== UNIDENTIFIED_MUTATION_TARGET && target !== SATISFIED_MUTATION_TARGET,\n );\n return replacement && targets.length ? [{ targets, replacement }] : [];\n });\n\nexport const collectSurveyOperationRecoveryRefinements = (\n values: unknown[],\n context: RecoveryContext,\n issues: SurveyValidationIssue[],\n) =>\n collectRecoveryTargetRefinements(values, context, issues, collectSurveyOperationRecoveryTargets);\n\nexport const collectExpressionMutationRecoveryRefinements = (\n values: unknown[],\n context: RecoveryContext,\n issues: SurveyValidationIssue[],\n) =>\n collectRecoveryTargetRefinements(\n values,\n context,\n issues,\n collectExpressionMutationRecoveryTargets,\n );\n\n/** Refine only resource identities present before a successful delta and absent\n * after it. Values, other items' components, and opaque recovery markers do not\n * count as references. Comparing canonical states also covers raw deletions.\n */\nexport const collectRemovedRecoveryTargetRefinements = (\n targets: Iterable<string>,\n before: SurveyAssistantEngineContext,\n after: SurveyAssistantEngineContext,\n): RecoveryTargetRefinement[] => {\n const resourceExists = (\n field: string,\n id: unknown,\n context: SurveyAssistantEngineContext,\n ): boolean => {\n if (typeof id !== \"string\") return false;\n if (/(?:^|\\.)(?:itemId|parentItemId)$/.test(field))\n return context.survey.surveyItems.some((item) => item.id === id);\n if (field === \"locale\") return Object.hasOwn(context.survey.translations ?? {}, id);\n if (field === \"assetId\") return Object.hasOwn(context.survey.assets ?? {}, id);\n if (/(?:^|\\.)(?:ownerId|bodyOwnerId|elementId|layoutId|blockId|slotId)$/.test(field))\n return context.model.identities.has(id);\n return false;\n };\n return [...new Set(targets)].flatMap((target) => {\n if (!target.startsWith(\"[\")) return [];\n let parts: unknown;\n try {\n parts = JSON.parse(target);\n } catch {\n return [];\n }\n if (!Array.isArray(parts) || typeof parts[0] !== \"string\") return [];\n const kind = parts[0];\n const fields: string[] | undefined = Object.hasOwn(identityFields, kind)\n ? identityFields[kind as SurveyOperation[\"kind\"]]\n : Object.hasOwn(expressionIdentityFields, kind)\n ? expressionIdentityFields[kind as keyof typeof expressionIdentityFields]\n : undefined;\n if (!fields) return [];\n const bindings = Object.fromEntries(\n fields.map((field, index) => [field.replace(/\\?$/, \"\"), parts[index + 1]]),\n );\n const removed = Object.entries(bindings).some(\n ([field, id]) => resourceExists(field, id, before) && !resourceExists(field, id, after),\n );\n return removed ? [{ targets: [target], replacement: UNIDENTIFIED_MUTATION_TARGET }] : [];\n });\n};\n","import {\n SURVEY_ASSISTANT_PROTOCOL_VERSION,\n surveyChangeSetSchema,\n surveyAssistantTurnFinalSchema,\n type SurveyAssistantTurnFinal,\n type SurveyChangeSet,\n type SurveyDocumentSnapshot,\n type SurveyOperation,\n type SurveyValidationIssue,\n} from \"../protocol\";\nimport { getContentPlainText } from \"@case-framework/survey-core\";\nimport { getAnswerTypeChangeDiagnostics } from \"@case-framework/survey-core/editor\";\nimport {\n MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT,\n createSurveyChangeSet,\n} from \"./operations\";\nimport { SurveyOperationExecutionSession } from \"./operation-execution\";\nimport { getGroupChildren } from \"./operation-state\";\nimport { auditSurvey, type SurveyAuditFinding } from \"./audit\";\nimport { createSurveyAssistantEngineContext, type SurveyAssistantEngineContext } from \"./context\";\nimport { getDiagnosticLocation, getIntroducedDefinitionIssues } from \"./definition-diagnostics\";\nimport {\n collectSurveyOperationRecoveryTargets,\n collectSurveyOperationRecoveryRefinements,\n collectRemovedRecoveryTargetRefinements,\n type RecoveryTargetRefinement,\n UNIDENTIFIED_MUTATION_TARGET,\n SATISFIED_MUTATION_TARGET,\n} from \"./mutation-recovery\";\n\nconst createId = () => globalThis.crypto.randomUUID();\n\nconst operationTargets = (\n operation: SurveyOperation,\n context?: SurveyAssistantEngineContext,\n): string[] => {\n const ownerTarget = (id: string) => {\n const identity = context?.model.identities.get(id),\n owner =\n context?.model.owners.get(id) ??\n (identity?.ownerId ? context?.model.owners.get(identity.ownerId) : undefined);\n return owner ? [`item:${owner.itemId}`] : [`owner:${id}`];\n };\n switch (operation.kind) {\n case \"create-item\":\n return [`item:${operation.item.id}`];\n case \"insert-element\":\n return ownerTarget(operation.target.layoutId);\n case \"insert-preset\":\n return \"layoutId\" in operation.target\n ? ownerTarget(operation.target.layoutId)\n : [`item:${operation.target.parentItemId}`];\n case \"insert-blocks\":\n case \"move-block\":\n return [\n ...ownerTarget(operation.bodyOwnerId),\n ...(operation.kind === \"move-block\" ? ownerTarget(operation.blockId) : []),\n ];\n case \"update-layout\":\n return ownerTarget(operation.layoutId);\n case \"remove-content\":\n return ownerTarget(operation.ownerId);\n case \"move-element\":\n return [...ownerTarget(operation.elementId), ...ownerTarget(operation.target.layoutId)];\n case \"patch-element-config\":\n return ownerTarget(operation.elementId);\n case \"update-content\":\n case \"update-placed-image\":\n return operation.ref.scope === \"content\" ? ownerTarget(operation.ref.ownerId) : [\"survey\"];\n case \"update-item-label\":\n case \"update-item-color\":\n case \"patch-item-config\":\n case \"remove-item\":\n case \"move-item\":\n return [`item:${operation.itemId}`];\n case \"reorder-items\":\n return [`item:${operation.parentItemId}`];\n case \"set-image-asset\":\n case \"update-image-asset-metadata\":\n case \"remove-image-asset\":\n return [`asset:${operation.assetId}`];\n case \"update-response-settings\":\n return [\n ...new Set(\n context?.responseVariables\n .filter(\n (slot) =>\n operation.naming.some((edit) =>\n \"slotId\" in edit\n ? edit.slotId === slot.slotId\n : edit.elementId === slot.elementId,\n ) || operation.settings.some((edit) => edit.slotId === slot.slotId),\n )\n .map((slot) => `item:${slot.itemId}`) ?? [\"survey\"],\n ),\n ];\n case \"update-survey-metadata\":\n case \"update-survey-pagination\":\n case \"update-survey-translation\":\n case \"add-survey-locale\":\n case \"remove-survey-locale\":\n return [\"survey\"];\n case \"survey-json-patch\":\n return operation.patches.map((patch) => `path:${patch.path}`);\n default: {\n const exhaustive: never = operation;\n throw new Error(String(exhaustive));\n }\n }\n};\n\nconst collectOperationTargets = (\n operations: SurveyOperation[],\n context?: SurveyAssistantEngineContext,\n) => new Set(operations.flatMap((operation) => operationTargets(operation, context)));\n\n// A proposal rejected only because it used the wrong mutation route should be\n// repairable through that route even when its untrusted raw target was wrong.\n// Add future specialized-tool routing codes here and have the corresponding\n// successful tool stage its route through `handledMutationRoutes`.\nconst mutationRecoveryRouteByIssueCode = {\n \"expression-patch-requires-specialized-tool\": \"expression\",\n} as const;\n\nexport type SurveyAssistantMutationRoute =\n (typeof mutationRecoveryRouteByIssueCode)[keyof typeof mutationRecoveryRouteByIssueCode];\n\nconst mutationRouteTarget = (route: SurveyAssistantMutationRoute) => `mutation-route:${route}`;\n\nconst collectExclusiveMutationRecoveryTargets = (\n changeSet: SurveyChangeSet,\n): Set<string> | undefined => {\n const errorIssues = changeSet.validation.issues.filter((issue) => issue.severity === \"error\");\n if (errorIssues.length === 0) return undefined;\n\n const routes = errorIssues.map(\n (issue) =>\n mutationRecoveryRouteByIssueCode[issue.code as keyof typeof mutationRecoveryRouteByIssueCode],\n );\n const knownRoutes = routes.filter(\n (route): route is SurveyAssistantMutationRoute => route !== undefined,\n );\n if (knownRoutes.length !== routes.length) return undefined;\n\n return new Set(knownRoutes.map(mutationRouteTarget));\n};\n\nconst MAX_POST_CHANGE_TARGETS = 16;\nconst MAX_POST_CHANGE_ITEMS = 6;\nconst MAX_POST_CHANGE_CHILDREN = 16;\nconst MAX_POST_CHANGE_TRANSLATIONS = 12;\nconst MAX_POST_CHANGE_RESPONSE_SLOTS = 12;\nconst MAX_POST_CHANGE_TEXT_CHARS = 100;\nconst MAX_VERIFICATION_AUDIT_FINDINGS = 8;\nconst MAX_VERIFICATION_MESSAGE_CHARS = 240;\nconst SUBSTANTIAL_CHANGE_ITEM_COUNT = 6;\nconst SUBSTANTIAL_CHANGE_OPERATION_COUNT = 12;\n\nconst createPostChangeProjection = (\n context: SurveyAssistantEngineContext,\n targets: Set<string>,\n before: SurveyAssistantEngineContext | undefined,\n reorderedParentIds: string[],\n): NonNullable<SurveyChangeSet[\"postChange\"]> => {\n // Echo explicit reorder requests even when already satisfied. For other\n // mutation routes, include only changed child lists, including both move parents.\n const beforeItems = new Map(before?.survey.surveyItems.map((item) => [item.id, item]));\n const previewedChildOrders = new Set(reorderedParentIds);\n for (const item of context.survey.surveyItems) {\n if (item.itemType !== \"group\") continue;\n const previous = beforeItems.get(item.id);\n const children = getGroupChildren(item);\n const previousChildren = getGroupChildren(previous);\n if (\n !previous ||\n children.length !== previousChildren.length ||\n children.some((id, index) => id !== previousChildren[index])\n )\n previewedChildOrders.add(item.id);\n }\n // Preserve mutation order, then append indirectly affected parents. All\n // targets participate in the same bounded coverage accounting.\n const allTargets = [\n ...new Set([...targets, ...[...previewedChildOrders].map((id) => `item:${id}`)]),\n ];\n const requestedItemIds = allTargets\n .filter((target) => target.startsWith(\"item:\"))\n .map((target) => target.slice(\"item:\".length));\n const itemEntries = requestedItemIds\n .map((itemId) => context.inspection.itemIndex.find((entry) => entry.itemId === itemId))\n .filter((entry) => entry !== undefined);\n const itemsById = new Map(context.survey.surveyItems.map((item) => [item.id, item]));\n const outlineById = new Map(context.inspection.outline.map((item) => [item.itemId, item]));\n let truncated =\n allTargets.length > MAX_POST_CHANGE_TARGETS || itemEntries.length > MAX_POST_CHANGE_ITEMS;\n\n const touchedItems = itemEntries.slice(0, MAX_POST_CHANGE_ITEMS).map((entry) => {\n const ownerIds = new Set(\n [...context.model.owners.values()]\n .filter((owner) => owner.itemId === entry.itemId)\n .map((owner) => owner.id),\n );\n const allTranslations = Object.entries(context.survey.translations ?? {}).flatMap(\n ([locale, translation]) =>\n Object.entries(translation.content)\n .filter(([ownerId]) => ownerIds.has(ownerId))\n .flatMap(([ownerId, roles]) =>\n Object.entries(roles).map(([role, content]) => {\n const characters = [...getContentPlainText(content)];\n return {\n locale,\n ownerId,\n role,\n textPreview: characters.slice(0, MAX_POST_CHANGE_TEXT_CHARS).join(\"\"),\n textLength: characters.length,\n truncated: characters.length > MAX_POST_CHANGE_TEXT_CHARS,\n };\n }),\n ),\n );\n const translations = allTranslations.slice(0, MAX_POST_CHANGE_TRANSLATIONS);\n const allResponseSlots = context.responseVariables\n .filter((slot) => slot.itemId === entry.itemId)\n .map((slot) => slot.slotId);\n const responseSlots = allResponseSlots.slice(0, MAX_POST_CHANGE_RESPONSE_SLOTS);\n if (\n allTranslations.length > translations.length ||\n allResponseSlots.length > responseSlots.length ||\n translations.some((translation) => translation.truncated)\n ) {\n truncated = true;\n }\n\n const parentId = outlineById.get(entry.itemId)?.parentId;\n const parent = parentId ? itemsById.get(parentId) : undefined;\n const siblings = parent?.itemType === \"group\" ? getGroupChildren(parent) : undefined;\n const index = siblings?.indexOf(entry.itemId) ?? -1;\n const placement =\n parent && siblings && index >= 0\n ? {\n parentItemId: parent.id,\n index,\n siblingCount: siblings.length,\n ...(index > 0 ? { previousItemId: siblings[index - 1] } : {}),\n ...(index + 1 < siblings.length ? { nextItemId: siblings[index + 1] } : {}),\n shuffled: parent.itemType === \"group\" && parent.config.shuffleItems === true,\n }\n : undefined;\n const item = itemsById.get(entry.itemId);\n const children = previewedChildOrders.has(entry.itemId) ? getGroupChildren(item) : undefined;\n const childOrder = children\n ? {\n itemIds: children.slice(0, MAX_POST_CHANGE_CHILDREN),\n total: children.length,\n truncated: children.length > MAX_POST_CHANGE_CHILDREN,\n shuffled: item?.itemType === \"group\" && item.config.shuffleItems === true,\n }\n : undefined;\n if (childOrder?.truncated) truncated = true;\n\n return {\n itemId: entry.itemId,\n ...(placement ? { placement } : {}),\n ...(childOrder ? { childOrder } : {}),\n itemType: entry.itemType,\n editorName: entry.editorName,\n breadcrumb: entry.breadcrumb,\n ...(entry.itemLabel ? { itemLabel: entry.itemLabel } : {}),\n translationCount: allTranslations.length,\n translations,\n responseSlotCount: allResponseSlots.length,\n responseSlots,\n responseVariables: context.responseVariables.filter((slot) =>\n responseSlots.includes(slot.slotId),\n ),\n };\n });\n\n return {\n version: context.version,\n itemCount: context.inspection.itemCount,\n localeCount: context.inspection.locales.length,\n locales: context.inspection.locales.slice(0, 32),\n targetCount: allTargets.length,\n touchedTargets: allTargets.slice(0, MAX_POST_CHANGE_TARGETS),\n touchedItemCount: requestedItemIds.length,\n availableTouchedItemCount: itemEntries.length,\n touchedItems,\n truncated: truncated || context.inspection.locales.length > 32,\n };\n};\n\nconst auditFindingKey = (finding: SurveyAuditFinding, context: SurveyAssistantEngineContext) =>\n [\n finding.code,\n finding.category,\n finding.itemId ?? \"\",\n finding.locale ?? \"\",\n JSON.stringify(finding.localizationRefs ?? getDiagnosticLocation(context.model, finding.path)),\n ].join(\"\\u0000\");\n\nconst isComplexOperation = (operation: SurveyOperation) =>\n [\n \"survey-json-patch\",\n \"patch-item-config\",\n \"patch-element-config\",\n \"insert-blocks\",\n \"move-element\",\n \"move-block\",\n \"create-item\",\n ].includes(operation.kind);\n\nconst createChangeVerification = ({\n after,\n before,\n operations,\n postChange,\n}: {\n after: SurveyAssistantEngineContext;\n before: SurveyAssistantEngineContext;\n operations: SurveyOperation[];\n postChange: NonNullable<SurveyChangeSet[\"postChange\"]>;\n}): NonNullable<SurveyChangeSet[\"verification\"]> | undefined => {\n const beforeFindingKeys = new Set(\n auditSurvey(before, { maxFindings: 10_000 }).findings.map((finding) =>\n auditFindingKey(finding, before),\n ),\n );\n const newAuditFindings = auditSurvey(after, { maxFindings: 10_000 }).findings.filter(\n (finding) => !beforeFindingKeys.has(auditFindingKey(finding, after)),\n );\n const reasons: NonNullable<SurveyChangeSet[\"verification\"]>[\"reasons\"] = [];\n if (\n operations.length > SUBSTANTIAL_CHANGE_OPERATION_COUNT ||\n postChange.touchedItemCount > SUBSTANTIAL_CHANGE_ITEM_COUNT\n ) {\n reasons.push(\"substantial-change\");\n }\n if (operations.some(isComplexOperation)) reasons.push(\"complex-change\");\n if (postChange.truncated) reasons.push(\"bounded-preview\");\n if (newAuditFindings.length > 0) reasons.push(\"new-audit-findings\");\n if (reasons.length === 0) return undefined;\n\n let truncated = newAuditFindings.length > MAX_VERIFICATION_AUDIT_FINDINGS;\n const auditFindings = newAuditFindings\n .slice(0, MAX_VERIFICATION_AUDIT_FINDINGS)\n .map((finding) => {\n const messageCharacters = [...finding.message];\n const messagePreview = messageCharacters.slice(0, MAX_VERIFICATION_MESSAGE_CHARS).join(\"\");\n const messageTruncated = messageCharacters.length > MAX_VERIFICATION_MESSAGE_CHARS;\n if (messageTruncated) truncated = true;\n return {\n code: finding.code,\n severity: finding.severity,\n category: finding.category,\n ...(finding.itemId ? { itemId: finding.itemId } : {}),\n ...(finding.locale ? { locale: finding.locale } : {}),\n ...(finding.localizationRefs ? { localizationRefs: finding.localizationRefs } : {}),\n messagePreview,\n messageLength: messageCharacters.length,\n truncated: messageTruncated,\n };\n });\n\n return {\n required: true,\n reasons,\n newAuditFindingCount: newAuditFindings.length,\n auditFindings,\n truncated,\n };\n};\n\n/**\n * Request-scoped transactional draft for one assistant response.\n *\n * Mutation tools submit deltas. A successful delta replaces the previous\n * candidate with a newly validated, cumulative change set. A rejected delta\n * leaves the accepted draft intact and blocks authorization until all of its\n * operation/surface obligations have been repaired. Only the latest cumulative\n * candidate can be authorized.\n */\nexport class TurnSurveyDraft {\n readonly turnId: string;\n\n readonly #candidates = new Map<string, SurveyChangeSet>();\n #draftOperations: SurveyOperation[] = [];\n #context: SurveyAssistantEngineContext | undefined;\n #baseline: SurveyAssistantEngineContext | undefined;\n #operationWarnings: SurveyValidationIssue[] = [];\n #reportingTargets = new Set<string>();\n #latestChangeSetId: string | undefined;\n #unresolvedCandidates = new Map<string, Set<string>>();\n #final: SurveyAssistantTurnFinal | null = null;\n\n constructor(turnId: string = createId()) {\n this.turnId = turnId;\n }\n\n initialize(context: SurveyAssistantEngineContext) {\n if (this.#context) {\n throw new Error(\"The survey turn draft was initialized more than once.\");\n }\n this.#context = context;\n this.#baseline = context;\n }\n\n stage({\n addressedTargets = [],\n allowExpressionJsonPatches = false,\n handledMutationRoutes = [],\n retryOfChangeIds = [],\n operations,\n snapshot,\n summary,\n }: {\n addressedTargets?: string[];\n allowExpressionJsonPatches?: boolean;\n handledMutationRoutes?: SurveyAssistantMutationRoute[];\n retryOfChangeIds?: string[];\n operations: SurveyOperation[];\n snapshot: SurveyAssistantEngineContext | SurveyDocumentSnapshot | undefined;\n summary: string;\n }): SurveyChangeSet {\n this.#assertOpen();\n\n if (!this.#context && snapshot && \"document\" in snapshot && \"trustedCapabilities\" in snapshot) {\n this.#context = snapshot;\n this.#baseline = snapshot;\n }\n const currentContext = this.#context ?? snapshot;\n const recoveryTargets =\n addressedTargets.length > 0\n ? new Set(addressedTargets)\n : collectSurveyOperationRecoveryTargets(operations, currentContext);\n const delta = createSurveyChangeSet({\n allowExpressionJsonPatches,\n operations,\n snapshot: currentContext,\n summary,\n turnId: this.turnId,\n });\n\n // An explicit acknowledgment can resolve already-satisfied rejected work\n // without inventing a mutation. It cannot clear identifiable obligations,\n // and an ordinary empty proposal is still invalid.\n if (\n operations.length === 0 &&\n retryOfChangeIds.some((id) =>\n this.#unresolvedCandidates.get(id)?.has(SATISFIED_MUTATION_TARGET),\n ) &&\n delta.validation.issues.length > 0 &&\n delta.validation.issues.every((issue) => issue.code === \"empty-operations\")\n ) {\n delta.status = \"validated\";\n delta.validation = { ...delta.validation, valid: true, issues: [] };\n }\n\n if (delta.status !== \"validated\" || !delta.validation.valid) {\n return this.reject(\n delta,\n collectExclusiveMutationRecoveryTargets(delta) ??\n (addressedTargets.length > 0\n ? recoveryTargets\n : collectSurveyOperationRecoveryTargets(\n operations,\n currentContext,\n delta.validation.issues,\n )),\n addressedTargets.length === 0\n ? collectSurveyOperationRecoveryRefinements(\n operations,\n currentContext,\n delta.validation.issues,\n )\n : [],\n );\n }\n\n const rejectMissingLinks = (missingRetryLinks: string[]) =>\n this.reject(\n {\n ...delta,\n status: \"rejected\",\n validation: {\n ...delta.validation,\n valid: false,\n issues: [\n {\n severity: \"error\",\n code: \"mutation-retry-link-required\",\n message: `No operations from this call were staged. Retry the complete corrected call with retryOfChangeIds: ${JSON.stringify(missingRetryLinks)} before further mutations.`,\n },\n ],\n },\n },\n recoveryTargets,\n );\n const missingRetryLinks = this.#pendingRepairs()\n .filter(\n (repair) => repair.requiresExplicitRetry && !retryOfChangeIds.includes(repair.changeId),\n )\n .map((repair) => repair.changeId);\n // Check linkage before staging so a retry cannot collide with its own work.\n if (missingRetryLinks.length > 0 && operations.length > 0)\n return rejectMissingLinks(missingRetryLinks);\n\n const cumulativeOperations = [...this.#draftOperations, ...delta.operations];\n if (cumulativeOperations.length > MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT) {\n return this.reject(\n createSurveyChangeSet({\n maxOperations: MAX_SURVEY_ASSISTANT_OPERATIONS_PER_TURN_DRAFT,\n operations: cumulativeOperations,\n snapshot: currentContext,\n summary,\n turnId: this.turnId,\n }),\n recoveryTargets,\n );\n }\n const beforeContext = this.#context;\n let nextContext = beforeContext;\n if (this.#context && delta.operations.length > 0) {\n const execution = new SurveyOperationExecutionSession(\n this.#context.survey,\n this.#context.trustedCapabilities,\n this.#context.document.answerTypes,\n );\n for (const operation of delta.operations) execution.apply(operation);\n execution.assertNoDanglingRemovals();\n nextContext = createSurveyAssistantEngineContext(\n {\n ...this.#context.document,\n survey: execution.serialize(),\n answerTypes: execution.getAnswerTypes(),\n },\n this.#context.trustedCapabilities,\n );\n }\n if (this.#baseline && nextContext) {\n const diagnostics = getAnswerTypeChangeDiagnostics(this.#baseline.model, nextContext.model);\n if (diagnostics.length)\n return this.reject(\n {\n ...delta,\n status: \"rejected\",\n validation: {\n ...delta.validation,\n valid: false,\n issues: diagnostics.map((issue) => ({\n severity: \"error\" as const,\n code: issue.code,\n message: `${JSON.stringify(issue.path)}: ${issue.message}`,\n })),\n },\n },\n recoveryTargets,\n );\n }\n const removedRefinements =\n beforeContext && nextContext && delta.operations.length > 0\n ? collectRemovedRecoveryTargetRefinements(\n [...this.#unresolvedCandidates.values()].flatMap((pending) =>\n [...pending].filter((target) => !recoveryTargets.has(target)),\n ),\n beforeContext,\n nextContext,\n )\n : [];\n const removedTargets = new Set(removedRefinements.flatMap((refinement) => refinement.targets));\n const removalLinks = [...this.#unresolvedCandidates]\n .filter(\n ([id, pending]) =>\n !retryOfChangeIds.includes(id) &&\n [...pending].some((target) => removedTargets.has(target)),\n )\n .map(([id]) => id);\n // Removing a pending target changes the requested scope. Require linkage\n // before staging, leaving an unlinked removal safely retryable.\n if (removalLinks.length > 0) return rejectMissingLinks(removalLinks);\n this.#context = nextContext;\n this.#refineRecoveryTargets(removedRefinements);\n const priorCandidate = this.#latestChangeSetId\n ? this.#candidates.get(this.#latestChangeSetId)\n : undefined;\n const acknowledgment = delta.operations.length === 0;\n const reportingTargets = new Set([\n ...collectOperationTargets(delta.operations, nextContext),\n ...addressedTargets,\n ...handledMutationRoutes.map(mutationRouteTarget),\n ...this.#reportingTargets,\n ]);\n const operationWarnings = [\n ...this.#operationWarnings,\n ...delta.validation.warnings.flatMap((warning) =>\n warning.operationIndex === undefined\n ? []\n : [{ ...warning, operationIndex: warning.operationIndex + this.#draftOperations.length }],\n ),\n ];\n // The executable candidate covers the whole turn. Recompute state warnings\n // so unrelated later edits cannot erase them, and actual repairs can clear them.\n const definitionWarnings =\n this.#baseline && this.#context\n ? getIntroducedDefinitionIssues(\n this.#baseline.model,\n this.#context.model,\n this.#context.ui.selectedLocale,\n ).filter((issue) => issue.severity === \"warning\")\n : delta.validation.warnings.filter((warning) => warning.operationIndex === undefined);\n const postChange = acknowledgment\n ? priorCandidate?.postChange\n : this.#context\n ? createPostChangeProjection(\n this.#context,\n reportingTargets,\n this.#baseline,\n cumulativeOperations.flatMap((operation) =>\n operation.kind === \"reorder-items\" ? [operation.parentItemId] : [],\n ),\n )\n : undefined;\n const verification = acknowledgment\n ? priorCandidate?.verification\n : this.#baseline && this.#context && postChange\n ? createChangeVerification({\n after: this.#context,\n before: this.#baseline,\n operations: cumulativeOperations,\n postChange,\n })\n : undefined;\n const registered = surveyChangeSetSchema.parse({\n ...delta,\n operations: cumulativeOperations,\n ...(acknowledgment && priorCandidate ? { summary: priorCandidate.summary } : {}),\n ...(postChange ? { postChange } : {}),\n ...(verification ? { verification } : {}),\n validation: {\n valid: true,\n issues: [],\n warnings: [...operationWarnings, ...definitionWarnings],\n normalizedOperations: cumulativeOperations,\n },\n ...(this.#latestChangeSetId ? { supersedesChangeIds: [this.#latestChangeSetId] } : {}),\n });\n this.#operationWarnings = operationWarnings;\n this.#reportingTargets = reportingTargets;\n this.#draftOperations = registered.operations;\n this.#latestChangeSetId = registered.operations.length > 0 ? registered.id : undefined;\n const resolvedTargets = new Set([\n ...recoveryTargets,\n ...handledMutationRoutes.map(mutationRouteTarget),\n ]);\n for (const [changeSetId, unresolvedTargets] of this.#unresolvedCandidates) {\n for (const target of resolvedTargets) {\n if (target !== UNIDENTIFIED_MUTATION_TARGET && target !== SATISFIED_MUTATION_TARGET)\n unresolvedTargets.delete(target);\n }\n if (retryOfChangeIds.includes(changeSetId)) {\n unresolvedTargets.delete(SATISFIED_MUTATION_TARGET);\n if (delta.operations.length > 0) unresolvedTargets.delete(UNIDENTIFIED_MUTATION_TARGET);\n }\n if (unresolvedTargets.size === 0) {\n this.#unresolvedCandidates.delete(changeSetId);\n }\n }\n registered.pendingRepairs = this.#pendingRepairs();\n this.#candidates.set(registered.id, registered);\n return registered;\n }\n\n reject(\n candidate: SurveyChangeSet,\n addressedTargets: Iterable<string> = [],\n refinements: RecoveryTargetRefinement[] = [],\n ): SurveyChangeSet {\n this.#assertOpen();\n if (this.#candidates.has(candidate.id)) {\n throw new Error(`Survey change \"${candidate.id}\" was registered more than once.`);\n }\n\n const registered = surveyChangeSetSchema.parse({\n ...candidate,\n turnId: this.turnId,\n status: \"rejected\",\n validation: {\n ...candidate.validation,\n valid: false,\n },\n });\n this.#refineRecoveryTargets(refinements);\n const targets = new Set(addressedTargets);\n if (targets.size === 0) targets.add(UNIDENTIFIED_MUTATION_TARGET);\n this.#unresolvedCandidates.set(registered.id, targets);\n registered.pendingRepairs = this.#pendingRepairs();\n this.#candidates.set(registered.id, registered);\n return registered;\n }\n\n #refineRecoveryTargets(refinements: RecoveryTargetRefinement[]) {\n for (const refinement of refinements) {\n for (const unresolved of this.#unresolvedCandidates.values()) {\n let matched = false;\n for (const target of refinement.targets) matched = unresolved.delete(target) || matched;\n if (matched) unresolved.add(refinement.replacement);\n }\n }\n }\n\n #pendingRepairs(): NonNullable<SurveyChangeSet[\"pendingRepairs\"]> {\n return [...this.#unresolvedCandidates].map(([changeId, targets]) => ({\n changeId,\n targets: [...targets].filter(\n (target) => target !== UNIDENTIFIED_MUTATION_TARGET && target !== SATISFIED_MUTATION_TARGET,\n ),\n requiresExplicitRetry:\n targets.has(UNIDENTIFIED_MUTATION_TARGET) || targets.has(SATISFIED_MUTATION_TARGET),\n ...(targets.has(SATISFIED_MUTATION_TARGET) ? { allowsAcknowledgment: true } : {}),\n }));\n }\n\n finalize(\n status: SurveyAssistantTurnFinal[\"status\"],\n createdAt = new Date().toISOString(),\n details: Pick<SurveyAssistantTurnFinal, \"durationMs\" | \"startedAt\" | \"terminationReason\"> = {},\n ): SurveyAssistantTurnFinal {\n if (this.#final) {\n return this.#final;\n }\n\n const blockedChangeSetIds = [...this.#unresolvedCandidates.keys()];\n const canAuthorize =\n status === \"completed\" &&\n blockedChangeSetIds.length === 0 &&\n this.#latestChangeSetId !== undefined;\n this.#final = surveyAssistantTurnFinalSchema.parse({\n protocolVersion: SURVEY_ASSISTANT_PROTOCOL_VERSION,\n turnId: this.turnId,\n status,\n executableChangeSetIds: canAuthorize ? [this.#latestChangeSetId] : [],\n ...(blockedChangeSetIds.length > 0 ? { blockedChangeSetIds } : {}),\n ...details,\n createdAt,\n });\n return this.#final;\n }\n\n getCandidate(changeSetId: string): SurveyChangeSet | undefined {\n return this.#candidates.get(changeSetId);\n }\n\n get draftOperations(): readonly SurveyOperation[] {\n return this.#draftOperations;\n }\n\n get context(): SurveyAssistantEngineContext | undefined {\n return this.#context;\n }\n\n get final(): SurveyAssistantTurnFinal | null {\n return this.#final;\n }\n\n #assertOpen() {\n if (this.#final) {\n throw new Error(\"Cannot register a survey change after the turn was finalized.\");\n }\n }\n}\n","import type { SurveyAssistantCapabilitySet } from \"./capabilities\";\nimport {\n getContentPlainText,\n listLocalizationEntries,\n ownValue,\n setOwnValue,\n type FlowItem,\n} from \"@case-framework/survey-core\";\nimport type {\n SurveyAssistantTaskContext,\n SurveyAssistantTaskItemSummary,\n SurveyDocumentSnapshot,\n} from \"../protocol\";\nimport { createSurveyAssistantEngineContext } from \"./context\";\n\nexport type SurveyAssistantTaskPurpose =\n | \"suggest-response-name\"\n | \"suggest-response-settings\"\n | \"suggest-item-label\"\n | \"translate-content\";\n\nexport interface BuildSurveyAssistantTaskContextOptions {\n purpose: SurveyAssistantTaskPurpose;\n capabilities?: SurveyAssistantCapabilitySet;\n focusItemId?: string;\n focusSlotId?: string;\n slotIds?: readonly string[];\n sourceLocale?: string;\n targetLocales?: readonly string[];\n sourceTexts?: readonly string[];\n}\n\nconst MAX_RELATED_ITEMS = 48;\nconst MAX_SIBLING_ITEMS = 80;\nconst MAX_VISIBLE_TEXT_ENTRIES_PER_ITEM = 24;\nconst MAX_VISIBLE_TEXT_CHARS = 600;\nconst MAX_NAMING_EXAMPLES = 40;\nconst MAX_TRANSLATION_EXAMPLES = 60;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst getItemLabel = (item: FlowItem): string | undefined => {\n if (!isRecord(item.metadata)) return undefined;\n const label = item.metadata.itemLabel;\n return typeof label === \"string\" && label.trim().length > 0 ? label.trim() : undefined;\n};\n\nconst getCenteredNeighbors = <T>(values: readonly T[], focusIndex: number, limit: number): T[] => {\n if (focusIndex < 0 || limit < 1) return [];\n const windowSize = Math.min(values.length, limit + 1);\n const idealStart = focusIndex - Math.floor(limit / 2);\n const start = Math.min(Math.max(0, idealStart), values.length - windowSize);\n return values.slice(start, start + windowSize).filter((_, index) => start + index !== focusIndex);\n};\n\nexport const buildSurveyAssistantTaskContext = (\n snapshot: SurveyDocumentSnapshot,\n options: BuildSurveyAssistantTaskContextOptions,\n): SurveyAssistantTaskContext => {\n const engineContext = createSurveyAssistantEngineContext(snapshot, options.capabilities, {\n focusItemId: options.focusItemId,\n });\n const { inspection } = engineContext;\n const model = engineContext.model;\n const itemName = (id: string) => model.resolveItemEditorName(id, snapshot.ui.selectedLocale);\n const itemsById = new Map(snapshot.survey.surveyItems.map((item) => [item.id, item]));\n const parentById = new Map(\n inspection.outline.flatMap((item) =>\n item.parentId ? ([[item.itemId, item.parentId]] as const) : [],\n ),\n );\n const childIdsByParent = new Map<string, string[]>();\n for (const item of inspection.outline) {\n if (!item.parentId) continue;\n const childIds = childIdsByParent.get(item.parentId) ?? [];\n childIds.push(item.itemId);\n childIdsByParent.set(item.parentId, childIds);\n }\n const breadcrumbById = new Map(\n inspection.itemIndex.map((item) => [item.itemId, item.breadcrumb]),\n );\n\n const summarizeItem = (item: FlowItem): SurveyAssistantTaskItemSummary => {\n const allVisibleText: SurveyAssistantTaskItemSummary[\"visibleText\"] = [];\n let visibleTextValueTruncated = false;\n for (const entry of listLocalizationEntries(model, { itemIds: [item.id] })) {\n if (entry.ref.scope !== \"content\" || model.owners.get(entry.ref.ownerId)?.itemId !== item.id)\n continue;\n for (const [locale, content] of Object.entries(entry.contents)) {\n const text = content ? getContentPlainText(content).trim() : \"\";\n if (!text) continue;\n if (text.length > MAX_VISIBLE_TEXT_CHARS) visibleTextValueTruncated = true;\n allVisibleText.push({\n locale,\n ownerId: entry.ref.ownerId,\n role: entry.ref.role,\n text:\n text.length > MAX_VISIBLE_TEXT_CHARS\n ? `${text.slice(0, MAX_VISIBLE_TEXT_CHARS)}...`\n : text,\n });\n }\n }\n return {\n id: item.id,\n editorName: itemName(item.id),\n breadcrumb: breadcrumbById.get(item.id) ?? itemName(item.id),\n itemType: item.itemType,\n itemLabel: getItemLabel(item),\n visibleText: allVisibleText.slice(0, MAX_VISIBLE_TEXT_ENTRIES_PER_ITEM),\n visibleTextTruncated:\n allVisibleText.length > MAX_VISIBLE_TEXT_ENTRIES_PER_ITEM || visibleTextValueTruncated,\n };\n };\n\n const slots = model.slots.definitions;\n const requested = options.slotIds ?? (options.focusSlotId ? [options.focusSlotId] : []);\n const selectedSlots = slots.filter((slot) => requested.includes(slot.slotId));\n // Include each selected matrix's full family: changing a component affects every derived name.\n const matrixIds = new Set(\n selectedSlots.filter((slot) => slot.naming?.kind === \"matrix\").map((slot) => slot.elementId),\n );\n const result: SurveyAssistantTaskContext = {\n existingVariableNames: slots.map((slot) => slot.variableName),\n responseVariables: slots\n .filter((slot) => requested.includes(slot.slotId) || matrixIds.has(slot.elementId))\n .map((slot) => ({ ...slot })),\n responseOwners: [\n ...new Set(\n slots\n .filter((slot) => requested.includes(slot.slotId) || matrixIds.has(slot.elementId))\n .map((slot) => slot.itemId),\n ),\n ].map((id) => ({\n item: summarizeItem(itemsById.get(id)!),\n configuration: itemsById.get(id)!.config,\n content: Object.fromEntries(\n [...model.owners.values()]\n .filter((owner) => owner.itemId === id)\n .map((owner) => [\n owner.id,\n ownValue(\n ownValue(snapshot.survey.translations, snapshot.ui.selectedLocale)?.content,\n owner.id,\n ) ?? {},\n ]),\n ),\n })),\n document: {\n revision: snapshot.version.revision,\n contentHash: snapshot.version.contentHash,\n capabilityDigest: snapshot.version.capabilityDigest,\n },\n survey: {\n key: snapshot.survey.metadata?.surveyKey,\n locales: inspection.locales,\n itemCount: inspection.itemCount,\n selectedLocale: snapshot.ui.selectedLocale,\n },\n };\n\n const focusItem = options.focusItemId ? itemsById.get(options.focusItemId) : undefined;\n if (focusItem) {\n const parentId = parentById.get(focusItem.id);\n const parentItem = parentId ? itemsById.get(parentId) : undefined;\n const ancestorItems: FlowItem[] = [];\n const seenAncestorIds = new Set<string>();\n let ancestorId = parentId;\n while (ancestorId && !seenAncestorIds.has(ancestorId)) {\n seenAncestorIds.add(ancestorId);\n const ancestor = itemsById.get(ancestorId);\n if (!ancestor) break;\n ancestorItems.unshift(ancestor);\n ancestorId = parentById.get(ancestorId);\n }\n\n const siblingIds = parentItem ? (childIdsByParent.get(parentItem.id) ?? []) : [];\n const siblingItemCount = Math.max(0, siblingIds.length - 1);\n const siblingItems = getCenteredNeighbors(\n siblingIds,\n siblingIds.indexOf(focusItem.id),\n MAX_SIBLING_ITEMS,\n )\n .map((itemId) => itemsById.get(itemId))\n .filter((item): item is FlowItem => Boolean(item));\n const allRelatedItems: FlowItem[] = [];\n const seenRelatedIds = new Set<string>();\n const pending = [...(childIdsByParent.get(focusItem.id) ?? [])];\n while (pending.length > 0) {\n const itemId = pending.shift();\n const item = itemId ? itemsById.get(itemId) : undefined;\n if (!item || seenRelatedIds.has(item.id)) continue;\n seenRelatedIds.add(item.id);\n allRelatedItems.push(item);\n pending.push(...(childIdsByParent.get(item.id) ?? []));\n }\n const relatedItems = allRelatedItems.slice(0, MAX_RELATED_ITEMS);\n\n result.focus = {\n item: summarizeItem(focusItem),\n parent: parentItem ? summarizeItem(parentItem) : undefined,\n ancestorPath: ancestorItems.map(summarizeItem),\n siblingNames: siblingItems.map((item) => itemName(item.id)),\n siblingItems: siblingItems.map(summarizeItem),\n siblingItemCount,\n siblingItemsTruncated: siblingItemCount > siblingItems.length,\n relatedItems: relatedItems.map(summarizeItem),\n relatedItemCount: allRelatedItems.length,\n relatedItemsTruncated: allRelatedItems.length > relatedItems.length,\n };\n }\n\n if (\n (options.purpose === \"suggest-response-name\" ||\n options.purpose === \"suggest-response-settings\" ||\n options.purpose === \"suggest-item-label\") &&\n focusItem\n ) {\n const parentId = parentById.get(focusItem.id);\n const siblingIds = parentId ? (childIdsByParent.get(parentId) ?? []) : [];\n const siblingPositionById = new Map(siblingIds.map((itemId, index) => [itemId, index]));\n const focusSiblingPosition = siblingPositionById.get(focusItem.id);\n const rankedItems = snapshot.survey.surveyItems\n .filter((item) => item.id !== focusItem.id)\n .map((item, index) => ({\n item,\n index,\n siblingDistance:\n focusSiblingPosition !== undefined && siblingPositionById.has(item.id)\n ? Math.abs(siblingPositionById.get(item.id)! - focusSiblingPosition)\n : Number.POSITIVE_INFINITY,\n relationship:\n parentById.get(item.id) === parentId\n ? (\"sibling\" as const)\n : item.itemType === focusItem.itemType\n ? (\"same-type\" as const)\n : (\"survey\" as const),\n }))\n .sort((left, right) => {\n const rank = { sibling: 0, \"same-type\": 1, survey: 2 } as const;\n return (\n rank[left.relationship] - rank[right.relationship] ||\n left.siblingDistance - right.siblingDistance ||\n left.index - right.index\n );\n });\n const allKeyExamples = model.slots.definitions\n .filter((slot) => !requested.includes(slot.slotId) && !matrixIds.has(slot.elementId))\n .map((slot) => ({\n itemId: slot.itemId,\n itemType: itemsById.get(slot.itemId)!.itemType,\n key: slot.variableName,\n slotId: slot.slotId,\n relationship: \"survey\" as const,\n }));\n const allLabelExamples = rankedItems.flatMap(({ item, relationship }) => {\n const label = getItemLabel(item);\n return label\n ? [\n {\n itemId: item.id,\n itemType: item.itemType,\n key: itemName(item.id),\n label,\n relationship,\n },\n ]\n : [];\n });\n result.naming = {\n keyExamples: allKeyExamples.slice(0, MAX_NAMING_EXAMPLES),\n keyExampleCount: allKeyExamples.length,\n keyExamplesTruncated: allKeyExamples.length > MAX_NAMING_EXAMPLES,\n labelExamples: allLabelExamples.slice(0, MAX_NAMING_EXAMPLES),\n labelExampleCount: allLabelExamples.length,\n labelExamplesTruncated: allLabelExamples.length > MAX_NAMING_EXAMPLES,\n };\n }\n\n const sourceLocale = options.sourceLocale;\n if (options.purpose === \"translate-content\" && sourceLocale) {\n const relevantLocales = [sourceLocale, ...(options.targetLocales ?? [])];\n const sourceTokens = new Set(\n (options.sourceTexts ?? [])\n .flatMap((text) => text.toLocaleLowerCase().split(/[^\\p{L}\\p{N}]+/u))\n .filter((token) => token.length >= 3),\n );\n const allExamples: Array<{\n itemId: string;\n ownerId: string;\n role: string;\n values: Record<string, string>;\n score: number;\n order: number;\n }> = [];\n listLocalizationEntries(model, { sourceLocale }).forEach((entry, order) => {\n if (entry.ref.scope !== \"content\") return;\n const owner = model.owners.get(entry.ref.ownerId)!;\n const values: Record<string, string> = {};\n for (const locale of relevantLocales) {\n const content = ownValue(entry.contents, locale);\n const text = content ? getContentPlainText(content).trim() : \"\";\n if (text) setOwnValue(values, locale, text.slice(0, MAX_VISIBLE_TEXT_CHARS));\n }\n const sourceText = ownValue(values, sourceLocale);\n if (!sourceText || Object.keys(values).length < 2) return;\n const normalizedSource = sourceText.toLocaleLowerCase();\n const score = [...sourceTokens].reduce(\n (total, token) => total + (normalizedSource.includes(token) ? 1 : 0),\n 0,\n );\n allExamples.push({\n itemId: owner.itemId,\n ownerId: owner.id,\n role: entry.ref.role,\n values,\n score,\n order,\n });\n });\n allExamples.sort((left, right) => right.score - left.score || left.order - right.order);\n result.translation = {\n examples: allExamples\n .slice(0, MAX_TRANSLATION_EXAMPLES)\n .map(({ itemId, ownerId, role, values }) => ({ itemId, ownerId, role, values })),\n exampleCount: allExamples.length,\n examplesTruncated: allExamples.length > MAX_TRANSLATION_EXAMPLES,\n };\n }\n\n return result;\n};\n","export interface SurveyAssistantTaskResultCacheOptions {\n ttlMs?: number;\n maxEntries?: number;\n now?: () => number;\n}\n\ninterface TaskResultCacheEntry {\n expiresAt: number;\n value: unknown;\n}\n\nconst DEFAULT_TTL_MS = 15 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES = 64;\n\n/** Small in-memory LRU cache for deterministic, snapshot-scoped one-shot results. */\nexport class SurveyAssistantTaskResultCache {\n private readonly entries = new Map<string, TaskResultCacheEntry>();\n private readonly ttlMs: number;\n private readonly maxEntries: number;\n private readonly now: () => number;\n\n constructor(options: SurveyAssistantTaskResultCacheOptions = {}) {\n this.ttlMs = Math.max(0, options.ttlMs ?? DEFAULT_TTL_MS);\n this.maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_MAX_ENTRIES);\n this.now = options.now ?? Date.now;\n }\n\n get<TResult>(key: string): TResult | undefined {\n const entry = this.entries.get(key);\n if (!entry) return undefined;\n if (entry.expiresAt <= this.now()) {\n this.entries.delete(key);\n return undefined;\n }\n\n this.entries.delete(key);\n this.entries.set(key, entry);\n return entry.value as TResult;\n }\n\n set<TResult>(key: string, value: TResult): void {\n this.entries.delete(key);\n this.entries.set(key, { expiresAt: this.now() + this.ttlMs, value });\n while (this.entries.size > this.maxEntries) {\n const oldestKey = this.entries.keys().next().value;\n if (oldestKey === undefined) break;\n this.entries.delete(oldestKey);\n }\n }\n\n clear(): void {\n this.entries.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,sBACd,KACA,cACQ;CACR,MAAM,WAA4B,cAAc,YAAY;CAG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