@wildo-ai/dev-companion 1.1.14 → 1.1.15
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/dist/esm/.tsbuildinfo +1 -1
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts +68 -1
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.d.ts.map +1 -1
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js +77 -5
- package/dist/esm/claude-cli/models/coding-agent-dispatch.models.js.map +1 -1
- package/dist/esm/claude-cli/models/concurrent-coding-runs.models.d.ts +46 -1
- package/dist/esm/claude-cli/models/concurrent-coding-runs.models.d.ts.map +1 -1
- package/dist/esm/claude-cli/models/concurrent-coding-runs.models.js +39 -2
- package/dist/esm/claude-cli/models/concurrent-coding-runs.models.js.map +1 -1
- package/dist/esm/claude-cli/models/shared-tree-reconciliation.models.d.ts +6 -0
- package/dist/esm/claude-cli/models/shared-tree-reconciliation.models.d.ts.map +1 -1
- package/dist/esm/claude-cli/models/shared-tree-reconciliation.models.js.map +1 -1
- package/dist/esm/claude-cli/models/verification-tool-availability.models.d.ts +19 -5
- package/dist/esm/claude-cli/models/verification-tool-availability.models.d.ts.map +1 -1
- package/dist/esm/claude-cli/models/verification-tool-availability.models.js +17 -5
- package/dist/esm/claude-cli/models/verification-tool-availability.models.js.map +1 -1
- package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.d.ts +16 -1
- package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.d.ts.map +1 -1
- package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.js +44 -4
- package/dist/esm/claude-cli/services/accepted-change-commit.companion.service.js.map +1 -1
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts +79 -6
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.d.ts.map +1 -1
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js +291 -40
- package/dist/esm/claude-cli/services/coding-agent-dispatch.companion.service.js.map +1 -1
- package/dist/esm/claude-cli/services/research-evidence-store.companion.d.ts +14 -0
- package/dist/esm/claude-cli/services/research-evidence-store.companion.d.ts.map +1 -1
- package/dist/esm/claude-cli/services/research-evidence-store.companion.js +35 -0
- package/dist/esm/claude-cli/services/research-evidence-store.companion.js.map +1 -1
- package/dist/esm/claude-cli/services/unrecorded-provider-directories.companion.d.ts +36 -0
- package/dist/esm/claude-cli/services/unrecorded-provider-directories.companion.d.ts.map +1 -0
- package/dist/esm/claude-cli/services/unrecorded-provider-directories.companion.js +134 -0
- package/dist/esm/claude-cli/services/unrecorded-provider-directories.companion.js.map +1 -0
- package/dist/esm/core/introspection/services/translation-placement.companion.service.d.ts +3 -2
- package/dist/esm/core/introspection/services/translation-placement.companion.service.d.ts.map +1 -1
- package/dist/esm/core/introspection/services/translation-placement.companion.service.js.map +1 -1
- package/dist/esm/core/introspection/subprocess/companion-introspection-behavior-handlers.d.ts.map +1 -1
- package/dist/esm/core/introspection/subprocess/companion-introspection-behavior-handlers.js +24 -14
- package/dist/esm/core/introspection/subprocess/companion-introspection-behavior-handlers.js.map +1 -1
- package/dist/esm/core/introspection/workspace-element-index.companion.d.ts +42 -0
- package/dist/esm/core/introspection/workspace-element-index.companion.d.ts.map +1 -1
- package/dist/esm/core/introspection/workspace-element-index.companion.js +42 -0
- package/dist/esm/core/introspection/workspace-element-index.companion.js.map +1 -1
- package/dist/esm/core/runtime/dev-compile-quiet.companion.d.ts +53 -0
- package/dist/esm/core/runtime/dev-compile-quiet.companion.d.ts.map +1 -1
- package/dist/esm/core/runtime/dev-compile-quiet.companion.js +119 -2
- package/dist/esm/core/runtime/dev-compile-quiet.companion.js.map +1 -1
- package/dist/esm/core/runtime/services/start-companion-application.service.d.ts.map +1 -1
- package/dist/esm/core/runtime/services/start-companion-application.service.js +13 -1
- package/dist/esm/core/runtime/services/start-companion-application.service.js.map +1 -1
- package/dist/esm/core/runtime/utils/companion-platform-config.companion.d.ts +2 -2
- package/dist/esm/core/runtime/utils/companion-platform-config.companion.d.ts.map +1 -1
- package/dist/esm/core/runtime/utils/companion-platform-config.companion.js +6 -6
- package/dist/esm/core/runtime/utils/companion-platform-config.companion.js.map +1 -1
- package/dist/esm/email/services/email-template.companion.service.d.ts +5 -0
- package/dist/esm/email/services/email-template.companion.service.d.ts.map +1 -1
- package/dist/esm/email/services/email-template.companion.service.js +44 -11
- package/dist/esm/email/services/email-template.companion.service.js.map +1 -1
- package/dist/esm/email/utils/email-template-fs-discovery.utils.d.ts +26 -2
- package/dist/esm/email/utils/email-template-fs-discovery.utils.d.ts.map +1 -1
- package/dist/esm/email/utils/email-template-fs-discovery.utils.js +41 -2
- package/dist/esm/email/utils/email-template-fs-discovery.utils.js.map +1 -1
- package/dist/esm/email/utils/email-template-scanner-calls.companion.utils.d.ts +19 -0
- package/dist/esm/email/utils/email-template-scanner-calls.companion.utils.d.ts.map +1 -0
- package/dist/esm/email/utils/email-template-scanner-calls.companion.utils.js +171 -0
- package/dist/esm/email/utils/email-template-scanner-calls.companion.utils.js.map +1 -0
- package/dist/esm/email/utils/module-email-root.companion.utils.d.ts +75 -0
- package/dist/esm/email/utils/module-email-root.companion.utils.d.ts.map +1 -0
- package/dist/esm/email/utils/module-email-root.companion.utils.js +162 -0
- package/dist/esm/email/utils/module-email-root.companion.utils.js.map +1 -0
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.en.d.ts +1 -0
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.en.d.ts.map +1 -1
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.en.js +1 -0
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.en.js.map +1 -1
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.fr.d.ts +1 -0
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.fr.d.ts.map +1 -1
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.fr.js +1 -0
- package/dist/esm/i18n/components/LOW_LEVEL_AI_AGENT_CONFIG.fr.js.map +1 -1
- package/dist/esm/i18n/resources/workbenchAspects.en.d.ts.map +1 -1
- package/dist/esm/i18n/resources/workbenchAspects.en.js +4 -0
- package/dist/esm/i18n/resources/workbenchAspects.en.js.map +1 -1
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.d.ts +35 -0
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.d.ts.map +1 -1
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.js +12 -0
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.en.js.map +1 -1
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.fr.d.ts +536 -531
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.fr.d.ts.map +1 -1
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.fr.js +536 -531
- package/dist/esm/i18n/resources/workbenchSpecificationArtifacts.fr.js.map +1 -1
- package/dist/esm/i18n/system_enums/workbench-build.en.d.ts +2 -2
- package/dist/esm/i18n/system_enums/workbench-build.en.js +2 -2
- package/dist/esm/i18n/system_enums/workbench-build.en.js.map +1 -1
- package/dist/esm/i18n-labelling/services/email-template-labelling-units.companion.service.d.ts.map +1 -1
- package/dist/esm/i18n-labelling/services/email-template-labelling-units.companion.service.js +7 -3
- package/dist/esm/i18n-labelling/services/email-template-labelling-units.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/models/creation-journey-timeline.models.d.ts +9 -0
- package/dist/esm/meta-workflows/models/creation-journey-timeline.models.d.ts.map +1 -1
- package/dist/esm/meta-workflows/models/creation-journey-timeline.models.js +18 -2
- package/dist/esm/meta-workflows/models/creation-journey-timeline.models.js.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts +33 -6
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js +97 -19
- package/dist/esm/meta-workflows/services/application-build-dispatch.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.d.ts +21 -8
- package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.js +65 -12
- package/dist/esm/meta-workflows/services/application-build-follow-up-derivation.companion.js.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.d.ts +1 -1
- package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.js +48 -26
- package/dist/esm/meta-workflows/services/application-build-task-coding-policy.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/build-task-brief-application-facts.companion.d.ts +12 -0
- package/dist/esm/meta-workflows/services/build-task-brief-application-facts.companion.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/build-task-brief-application-facts.companion.js +30 -1
- package/dist/esm/meta-workflows/services/build-task-brief-application-facts.companion.js.map +1 -1
- package/dist/esm/meta-workflows/services/creation-run-report.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/creation-run-report.companion.service.js +12 -1
- package/dist/esm/meta-workflows/services/creation-run-report.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts +7 -0
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.js +81 -4
- package/dist/esm/meta-workflows/services/playbook-run.companion.service.js.map +1 -1
- package/dist/esm/meta-workflows/services/provider-registry-brief.companion.utils.d.ts +55 -1
- package/dist/esm/meta-workflows/services/provider-registry-brief.companion.utils.d.ts.map +1 -1
- package/dist/esm/meta-workflows/services/provider-registry-brief.companion.utils.js +157 -10
- package/dist/esm/meta-workflows/services/provider-registry-brief.companion.utils.js.map +1 -1
- package/dist/esm/module-layout/module-layout-convention.companion.d.ts +158 -0
- package/dist/esm/module-layout/module-layout-convention.companion.d.ts.map +1 -0
- package/dist/esm/module-layout/module-layout-convention.companion.js +272 -0
- package/dist/esm/module-layout/module-layout-convention.companion.js.map +1 -0
- package/dist/esm/module-layout/module-layout-inspection.companion.d.ts +42 -0
- package/dist/esm/module-layout/module-layout-inspection.companion.d.ts.map +1 -0
- package/dist/esm/module-layout/module-layout-inspection.companion.js +290 -0
- package/dist/esm/module-layout/module-layout-inspection.companion.js.map +1 -0
- package/dist/esm/module-layout/module-source-files.companion.d.ts +3 -0
- package/dist/esm/module-layout/module-source-files.companion.d.ts.map +1 -0
- package/dist/esm/module-layout/module-source-files.companion.js +45 -0
- package/dist/esm/module-layout/module-source-files.companion.js.map +1 -0
- package/package.json +17 -17
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-template.companion.service.js","sourceRoot":"","sources":["../../../../src/email/services/email-template.companion.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,wBAAwB,EAGxB,aAAa,EACb,0BAA0B,EAC1B,kBAAkB,EAElB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AAMpC,OAAO,EACL,sCAAsC,EACtC,qCAAqC,GACtC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,sBAAsB,EAEtB,qBAAqB,EACrB,iBAAiB,EACjB,SAAS,EACT,2BAA2B,EAC3B,iBAAiB,EAGj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AkC,CAAC,CAAA;IAElE,YAAA,MAAM,CAAC,uBAAuB,CAAC,4BAA4B,CAAC,CAAA;IAE5D,YAAA,MAAM,CAAC,uBAAuB,CAAC,2BAA2B,CAAC,CAAA;qCAnBA,aAAa;QACM,0BAA0B,4DAS3D,oCAAoC;QAE5C,4BAA4B;QAEzB,sCAAsC;QAEjC,2CAA2C;QAEjD,qCAAqC;QAErC,2CAA2C;GAxB1E,6BAA6B,CAglDzC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { render } from '@react-email/render';\nimport { injectable, inject } from 'inversify';\nimport {\n buildEmailBrandTokensFromConfig,\n mergeEmailComponentLabels,\n withEmailComponentLabels,\n type EmailTemplateDefinitionsMap,\n type EmailTemplateRegistryBackendService,\n LoggerService,\n ErrorBuilderBackendService,\n SAAS_SERVICE_TYPES,\n type AgentsBackendService,\n describeCaughtError,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n LLMProvider_GenerateTextInputSchema,\n LLMProvider_GenerateTextOutputSchema,\n LLMProvider_OperationContext_BaseSchema,\n} from '@wildo-ai/external-connectors-models';\nimport {\n getCompanionConfiguredFallbackLanguage,\n getCompanionConfiguredPrimaryLanguage,\n} from '../../core/config/primary-language.companion.utils';\nimport {\n applicationDisplayName,\n FlowsActors_Agent_Invocation,\n BrandAssetComposition,\n BrandAssetPurpose,\n ErrorType,\n ErrorCustomMessageReference,\n EmailTemplateType,\n type ObjectContext,\n type PrimaryScopeContext,\n EmailSubmissionOutcome,\n isWildoBackendError,\n} from '@wildo-ai/saas-models';\nimport { AvailableLanguage, LANGUAGE_INFO_MAP } from '@wildo-ai/presets-components-models';\nimport type { CompanionEmailTemplateOwnershipDescriptor } from '@wildo-ai/saas-models/companion';\nimport {\n resolveEmailTemplateArtifactTargets,\n labelsFilePath,\n readUtf8File,\n writeUtf8File,\n fileExists,\n templateFilePath,\n templateRefToRelativeDir,\n listTemplateRefsUnderEmailRoot,\n withDeliveredCanonEngineRefs,\n type EmailTemplateArtifactTarget,\n} from '../utils/email-template-fs-discovery.utils';\nimport { flattenEmailLabelsTree, parseEmailLabelsTreeSource } from '../utils/email-labels-tree.utils';\nimport { getCompanionEnabledLocaleCodes } from '../../core/config/primary-language.companion.utils';\nimport {\n parseEmailLabelsTsSource,\n formatLabelsTsFile,\n} from '../utils/email-labels-file-source.utils';\nimport { COMPANION_SERVICE_TYPES } from '../../core/inject/models/service-types';\nimport type { CompanionContext } from '../../core/context/companion-context';\nimport {\n loadBackendCompanionExports,\n resolvePrimaryBackendServiceTarget,\n assertSpecificationsReadWhole,\n} from '../../core/context/companion-package-loaders.companion';\nimport { TranslationPlacementCompanionService } from '../../core/introspection/services/translation-placement.companion.service';\nimport { CompanionTraceabilityService } from '../../core/traceability/companion-traceability.service';\nimport { EmailSpecContextLoaderCompanionService } from './email-spec-context-loader.companion.service';\nimport { ApplicationEmailWordSourcesCompanionService } from './application-email-word-sources.companion.service';\nimport { EmailTemplateLabellingUnitsCompanionService } from '../../i18n-labelling/services/email-template-labelling-units.companion.service';\nimport { TranslateOrchestratorCompanionService } from '../../i18n-labelling/services/translate-orchestrator.companion.service';\nimport { I18nUnitRunStatus } from '../../i18n-labelling/models/labelling-unit.models';\nimport {\n CompanionTraceabilityLevel,\n CompanionTraceArtifactFormat,\n type CompanionExecutionSessionContext,\n} from '../../core/traceability/companion-traceability.models';\n\n// Import email services - these are injected via DI, so we only need the types\nimport type { AppConfigurationService } from '@wildo-ai/saas-backend-lib';\nimport type { EmailBackendService } from '@wildo-ai/saas-backend-lib';\nimport type { EmailTemplateValidatorBackendService } from '@wildo-ai/saas-backend-lib';\nimport type { LabellingProgressReporter } from '../../i18n-labelling/models/labelling-progress.models';\n\n/**\n * The framework's ENGINE email templates as an application receives them — `templates/saas/i18n/email`,\n * harvested from Wonder Todos and delivered into every application's `.wildo-saas/templates/`.\n */\nconst DELIVERED_EMAIL_CANON_RELATIVE = '.wildo-saas/templates/i18n/email' as const;\n\n/** Partial authoring-only object context; nested scope overrides retain synthetic defaults. */\nexport type EmailTemplateMockObjectContext = Omit<Partial<ObjectContext>, 'primaryScopeContext'> & {\n primaryScopeContext?: Partial<PrimaryScopeContext>;\n};\n\n/**\n * Request for generating email templates\n */\nexport interface GenerateEmailTemplatesRequest {\n /** Force regenerate even if template exists */\n forceRegenerate?: boolean;\n /** Specific template refs to generate (empty = all) */\n templateRefs?: string[];\n /** Specific locales to generate (empty = all configured) */\n locales?: AvailableLanguage[];\n}\n\n/**\n * Request for previewing an email template\n */\nexport interface PreviewEmailTemplateRequest {\n templateRef: string;\n locale: AvailableLanguage;\n /** Mock context data for preview */\n mockContext?: {\n currentObject?: Record<string, unknown>;\n objectContext?: EmailTemplateMockObjectContext;\n userContext?: {\n email: string;\n name?: string;\n firstName?: string;\n };\n additionalContext?: Record<string, unknown>;\n };\n}\n\n/**\n * Preview result\n */\nexport interface PreviewEmailTemplateResult {\n templateRef: string;\n locale: AvailableLanguage;\n resolvedLocale?: string;\n subject: string;\n bodyHtml: string;\n bodyText?: string;\n previewedAt: string;\n}\n\n/**\n * Request for sending a test email\n */\nexport interface TestSendEmailRequest {\n templateRef: string;\n locale: AvailableLanguage;\n /** Recipient email address for test */\n recipientEmail: string;\n /** Mock context data for test */\n mockContext?: {\n currentObject?: Record<string, unknown>;\n objectContext?: EmailTemplateMockObjectContext;\n userContext?: {\n email: string;\n name?: string;\n firstName?: string;\n };\n additionalContext?: Record<string, unknown>;\n };\n}\n\n/**\n * Test send result\n */\nexport interface TestSendEmailResult {\n success: boolean;\n submissionId: string;\n outcome: EmailSubmissionOutcome;\n retryable: boolean;\n deduplicated?: boolean;\n templateRef: string;\n locale: AvailableLanguage;\n recipientEmail: string;\n /** All provider receipts returned for the test submission. */\n providerMessageIds: string[];\n error?: string;\n sentAt: string;\n}\n\n/**\n * Template status result\n */\nexport interface EmailTemplateStatusResult {\n ownerId: string;\n templateRef: string;\n templatePath: string;\n templateExists: boolean;\n locales: Array<{\n locale: string;\n labelsPath: string;\n exists: boolean;\n updatedAt: string;\n }>;\n}\n\n/**\n * Translate filesystem `labels.{primaryLocale}.ts` → `labels.{targetLocale}.ts` for each template directory.\n *\n * The source locale is always the SaaS application's configured primary\n * language from `appPreferences.languages.defaultLanguage`.\n */\nexport interface TranslateEmailTemplateLabelsRequest {\n /** Target locale codes (e.g. fr, de) — must match `AvailableLanguage` enum values */\n targetLocales: string[];\n /** Limit to specific registry template refs; omit for all */\n templateRefs?: string[];\n /** When true, only report planned writes (no LLM, no disk writes) */\n dryRun?: boolean;\n}\n\nexport interface TranslateEmailTemplateLabelsResult {\n translatedFiles: number;\n skipped: number;\n failed: number;\n warnings: string[];\n details: Array<{\n ownerId: string;\n templateRef: string;\n targetLocale: string;\n success: boolean;\n outputPath?: string;\n error?: string;\n }>;\n completedAt: string;\n}\n\nexport interface GenerateEmailTemplatesResult {\n generated: number;\n skipped: number;\n failed: number;\n warnings: string[];\n details: Array<{\n ownerId: string;\n templateRef: string;\n locale: AvailableLanguage;\n success: boolean;\n skipped?: boolean;\n /** The template was copied from the delivered engine canon this run, with no model call (#3156). */\n seededFromCanon?: boolean;\n templatePath?: string;\n labelsPath?: string;\n errors?: string[];\n }>;\n generatedAt: string;\n}\n\ninterface GeneratedEmailTemplateBundle {\n templateSource: string;\n labels: Record<string, string>;\n}\n\nfunction formatUnknownError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (typeof error === 'object' && error !== null) {\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n\n return String(error);\n}\n\n/**\n * Email Template Companion Service\n * \n * Handles email template generation, preview, and testing operations\n * for the dev companion API.\n */\n@injectable()\nexport class EmailTemplateCompanionService {\n private readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.AgentsBackendService) private readonly agentsService: AgentsBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_SERVICE_TYPES.EmailTemplateValidator) private readonly emailTemplateValidator: EmailTemplateValidatorBackendService,\n @inject(SAAS_SERVICE_TYPES.EmailTemplateRegistry) private readonly emailTemplateRegistry: EmailTemplateRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.EmailService) private readonly emailService: EmailBackendService,\n @inject(COMPANION_SERVICE_TYPES.CompanionContext)\n private readonly companionContext: CompanionContext,\n @inject(COMPANION_SERVICE_TYPES.TranslationPlacementService)\n private readonly translationPlacementService: TranslationPlacementCompanionService,\n @inject(COMPANION_SERVICE_TYPES.TraceabilityService)\n private readonly traceabilityService: CompanionTraceabilityService,\n @inject(COMPANION_SERVICE_TYPES.EmailSpecContextLoader)\n private readonly emailSpecContextLoader: EmailSpecContextLoaderCompanionService,\n @inject(COMPANION_SERVICE_TYPES.EmailTemplateLabellingUnitsService)\n private readonly emailTemplateLabellingUnits: EmailTemplateLabellingUnitsCompanionService,\n @inject(COMPANION_SERVICE_TYPES.TranslateOrchestratorService)\n private readonly translateOrchestrator: TranslateOrchestratorCompanionService,\n @inject(COMPANION_SERVICE_TYPES.ApplicationEmailWordSources)\n private readonly applicationEmailWords: ApplicationEmailWordSourcesCompanionService,\n ) {\n this.logDebug = this.logger.debugByType('EmailTemplateCompanion');\n this.logger.setDebugTypeLogging('EmailTemplateCompanion', true);\n }\n\n /**\n * Generate primary-locale filesystem email template artifacts using LLM.\n */\n async generateTemplates(\n request: GenerateEmailTemplatesRequest,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<GenerateEmailTemplatesResult> {\n // The prompts are built from the package: a short read rewrites a template from less than it had (#3258).\n await assertSpecificationsReadWhole(this.companionContext, 'The email templates');\n this.logDebug('Generating email templates...', { request });\n const traceStep = this.createWrapperTraceStep(sessionContext, 'generate-templates');\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-generation-wrapper-start',\n 'Generate email templates',\n {\n forceRegenerate: request.forceRegenerate === true,\n templateRefs: request.templateRefs ?? [],\n locales: request.locales ?? [],\n },\n 'email-template-generation-wrapper-request.json',\n request,\n );\n\n try {\n const primaryLocale = this.resolvePrimaryGenerationLocale(request.locales);\n const snapshot = await this.translationPlacementService.getPlacementSnapshot({\n includeShared: false,\n includeFrontend: false,\n includeBackendEmail: true,\n });\n const ownership = await this.emailTemplateOwnershipWithCanon(snapshot.backendEmail);\n const targets = resolveEmailTemplateArtifactTargets(\n this.getWorkspaceRoot(),\n ownership,\n request.templateRefs,\n );\n this.assertResolvedEmailTargetsOrThrow(targets, snapshot.warnings, request.templateRefs);\n\n const details: GenerateEmailTemplatesResult['details'] = [];\n const runWarnings: string[] = [];\n let generated = 0;\n let skipped = 0;\n let failed = 0;\n\n for (const target of targets) {\n const labelsPath = labelsFilePath(target.dirPath, primaryLocale);\n\n try {\n let hasTemplate = await fileExists(target.templatePath);\n /*\n * A template the application does not have is copied from the canon, forced or not (#3156): a forced run\n * regenerates the application's OWN templates, and one it does not hold yet is the engine's, the same in\n * every application, so paying a model call for it is the cost the canon exists to avoid. A just-copied\n * template is then delivered as it stands.\n */\n const seededFromCanon = !hasTemplate && await this.seedTemplateFromDeliveredCanon(target);\n hasTemplate = hasTemplate || seededFromCanon;\n const hasLabels = await fileExists(labelsPath);\n const existingLabels = hasLabels ? await this.tryReadExistingLabels(labelsPath) : null;\n /*\n * Engine templates key some words by a vocabulary (`stages.<stage>.subject`), which the FLAT reader refuses.\n * Reading that as \"no words\" sent a template that has its words to the flat generator, whose rewrite the import\n * validator refused (measured on Wonder Procurement, #3156: three system templates failed on every run). Such\n * a file is read with the keyed reader the translate lane uses; a file NEITHER reader parses is a failure that\n * names the file, never words and never wordless.\n */\n const keyedWordCount = hasLabels && existingLabels === null ? await this.countKeyedLabelWords(labelsPath) : null;\n if (hasLabels && existingLabels === null && keyedWordCount === null) {\n throw new Error(`Cannot read the words in ${labelsPath}: neither the flat nor the keyed labels reader parses it.`);\n }\n const hasWords = existingLabels !== null ? Object.keys(existingLabels).length > 0 : (keyedWordCount ?? 0) > 0;\n // The flat generator cannot write words keyed by a vocabulary, so even a forced run keeps them (and says so).\n const keyedWordsKept = request.forceRegenerate === true && !seededFromCanon && hasTemplate && (keyedWordCount ?? 0) > 0;\n if (keyedWordsKept) {\n runWarnings.push(`${target.templateRef}: kept as it stands; its words are keyed by a vocabulary, which the generator cannot write (edit ${labelsPath} by hand).`);\n }\n\n if (\n ((!request.forceRegenerate || seededFromCanon) || keyedWordsKept)\n && hasTemplate\n && hasWords\n ) {\n skipped++;\n details.push({\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n locale: primaryLocale,\n success: true,\n skipped: true,\n ...(seededFromCanon ? { seededFromCanon: true } : {}),\n templatePath: target.templatePath,\n labelsPath,\n });\n continue;\n }\n\n const currentTemplateSource = hasTemplate\n ? await readUtf8File(target.templatePath)\n : null;\n const labelsTypeName = this.buildLabelsTypeName(target.templateRef);\n const generatedBundle = await this.generateTemplateArtifactsWithAgent({\n templateRef: target.templateRef,\n locale: primaryLocale,\n labelsTypeName,\n currentTemplateSource,\n existingLabels: existingLabels ?? undefined,\n }, sessionContext);\n this.assertTemplateLabelsConsistencyOrThrow(\n generatedBundle.templateSource,\n generatedBundle.labels,\n );\n\n const validation = await this.emailTemplateValidator.validate(generatedBundle.templateSource);\n if (!validation.valid) {\n throw new Error(validation.errors.join(', '));\n }\n\n await writeUtf8File(target.templatePath, this.normalizeGeneratedTemplateSource(generatedBundle.templateSource));\n await writeUtf8File(\n labelsPath,\n formatLabelsTsFile({\n localeCode: primaryLocale,\n localeDisplayName: LANGUAGE_INFO_MAP[primaryLocale]?.name ?? primaryLocale,\n isPrimaryLocale: true,\n entries: generatedBundle.labels,\n labelsTypeName,\n usesAsConst: true,\n }),\n );\n\n generated++;\n details.push({\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n locale: primaryLocale,\n success: true,\n templatePath: target.templatePath,\n labelsPath,\n });\n } catch (error) {\n failed++;\n details.push({\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n locale: primaryLocale,\n success: false,\n templatePath: target.templatePath,\n labelsPath,\n errors: [formatUnknownError(error)],\n });\n }\n }\n\n // No registry refresh here (#3268): only a preview and a test send read the registry, and each refreshes it first.\n // Refreshing after a generation step re-imported the backend's companion graph into this process during a wave.\n\n const result = {\n generated,\n skipped,\n failed,\n warnings: [...snapshot.warnings, ...runWarnings],\n details,\n generatedAt: new Date().toISOString(),\n };\n const completedWithFailures = failed > 0;\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n completedWithFailures\n ? 'email-template-generation-wrapper-mixed-result'\n : 'email-template-generation-wrapper-success',\n completedWithFailures\n ? `Generated email templates for ${generated} targets with ${failed} failures`\n : `Generated email templates for ${generated} targets`,\n {\n generated,\n skipped,\n failed,\n warningCount: snapshot.warnings.length,\n },\n 'email-template-generation-wrapper-result.json',\n result,\n );\n return result;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-generation-wrapper-failure',\n 'Email template generation failed',\n error,\n {\n forceRegenerate: request.forceRegenerate === true,\n templateRefs: request.templateRefs ?? [],\n locales: request.locales ?? [],\n },\n );\n throw error;\n }\n }\n\n /**\n * Preview and test-send share the application's email logo resolver. Their synthetic names,\n * object ids and recipients remain distinct. Scope overrides merge over branding/defaults;\n * other object-context fields (parents and operation) survive without replacing that scope.\n * This is an authoring context, not a replay of a notification producer's real resource context.\n */\n private buildMockObjectContext(defaultScope: PrimaryScopeContext, overrides?: EmailTemplateMockObjectContext): ObjectContext {\n return {\n ...overrides,\n primaryScopeContext: {\n ...defaultScope,\n logoUrl: this.appConfigService.resolveBrandLogoAbsoluteUrl({\n composition: BrandAssetComposition.LOCKUP,\n purpose: BrandAssetPurpose.EMAIL,\n }) ?? undefined,\n ...overrides?.primaryScopeContext,\n },\n };\n }\n\n /**\n * Preview an email template with mock context\n */\n async previewTemplate(\n request: PreviewEmailTemplateRequest,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<PreviewEmailTemplateResult> {\n this.logDebug('Previewing email template...', { \n templateRef: request.templateRef, \n locale: request.locale,\n });\n\n const traceStep = this.createWrapperTraceStep(sessionContext, `preview-${request.templateRef}`);\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-preview-start',\n `Preview email template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n },\n 'email-template-preview-request.json',\n request,\n );\n\n try {\n\n await this.refreshEmailTemplateRegistry();\n const resolved = this.emailTemplateRegistry.resolve(\n request.templateRef,\n request.locale,\n this.getDefaultLocale(),\n this.getFallbackLocale(),\n );\n\n const defaultUserContext = {\n userId: 'preview-user-id',\n email: 'preview@example.com',\n name: 'Preview User',\n firstName: 'Preview',\n };\n \n const mockContext = {\n currentObject: request.mockContext?.currentObject || { _id: 'preview-id', title: 'Preview Object' },\n objectContext: this.buildMockObjectContext({\n appName: 'Preview App', applicationId: 'preview-app-id', organizationName: 'Preview Organization',\n }, request.mockContext?.objectContext),\n userContext: request.mockContext?.userContext \n ? { userId: 'preview-user-id', ...request.mockContext.userContext }\n : defaultUserContext,\n additionalContext: request.mockContext?.additionalContext || {},\n };\n\n const brandTokens = this.getDesignTokens();\n const templateProps = {\n context: mockContext,\n brand: brandTokens,\n labels: resolved.labels,\n locale: resolved.resolvedLocale,\n // An enum value's word, from the same label tree and cascade a send uses (#2884).\n fieldValueWord: this.emailService.fieldValueWordFor(resolved.resolvedLocale),\n providerName: this.emailService.providerNameFor(resolved.resolvedLocale),\n vocabularyWord: this.emailService.vocabularyWordFor(resolved.resolvedLocale),\n };\n\n const subject = resolved.definition.subject(templateProps);\n // As a send renders it: the shared components read their words in the language the template resolved in (#2884).\n const bodyElement = withEmailComponentLabels(\n resolved.definition.body(templateProps),\n this.emailTemplateRegistry.resolveComponentWords(resolved.resolvedLocale),\n );\n const bodyHtml = await render(bodyElement, { pretty: true });\n const bodyText = await render(bodyElement, { plainText: true });\n\n const previewResult = {\n templateRef: request.templateRef,\n locale: request.locale,\n resolvedLocale: resolved.resolvedLocale,\n subject,\n bodyHtml,\n bodyText,\n previewedAt: new Date().toISOString(),\n };\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-preview-success',\n `Previewed email template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n resolvedLocale: resolved.resolvedLocale ?? null,\n },\n 'email-template-preview-result.json',\n previewResult,\n );\n return previewResult;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-preview-failure',\n `Failed to preview email template ${request.templateRef}`,\n error,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n },\n );\n if (isWildoBackendError(error) || (error as { customMessageReference?: unknown })?.customMessageReference) {\n throw error;\n }\n\n this.logger.error('Failed to preview email template', {\n templateRef: request.templateRef,\n locale: request.locale,\n error: formatUnknownError(error),\n });\n\n throw this.errorBuilder.buildFromStandardError(error, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: { operation: 'previewTemplate' },\n });\n }\n }\n\n /**\n * Send a test email using a template\n */\n async testSend(\n request: TestSendEmailRequest,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<TestSendEmailResult> {\n this.logDebug('Sending test email...', {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n });\n\n const traceStep = this.createWrapperTraceStep(sessionContext, `test-send-${request.templateRef}`);\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-test-send-start',\n `Send test email for template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n },\n 'email-template-test-send-request.json',\n request,\n );\n\n const submissionId = randomUUID();\n let submissionAttempted = false;\n let sendResult: TestSendEmailResult | undefined;\n try {\n\n await this.refreshEmailTemplateRegistry();\n const defaultUserContext = {\n userId: 'test-user-id',\n email: request.recipientEmail,\n name: 'Test User',\n firstName: 'Test',\n };\n \n const context = {\n currentObject: request.mockContext?.currentObject || { _id: 'test-id', title: 'Test Object' },\n objectContext: this.buildMockObjectContext({\n appName: 'Test App', applicationId: 'test-app-id', organizationName: 'Test Organization',\n }, request.mockContext?.objectContext),\n userContext: request.mockContext?.userContext \n ? { userId: 'test-user-id', ...request.mockContext.userContext }\n : defaultUserContext,\n additionalContext: request.mockContext?.additionalContext || {},\n };\n\n submissionAttempted = true;\n const result = await this.emailService.send({\n submissionId,\n templateRef: request.templateRef,\n locale: request.locale,\n type: EmailTemplateType.TRANSACTIONAL,\n to: request.recipientEmail,\n context,\n });\n\n sendResult = {\n success: result.success,\n submissionId: result.submissionId,\n outcome: result.outcome,\n retryable: result.retryable,\n deduplicated: result.deduplicated,\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n providerMessageIds: result.providerMessageIds,\n error: result.error,\n sentAt: new Date().toISOString(),\n };\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-test-send-success',\n `Completed test email attempt for template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n success: result.success,\n },\n 'email-template-test-send-result.json',\n sendResult,\n );\n return sendResult;\n } catch (error) {\n // Reporting failures cannot erase or contradict the sender's already-known outcome.\n if (sendResult) {\n this.logger.error('Failed to record test email trace', {\n submissionId: sendResult.submissionId,\n outcome: sendResult.outcome,\n providerMessageIds: sendResult.providerMessageIds,\n error: formatUnknownError(error),\n });\n return sendResult;\n }\n this.logger.error('Failed to send test email', {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n providerMessageIds: [],\n error: formatUnknownError(error),\n });\n\n const failureResult: TestSendEmailResult = {\n success: false,\n submissionId,\n outcome: submissionAttempted ? EmailSubmissionOutcome.ACCEPTANCE_UNKNOWN : EmailSubmissionOutcome.NOT_SUBMITTED,\n retryable: submissionAttempted,\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n providerMessageIds: [],\n error: formatUnknownError(error),\n sentAt: new Date().toISOString(),\n };\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-test-send-failure',\n `Failed to send test email for template ${request.templateRef}`,\n error,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n },\n );\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-test-send-result',\n `Recorded failed test email result for template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n success: false,\n },\n 'email-template-test-send-result.json',\n failureResult,\n );\n return failureResult;\n }\n }\n\n /**\n * Get filesystem-backed status of email template artifacts.\n */\n /**\n * The app-root-relative files the email-template pipelines are responsible for, for the given\n * locales: one `template.tsx` per owned template plus one `labels.<locale>.ts` per locale.\n *\n * This is the email domain's HALF of the build lane's landed-evidence contract: PLACEMENT — which\n * directory, which file names — is this domain's single authority (`resolveEmailTemplateArtifactTargets`\n * + `templateFilePath`/`labelsFilePath`), while the build lane owns what \"landed\" means (every path\n * committed in git). Derived from the live placement snapshot, so the set is re-derivable after a\n * restart, a fresh clone, or a branch switch — never a stored list.\n */\n async resolveExpectedArtifactRelativePaths(locales: readonly string[]): Promise<readonly string[]> {\n const snapshot = await this.translationPlacementService.getPlacementSnapshot({\n includeShared: false,\n includeFrontend: false,\n includeBackendEmail: true,\n });\n const ownership = snapshot.backendEmail.flatMap((entry) => entry.emailTemplateOwnership);\n const workspaceRoot = this.getWorkspaceRoot();\n const targets = resolveEmailTemplateArtifactTargets(workspaceRoot, ownership);\n return targets\n .flatMap((target) => [target.templatePath, ...locales.map((locale) => labelsFilePath(target.dirPath, locale))])\n .map((absolutePath) => path.relative(workspaceRoot, absolutePath).split(path.sep).join(path.posix.sep));\n }\n\n async getTemplateStatus(\n templateRefs?: string[],\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<EmailTemplateStatusResult[]> {\n this.logDebug('Getting template status...', { templateRefs });\n const traceStep = this.createWrapperTraceStep(sessionContext, 'status');\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-status-start',\n 'Get email template status',\n {\n templateRefs: templateRefs ?? [],\n },\n 'email-template-status-request.json',\n { templateRefs },\n );\n\n try {\n const snapshot = await this.translationPlacementService.getPlacementSnapshot({\n includeShared: false,\n includeFrontend: false,\n includeBackendEmail: true,\n });\n // Status lists what generation would deliver, the engine notices the application lacks included (#3156).\n const ownership = await this.emailTemplateOwnershipWithCanon(snapshot.backendEmail);\n const targets = resolveEmailTemplateArtifactTargets(\n this.getWorkspaceRoot(),\n ownership,\n templateRefs,\n );\n this.assertResolvedEmailTargetsOrThrow(targets, snapshot.warnings, templateRefs);\n\n const statusResults = await Promise.all(\n targets.map(async (target) => {\n const templateExists = await fileExists(target.templatePath);\n const localeStatuses = await this.getTemplateLocaleStatuses(target.dirPath);\n\n return {\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n templatePath: target.templatePath,\n templateExists,\n locales: localeStatuses,\n } satisfies EmailTemplateStatusResult;\n }),\n );\n\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-status-success',\n `Resolved status for ${statusResults.length} email templates`,\n {\n templateRefs: templateRefs ?? [],\n resultCount: statusResults.length,\n },\n 'email-template-status-result.json',\n statusResults,\n );\n return statusResults;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-status-failure',\n 'Failed to resolve email template status',\n error,\n {\n templateRefs: templateRefs ?? [],\n },\n );\n this.logger.error('Failed to get template status', {\n error: formatUnknownError(error),\n });\n\n if (isWildoBackendError(error)) {\n throw error;\n }\n throw this.errorBuilder.buildFromStandardError(error, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: { operation: 'getTemplateStatus' },\n });\n }\n }\n\n /**\n * Translate owner-scoped email `labels.{source}.ts` files into\n * `labels.{target}.ts` using the companion labelling translation agent.\n *\n * Reads the app package root from the resolved `CompanionContext.saasRoot`\n * snapshot — the companion trusts the context established at bootstrap and\n * does not consult `process.env.COMPANION_WORKSPACE_ROOT` at runtime.\n */\n async translateEmailTemplateLabels(\n request: TranslateEmailTemplateLabelsRequest,\n sessionContext?: CompanionExecutionSessionContext,\n /** In-process only, never part of the request body: the build step's progress port (#2215). */\n options?: { readonly progress?: LabellingProgressReporter },\n ): Promise<TranslateEmailTemplateLabelsResult> {\n const traceStep = this.createWrapperTraceStep(sessionContext, 'translate-email-template-labels');\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-label-translation-wrapper-start',\n 'Translate email template labels',\n {\n primaryLocale: this.getDefaultLocale(),\n targetLocales: request.targetLocales ?? [],\n templateRefs: request.templateRefs ?? [],\n dryRun: request.dryRun === true,\n },\n 'email-label-translation-wrapper-request.json',\n request,\n );\n\n try {\n const primaryLocale = this.getDefaultLocale();\n const targetLocales = [...new Set(request.targetLocales ?? [])];\n\n if (!Array.isArray(targetLocales) || targetLocales.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { message: 'targetLocales is required and must be a non-empty array' },\n });\n }\n\n const resolvedTargets = targetLocales.map((code) => this.parseAvailableLanguageOrThrow(code));\n\n for (const t of resolvedTargets) {\n if (t === primaryLocale) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { message: `targetLocales must not include the primary locale (${primaryLocale})` },\n });\n }\n }\n\n /*\n * One translator for email words, not two (#1908). This method used to carry its own: it read\n * only FLAT label files (so it threw on every template keyed by stage or alert type), kept no\n * freshness state (so each run re-translated every email), checked no placeholder, and wrote\n * files the `wildo generate translate` lane knew nothing about. It now plans and runs that lane,\n * so `wildo generate email translate`, the email generation step and `wildo generate translate`\n * write the same files under the same lock and the same contract.\n */\n const plan = await this.emailTemplateLabellingUnits.planEmailTemplateUnits(request.templateRefs);\n this.assertResolvedEmailTargetsOrThrow(plan.units, plan.warnings, request.templateRefs);\n\n const details: TranslateEmailTemplateLabelsResult['details'] = [];\n let translatedFiles = 0;\n let skipped = 0;\n let failed = 0;\n\n if (request.dryRun) {\n for (const unit of plan.units) {\n for (const targetLocale of resolvedTargets) {\n details.push({\n ownerId: unit.ownerId,\n templateRef: unit.templateRef,\n targetLocale,\n success: true,\n outputPath: labelsFilePath(unit.templateDirectory, targetLocale),\n });\n translatedFiles++;\n }\n }\n } else {\n const run = await this.translateOrchestrator.translateEmailTemplates(\n {\n targetLocales: resolvedTargets,\n ...(request.templateRefs?.length ? { templateRefs: request.templateRefs } : {}),\n ...(options?.progress ? { progress: options.progress } : {}),\n },\n sessionContext,\n );\n const unitsById = new Map(plan.units.map((unit) => [unit.id, unit]));\n for (const detail of run.details) {\n const unit = unitsById.get(detail.unitId);\n const succeeded = detail.status === I18nUnitRunStatus.UPDATED || detail.status === I18nUnitRunStatus.FRESH;\n if (detail.status === I18nUnitRunStatus.UPDATED) translatedFiles++;\n else if (detail.status === I18nUnitRunStatus.FRESH || detail.status === I18nUnitRunStatus.SKIPPED) skipped++;\n else failed++;\n details.push({\n ownerId: unit?.ownerId ?? '',\n templateRef: unit?.templateRef ?? detail.unitId,\n targetLocale: detail.targetLocale,\n success: succeeded || detail.status === I18nUnitRunStatus.SKIPPED,\n ...(detail.filePath ? { outputPath: detail.filePath } : {}),\n ...(detail.error ? { error: detail.error } : {}),\n });\n }\n // No registry refresh (#3268): see `generateTemplates`. A preview or a test send refreshes before it reads.\n }\n\n const result = {\n translatedFiles,\n skipped,\n failed,\n warnings: plan.warnings,\n details,\n completedAt: new Date().toISOString(),\n };\n const completedWithFailures = failed > 0;\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n completedWithFailures\n ? 'email-label-translation-wrapper-mixed-result'\n : 'email-label-translation-wrapper-success',\n completedWithFailures\n ? `Translated ${translatedFiles} email label files with ${failed} failures`\n : `Translated ${translatedFiles} email label files`,\n {\n translatedFiles,\n skipped,\n failed,\n warningCount: plan.warnings.length,\n },\n 'email-label-translation-wrapper-result.json',\n result,\n );\n return result;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-label-translation-wrapper-failure',\n 'Email label translation failed',\n error,\n {\n primaryLocale: this.getDefaultLocale(),\n targetLocales: request.targetLocales ?? [],\n templateRefs: request.templateRefs ?? [],\n dryRun: request.dryRun === true,\n },\n );\n throw error;\n }\n }\n\n private resolvePrimaryGenerationLocale(requestedLocales?: AvailableLanguage[]): AvailableLanguage {\n const resolvedDefault = this.getDefaultLocale();\n\n if (!requestedLocales?.length) {\n return resolvedDefault;\n }\n\n const resolvedRequested = requestedLocales.map((locale) =>\n this.parseAvailableLanguageOrThrow(locale),\n );\n\n if (resolvedRequested.some((locale) => locale !== resolvedDefault)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Email generation only writes the primary locale (${resolvedDefault}). Use /email-templates/translate for additional locales.`,\n },\n });\n }\n\n return resolvedDefault;\n }\n\n /**\n * How many non-empty words a labels file holds, read with the KEYED reader (`parseEmailLabelsTreeSource`, the one the\n * translate lane uses), or `null` when that reader cannot parse it either (#3156).\n */\n private async countKeyedLabelWords(labelsPath: string): Promise<number | null> {\n try {\n const { tree } = parseEmailLabelsTreeSource(await readUtf8File(labelsPath));\n return Object.values(flattenEmailLabelsTree(tree)).filter((word) => word.trim() !== '').length;\n } catch {\n return null;\n }\n }\n\n private async tryReadExistingLabels(\n labelsPath: string,\n ): Promise<Record<string, string> | null> {\n try {\n const source = await readUtf8File(labelsPath);\n return parseEmailLabelsTsSource(source).entries;\n } catch {\n return null;\n }\n }\n\n private buildLabelsTypeName(templateRef: string): string {\n const normalized = templateRef\n .replace(/^system\\./, '')\n .replace(/^email\\./, '')\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n\n return `${normalized || 'Template'}Labels`;\n }\n\n private normalizeGeneratedTemplateSource(templateSource: string): string {\n return templateSource.trimEnd() + '\\n';\n }\n\n private assertTemplateLabelsConsistencyOrThrow(\n templateSource: string,\n labels: Record<string, string>,\n ): void {\n const referencedKeys = new Set<string>();\n // Scan the EXECUTABLE body only — strip `import … from '…'` statements\n // first. The mandatory label-type import\n // (`import type { XLabels } from './labels.<locale>'`, required by the\n // generation prompt) otherwise matches the `labels.<key>` access pattern\n // below and reports the LOCALE segment (e.g. `en`) as a phantom missing\n // label key, failing generation for EVERY template by construction.\n // Labels are only ever READ inside subject()/body(), never in an import\n // specifier, so dropping import statements is safe and removes the whole\n // false-positive class. The lazy `[\\s\\S]*?` spans multi-line imports up to\n // their `from '…'` specifier.\n const scannableSource = templateSource.replace(\n /import\\b[\\s\\S]*?from\\s*['\"][^'\"]*['\"]\\s*;?/g,\n '',\n );\n const labelAccessPatterns = [\n /labels\\.([a-zA-Z0-9_]+)/g,\n /labels\\[['\"]([a-zA-Z0-9_]+)['\"]\\]/g,\n ];\n let match: RegExpExecArray | null = null;\n\n for (const pattern of labelAccessPatterns) {\n while ((match = pattern.exec(scannableSource)) !== null) {\n referencedKeys.add(match[1]);\n }\n }\n\n const destructurePattern = /\\{([^}]+)\\}\\s*=\\s*labels\\b/g;\n while ((match = destructurePattern.exec(scannableSource)) !== null) {\n const destructuredMembers = match[1]\n .split(',')\n .map((member) => member.trim())\n .filter(Boolean)\n .map((member) => member.split(':')[0]?.trim())\n .filter((member): member is string => Boolean(member));\n\n for (const member of destructuredMembers) {\n referencedKeys.add(member);\n }\n }\n\n const missingKeys = Array.from(referencedKeys).filter((key) => !(key in labels));\n if (missingKeys.length > 0) {\n throw new Error(\n `Generated template references missing label keys: ${missingKeys.join(', ')}`,\n );\n }\n }\n\n /**\n * Return the trusted SaaS app root for email template/label file operations.\n *\n * Always reads `this.companionContext.saasRoot`. `COMPANION_WORKSPACE_ROOT`\n * is only a subprocess bootstrap seed (written by\n * `applyTrustedHomesToChildProcess`) and must never override the resolved\n * CompanionContext snapshot at runtime — otherwise a stale env var could\n * silently misroute generated email artifacts to the wrong app.\n */\n private getWorkspaceRoot(): string {\n return this.companionContext.saasRoot;\n }\n\n /**\n * The email template owners, the ENGINE owner answering also for every template the delivered canon carries (#3156).\n * Its refs otherwise come from the application's own registry, which scans the folders it already has, so an engine\n * notice added after the application was created was in no target list and could not be delivered or named. One\n * derivation for generation and status, so status lists exactly what generation would deliver.\n *\n * The build lane's expected paths (`resolveExpectedArtifactRelativePaths`) deliberately keep the application's own\n * registry: they say what a landed build must have committed, and a canon template not yet delivered is not a build\n * step's artifact.\n */\n private async emailTemplateOwnershipWithCanon(\n backendEmail: ReadonlyArray<{ emailTemplateOwnership: CompanionEmailTemplateOwnershipDescriptor[] }>,\n ): Promise<CompanionEmailTemplateOwnershipDescriptor[]> {\n const canonRefs = await listTemplateRefsUnderEmailRoot(path.join(this.getWorkspaceRoot(), DELIVERED_EMAIL_CANON_RELATIVE));\n return withDeliveredCanonEngineRefs(backendEmail.flatMap((entry) => entry.emailTemplateOwnership), canonRefs);\n }\n\n /**\n * Answer a template the application does not have yet from the delivered engine canon, with no model\n * call. Answers whether the template now exists.\n *\n * `wildo init` copies the canon once, so an engine email added afterwards reached an existing\n * application only by generating it — the cost the canon exists to avoid, for a template that is the\n * same in every application. This is the email twin of the labelling run's base seeding. It copies\n * the template and the labels of each locale the application serves, and NEVER overwrites: a file\n * that exists is the application's, generated or edited. A template the canon does not carry — the\n * application's own — is generated as before.\n */\n private async seedTemplateFromDeliveredCanon(target: EmailTemplateArtifactTarget): Promise<boolean> {\n const canonDirectory = path.join(this.getWorkspaceRoot(), DELIVERED_EMAIL_CANON_RELATIVE, templateRefToRelativeDir(target.templateRef));\n if (!(await fileExists(templateFilePath(canonDirectory)))) return false;\n const locales = getCompanionEnabledLocaleCodes(this.appConfigService.config as Parameters<typeof getCompanionEnabledLocaleCodes>[0]);\n const copied: string[] = [];\n for (const fileName of [path.basename(templateFilePath(canonDirectory)), ...locales.map((locale) => path.basename(labelsFilePath(canonDirectory, locale)))]) {\n const source = path.join(canonDirectory, fileName);\n const destination = path.join(target.dirPath, fileName);\n if (!(await fileExists(source)) || (await fileExists(destination))) continue;\n await fs.mkdir(target.dirPath, { recursive: true });\n await fs.copyFile(source, destination);\n copied.push(fileName);\n }\n if (copied.length > 0) this.logDebug('Seeded an engine email template from the delivered canon', { templateRef: target.templateRef, copied });\n return fileExists(target.templatePath);\n }\n\n private assertResolvedEmailTargetsOrThrow(\n targets: Array<{ templateRef: string }>,\n warnings: string[],\n requestedTemplateRefs?: string[],\n ): void {\n if (requestedTemplateRefs?.length) {\n const resolvedRefs = new Set(targets.map((target) => target.templateRef));\n const missingRefs = requestedTemplateRefs.filter((templateRef) => !resolvedRefs.has(templateRef));\n\n if (missingRefs.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Unknown email template refs: ${missingRefs.join(', ')}`,\n missingTemplateRefs: missingRefs,\n },\n });\n }\n }\n\n if (targets.length > 0) {\n return;\n }\n\n if (requestedTemplateRefs?.length) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `No email template targets resolved for the requested templateRefs: ${requestedTemplateRefs.join(', ')}`,\n },\n });\n }\n\n if (warnings.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n message: `Email template placement resolution failed: ${warnings.join(' | ')}`,\n },\n });\n }\n }\n\n /**\n * Reload the backend email-definition modules and repopulate the in-memory registry so\n * preview/test-send use the latest filesystem email artifacts.\n */\n private async refreshEmailTemplateRegistry(): Promise<void> {\n const distRoot = this.getPrimaryBackendDistRoot();\n const cacheBust = `${Date.now()}`;\n\n process.env.WILDO_EMAIL_TEMPLATE_IMPORT_BUST = cacheBust;\n\n try {\n /*\n * IN-PROCESS, deliberately (#3268): a preview and a test send RENDER the application's email templates, which are\n * React components imported below, and word them from the initialization config's live label tree and resource\n * schemas. None of that is data. It runs only for a preview or a test send (an operator's action), never for a\n * generation step or a playbook run, so a build wave does not re-import the backend through it.\n */\n const { loadBackendModules, buildApplicationInitializationConfig } = await loadBackendCompanionExports(this.companionContext);\n const backendModules = await loadBackendModules();\n // The application's own label tree and resource schemas, which `EmailBackendService` reads for `fieldValueWord`\n // and `providerName` (bound as `EmailWordSources`), so the preview and test-send say what a send says (#2884).\n try {\n this.applicationEmailWords.load(buildApplicationInitializationConfig());\n } catch (error) {\n this.applicationEmailWords.clear();\n this.logger.warn('[EmailTemplateCompanion] The application\\'s initialization config could not be built; preview shows enum values and provider refs as they are', {\n error: describeCaughtError(error),\n });\n }\n const emailOwnerModules = backendModules.filter((ownedModule) =>\n Object.keys(ownedModule.emailTemplateDefinitions ?? {}).length > 0\n );\n const importedEmailModules = await Promise.all(\n emailOwnerModules.map(async (ownedModule) => {\n const definitionsEntryPath = ownedModule.kind === 'engine'\n ? path.join(distRoot, 'engine/email/email-template-definitions.js')\n : path.join(distRoot, 'modules', ownedModule.moduleId, 'emails/module-email-template-definitions.js');\n const definitionsModuleUrl = `${pathToFileURL(definitionsEntryPath).href}?refresh=${cacheBust}`;\n return import(definitionsModuleUrl) as Promise<{\n emailTemplateDefinitions?: Record<string, {\n template: unknown;\n labels: Record<string, Record<string, string>>;\n }>;\n moduleEmailTemplateDefinitions?: Record<string, {\n template: unknown;\n labels: Record<string, Record<string, string>>;\n }>;\n /** The shared components' words per locale (#2884), exported by the engine email root beside its templates. */\n emailComponentLabels?: Record<string, Record<string, string>>;\n default?: {\n emailTemplateDefinitions?: Record<string, {\n template: unknown;\n labels: Record<string, Record<string, string>>;\n }>;\n };\n }>;\n }),\n );\n\n const refreshedDefinitions: EmailTemplateDefinitionsMap = Object.assign(\n {},\n ...importedEmailModules.map((ownerModule) => (\n ownerModule.emailTemplateDefinitions\n ?? ownerModule.moduleEmailTemplateDefinitions\n ?? ownerModule.default?.emailTemplateDefinitions\n ?? {}\n )),\n ) as EmailTemplateDefinitionsMap;\n\n this.emailTemplateRegistry.initialize(\n refreshedDefinitions,\n mergeEmailComponentLabels(\n ...importedEmailModules.map((ownerModule) => ownerModule.emailComponentLabels),\n // An owner with component words and no templates has no definitions module to re-import; its words come\n // from the module just loaded, as the placement (and so the translate lane) counts it (#2884).\n ...backendModules\n .filter((ownedModule) => Object.keys(ownedModule.emailTemplateDefinitions ?? {}).length === 0)\n .map((ownedModule) => ownedModule.emailComponentLabels),\n ),\n );\n } finally {\n delete process.env.WILDO_EMAIL_TEMPLATE_IMPORT_BUST;\n }\n }\n\n private getPrimaryBackendDistRoot(): string {\n const backendTarget = resolvePrimaryBackendServiceTarget(this.companionContext);\n return path.resolve(backendTarget.packageRoot, 'dist');\n }\n\n private buildTemplateArtifactGenerationPrompt(\n options: {\n templateRef: string;\n locale: AvailableLanguage;\n labelsTypeName: string;\n currentTemplateSource: string | null;\n existingLabels?: Record<string, string>;\n },\n specContextMarkdown?: string,\n correctionMarkdown?: string,\n ): string {\n const localeName = LANGUAGE_INFO_MAP[options.locale]?.name ?? options.locale;\n // The name a person reads, through the one resolver every email uses (#2873): the display name, else the\n // technical name. The local is named `appDisplayLabel` to avoid colliding with `appIdentity.appName`.\n const appDisplayLabel = applicationDisplayName(this.appConfigService.config.appIdentity);\n\n // Authored-spec context block (DD1: the CUSTOM_IMPLEMENTATION_CONTEXT\n // render — purpose, tone, text-slot meaning, event data, business\n // constraints). Empty when the templateRef has no authored\n // SystemEmailTemplateSpecification — the prompt then falls back to ref +\n // app name + current source only (the context-starved baseline).\n const specContextLines = specContextMarkdown\n ? [\n '',\n '# Email purpose & contract (authored specification — honor over assumptions)',\n 'Generate the template and labels to satisfy this authored spec. It defines',\n \"the email's purpose, tone, the meaning of each text slot, the event data the\",\n 'template receives at send time, and any business constraints. Prefer it over',\n 'inferring intent from the templateRef.',\n '',\n specContextMarkdown.trim(),\n ]\n : [];\n\n // Appended only on a retry — see generateTemplateArtifactsWithAgent's loop.\n const correctionLines = correctionMarkdown\n ? ['', '# Correction (your previous attempt was rejected)', correctionMarkdown.trim()]\n : [];\n\n return [\n `Rewrite or generate the email template artifacts for templateRef \"${options.templateRef}\".`,\n `Primary locale: ${options.locale} (${localeName}).`,\n `Application name: ${appDisplayLabel}.`,\n ...specContextLines,\n '',\n 'Return a JSON object only, with this shape:',\n '{',\n ' \"templateSource\": \"full TSX source for template.tsx\",',\n ' \"labels\": { \"flatLabelKey\": \"Primary locale string\" }',\n '}',\n '',\n 'Code conventions you MUST follow:',\n \"- `templateSource` must be a complete `template.tsx` file.\",\n \"- Import `* as React` from 'react'.\",\n \"- Import `{ type EmailTemplateDefinition, interpolateEmailLabel }` from '@wildo-ai/saas-backend-lib'.\",\n `- Import type \\`${options.labelsTypeName}\\` from './labels.${options.locale}'.`,\n \"- Import UI primitives only from '~backend-api/engine/email/components'.\",\n `- Export a default \\`const template: EmailTemplateDefinition<${options.labelsTypeName}>\\`.`,\n '- Keep all user-visible copy in the `labels` object, not inline in JSX or subject strings.',\n '- Access label values only as direct `labels.someKey` property reads. Do not destructure `labels` and do not use bracket notation.',\n '- Use `interpolateEmailLabel(labels.someKey, { placeholder })` for label strings that contain placeholders like `{appName}`.',\n '- Keep the label object flat and string-only.',\n '- Preserve the current business behavior and context-field access whenever the existing template already expresses it correctly.',\n '',\n 'Current template source (use this as the behavioral source of truth when present):',\n '```tsx',\n options.currentTemplateSource ?? '// No current template source available. Generate a sensible template from scratch.',\n '```',\n '',\n 'Existing primary-locale labels (reuse stable keys when sensible):',\n JSON.stringify(options.existingLabels ?? {}, null, 2),\n ...correctionLines,\n ].join('\\n');\n }\n\n private async generateTemplateArtifactsWithAgent(options: {\n templateRef: string;\n locale: AvailableLanguage;\n labelsTypeName: string;\n currentTemplateSource: string | null;\n existingLabels?: Record<string, string>;\n }, sessionContext?: CompanionExecutionSessionContext): Promise<GeneratedEmailTemplateBundle> {\n // Resolve the authored SystemEmailTemplateSpecification context (purpose,\n // tone, per-slot text-slot meaning, event data, business constraints) and\n // inject it into the prompt so the LLM generates from the email's real\n // contract — not just the templateRef string + current source. Best-effort:\n // a ref with no authored spec generates with generic context (the loader\n // warns and returns undefined; never throws).\n const specContext = await this.emailSpecContextLoader.loadGenerationContext(options.templateRef);\n\n const traceStep = sessionContext\n ? this.traceabilityService.createStep(sessionContext, {\n kind: 'agent-invocation',\n label: `email-template-generation-${options.templateRef}`,\n })\n : undefined;\n\n if (sessionContext) {\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: 'agent-email-template-generation-start',\n summary: `Generate email template artifacts for ${options.templateRef}`,\n payload: {\n templateRef: options.templateRef,\n locale: options.locale,\n hasSpecContext: Boolean(specContext?.description),\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n // spec-context.json — the per-template \"what authored context did this\n // generation receive?\" record. `hasSpecContext:false` flags a ref whose\n // authored SystemEmailTemplateSpecification is missing (the enrichment\n // worklist), mirroring the labellize orchestrator's spec-context.json.\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation.spec-context.json',\n content: {\n templateRef: options.templateRef,\n locale: options.locale,\n hasSpecContext: Boolean(specContext?.description),\n description: specContext?.description ?? null,\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation-input.json',\n content: { options },\n ...(traceStep ? { step: traceStep } : {}),\n });\n }\n\n // Bounded generate → parse/validate → retry-with-correction loop. The LLM\n // occasionally wraps the JSON in prose or emits a malformed object; rather\n // than failing the target outright we re-prompt once with the specific\n // rejection reason appended as a `# Correction` block (mirrors the labellize\n // orchestrator's correction-on-retry). GENERATE_TEXT is retained — the\n // GENERATE_STRUCTURED flip (DD4) stays gated on a provider large-TSX-field\n // truncation check — so the retry delivers the reliability win without it.\n const MAX_ATTEMPTS = 2;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n const prompt = this.buildTemplateArtifactGenerationPrompt(\n options,\n specContext?.description,\n attempt > 1 ? this.buildGenerationCorrection(lastError) : undefined,\n );\n\n const invocation: FlowsActors_Agent_Invocation<\n typeof LLMProvider_GenerateTextInputSchema,\n typeof LLMProvider_GenerateTextOutputSchema,\n typeof LLMProvider_OperationContext_BaseSchema\n > = {\n agentRef: 'email-template.generation.agent',\n initiator: {},\n invocationContext: [],\n input: { prompt },\n output: { text: '' },\n executionContext: { callTimestamp: new Date().toISOString() },\n artifactBindings: [],\n };\n\n // Correlate this attempt so the engine AgentCallTraceSink writes the prompt\n // + output (+usage/latency) into THIS step, keyed by attempt (the attempt\n // rides in the label → filenames stay `…attempt-${n}.prompt.txt/.output.json`).\n // The caller keeps only its composed artifacts (generated.tsx, generated-labels).\n const traceContext = sessionContext && traceStep\n ? {\n sessionRef: sessionContext.sessionId,\n stepRef: traceStep.stepId,\n label: `email-template-generation.attempt-${attempt}`,\n attributes: { templateRef: options.templateRef, locale: options.locale, attempt },\n }\n : undefined;\n\n try {\n const result = await this.agentsService.invokeAgent(invocation, traceContext);\n const bundle = this.parseGeneratedBundle(result.output);\n\n if (sessionContext) {\n // Human-readable twins of the generated output: the template as real\n // TSX (not a JSON-escaped blob) and the labels as pretty JSON.\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation.generated.tsx',\n content: bundle.templateSource,\n format: CompanionTraceArtifactFormat.TEXT,\n ...(traceStep ? { step: traceStep } : {}),\n });\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation.generated-labels.json',\n content: bundle.labels,\n ...(traceStep ? { step: traceStep } : {}),\n });\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: 'agent-email-template-generation-success',\n summary: `Generated email template artifacts for ${options.templateRef}`,\n payload: {\n templateRef: options.templateRef,\n labelCount: Object.keys(bundle.labels).length,\n attempt,\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n }\n\n return bundle;\n } catch (error) {\n lastError = error;\n const isLastAttempt = attempt >= MAX_ATTEMPTS;\n\n if (sessionContext) {\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: isLastAttempt\n ? 'agent-email-template-generation-failure'\n : 'agent-email-template-generation-retry',\n summary: isLastAttempt\n ? `Failed to generate email template artifacts for ${options.templateRef} after ${attempt} attempt(s)`\n : `Email generation attempt ${attempt} for ${options.templateRef} failed; retrying with correction`,\n payload: {\n templateRef: options.templateRef,\n locale: options.locale,\n attempt,\n error: this.buildTraceErrorPayload(error),\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n if (isLastAttempt) {\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation-failure.json',\n content: {\n templateRef: options.templateRef,\n locale: options.locale,\n attempts: attempt,\n error: this.buildTraceErrorPayload(error),\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n }\n }\n\n if (isLastAttempt) {\n throw error;\n }\n }\n }\n\n // Unreachable: the loop returns a bundle or throws on the final attempt.\n throw lastError;\n }\n\n /**\n * Parse + validate the email-generation agent's raw text output into a\n * `{ templateSource, labels }` bundle. Throws with a specific message (fed\n * back to the model by the retry loop) on empty output, non-JSON output, a\n * missing/blank `templateSource`, or a missing / non-flat / empty `labels`.\n */\n private parseGeneratedBundle(output: unknown): GeneratedEmailTemplateBundle {\n const rawText = (output as { text?: string })?.text;\n if (!rawText || typeof rawText !== 'string') {\n throw new Error('Email generation agent returned empty output');\n }\n\n const jsonMatch = rawText.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n const jsonText = jsonMatch?.[1]?.trim() ?? rawText.trim();\n let parsed: { templateSource?: unknown; labels?: unknown };\n try {\n parsed = JSON.parse(jsonText) as { templateSource?: unknown; labels?: unknown };\n } catch (err) {\n throw new Error(\n `Email generation output was not valid JSON: ${describeCaughtError(err)}`,\n );\n }\n\n if (typeof parsed.templateSource !== 'string' || !parsed.templateSource.trim().length) {\n throw new Error('Email generation output is missing templateSource');\n }\n const templateSource = parsed.templateSource;\n\n if (!parsed.labels || typeof parsed.labels !== 'object' || Array.isArray(parsed.labels)) {\n throw new Error('Email generation output is missing a flat labels object');\n }\n\n const labels: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed.labels as Record<string, unknown>)) {\n if (typeof value !== 'string' || !value.trim().length) {\n throw new Error(`Email generation returned an invalid label for key \"${key}\"`);\n }\n labels[key] = value;\n }\n\n if (Object.keys(labels).length === 0) {\n throw new Error('Email generation returned an empty labels object');\n }\n\n return { templateSource, labels };\n }\n\n /**\n * Build the `# Correction` block appended to the prompt on a retry — feeds\n * the specific rejection reason back so the model fixes exactly that.\n */\n private buildGenerationCorrection(error: unknown): string {\n const reason = describeCaughtError(error);\n return [\n `Your previous attempt was rejected: ${reason}`,\n 'Return ONLY a single JSON object of the exact shape '\n + '{ \"templateSource\": \"<full template.tsx>\", \"labels\": { \"<key>\": \"<non-empty string>\" } } '\n + '— no prose before or after, every label value a non-empty string, the labels object flat.',\n ].join('\\n');\n }\n\n private parseAvailableLanguageOrThrow(code: string): AvailableLanguage {\n const found = Object.values(AvailableLanguage).find((v) => v === code);\n if (!found) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Unknown locale code \"${code}\". Use an AvailableLanguage value (e.g. en, fr, de).`,\n },\n });\n }\n return found as AvailableLanguage;\n }\n\n private createWrapperTraceStep(\n sessionContext: CompanionExecutionSessionContext | undefined,\n label: string,\n ) {\n return sessionContext\n ? this.traceabilityService.createStep(sessionContext, {\n kind: 'email-template',\n label,\n })\n : undefined;\n }\n\n private async traceWrapperStart(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n type: string,\n summary: string,\n payload: Record<string, unknown>,\n artifactFileName: string,\n artifactContent: unknown,\n ): Promise<void> {\n if (!sessionContext) {\n return;\n }\n\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type,\n summary,\n payload,\n ...(step ? { step } : {}),\n });\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: artifactFileName,\n content: artifactContent,\n ...(step ? { step } : {}),\n });\n }\n\n private async traceWrapperSuccess(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n type: string,\n summary: string,\n payload: Record<string, unknown>,\n artifactFileName: string,\n artifactContent: unknown,\n ): Promise<void> {\n if (!sessionContext) {\n return;\n }\n\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: artifactFileName,\n content: artifactContent,\n ...(step ? { step } : {}),\n });\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type,\n summary,\n payload,\n ...(step ? { step } : {}),\n });\n }\n\n private async traceWrapperFailure(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n type: string,\n summary: string,\n error: unknown,\n payload: Record<string, unknown>,\n ): Promise<void> {\n if (!sessionContext) {\n return;\n }\n\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type,\n summary,\n payload: {\n ...payload,\n error: this.buildTraceErrorPayload(error),\n },\n ...(step ? { step } : {}),\n });\n }\n\n private buildTraceErrorPayload(error: unknown) {\n if (isWildoBackendError(error)) {\n return error;\n }\n\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n ...(error.stack ? { stack: error.stack } : {}),\n };\n }\n\n return {\n message: formatUnknownError(error),\n };\n }\n\n /**\n * Resolve the application's default locale for email fallback.\n */\n private getDefaultLocale(): AvailableLanguage {\n return getCompanionConfiguredPrimaryLanguage(this.appConfigService.config);\n }\n\n private getFallbackLocale(): AvailableLanguage {\n return getCompanionConfiguredFallbackLanguage(this.appConfigService.config);\n }\n\n /**\n * Resolve brand tokens the same way the runtime email backend does.\n */\n private getDesignTokens() {\n return buildEmailBrandTokensFromConfig(this.appConfigService.config.email?.brandTokens);\n }\n\n /**\n * List existing locale label artifacts for one filesystem template directory.\n */\n private async getTemplateLocaleStatuses(\n dirPath: string,\n ): Promise<EmailTemplateStatusResult['locales']> {\n let entries: Array<{ name: string; isFile(): boolean }>;\n try {\n entries = (await fs.readdir(dirPath, {\n withFileTypes: true,\n encoding: 'utf8',\n })) as Array<{ name: string; isFile(): boolean }>;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n\n const localeEntries = await Promise.all(\n entries\n .filter((entry) => entry.isFile() && /^labels\\.(.+)\\.ts$/.test(entry.name))\n .map(async (entry) => {\n const localeMatch = entry.name.match(/^labels\\.(.+)\\.ts$/);\n const locale = localeMatch?.[1] ?? 'unknown';\n const labelsPath = labelsFilePath(dirPath, locale);\n const stat = await fs.stat(labelsPath);\n\n return {\n locale,\n labelsPath,\n exists: true,\n updatedAt: stat.mtime.toISOString(),\n };\n }),\n );\n\n return localeEntries.sort((left, right) => left.locale.localeCompare(right.locale));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"email-template.companion.service.js","sourceRoot":"","sources":["../../../../src/email/services/email-template.companion.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,+BAA+B,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AACnI,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,wBAAwB,EAGxB,aAAa,EACb,0BAA0B,EAC1B,kBAAkB,EAElB,mBAAmB,GACpB,MAAM,4BAA4B,CAAC;AAMpC,OAAO,EACL,sCAAsC,EACtC,qCAAqC,GACtC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,sBAAsB,EAEtB,qBAAqB,EACrB,iBAAiB,EACjB,SAAS,EACT,2BAA2B,EAC3B,iBAAiB,EAGjB,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAC3F,OAAO,EACL,qCAAqC,EACrC,mCAAmC,EACnC,cAAc,EACd,YAAY,EACZ,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,wBAAwB,EACxB,8BAA8B,EAC9B,4BAA4B,GAG7B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,sBAAsB,EAAE,0BAA0B,EAAE,MAAM,kCAAkC,CAAC;AACtG,OAAO,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AAC,CAAA;IACjC,WAAA,MAAM,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAA;IAC9C,WAAA,MAAM,CAAC,kBAAkB,CAAC,oBAAoB,CAAC,CAAA;IAC/C,WAAA,MAAM,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAA;IAC3C,WAAA,MAAM,CAAC,kBAAkB,CAAC,sBAAsB,CAAC,CAAA;IACjD,WAAA,MAAM,CAAC,kBAAkB,CAAC,qBAAqB,CAAC,CAAA;IAChD,WAAA,MAAM,CAAC,kBAAkB,CAAC,YAAY,CAAC,CAAA;IACvC,WAAA,MAAM,CAAC,uBAAuB,CAAC,gBAAgB,CAAC,CAAA;IAEhD,WAAA,MAAM,CAAC,uBAAuB,CAAC,2BAA2B,CAAC,CAAA;IAE3D,WAAA,MAAM,CAAC,uBAAuB,CAAC,mBAAmB,CAAC,CAAA;IAEnD,YAAA,MAAM,CAAC,uBAAuB,CAAC,sBAAsB,CAAC,CAAA;IAEtD,YAAA,MAAM,CAAC,uBAAuB,CAAC,kCAAkC,CAAC,CAAA;IAElE,YAAA,MAAM,CAAC,uBAAuB,CAAC,4BAA4B,CAAC,CAAA;IAE5D,YAAA,MAAM,CAAC,uBAAuB,CAAC,2BAA2B,CAAC,CAAA;qCAnBA,aAAa;QACM,0BAA0B,4DAS3D,oCAAoC;QAE5C,4BAA4B;QAEzB,sCAAsC;QAEjC,2CAA2C;QAEjD,qCAAqC;QAErC,2CAA2C;GAxB1E,6BAA6B,CAknDzC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { moduleEmailDefinitionsEntryPath, selectModuleEmailTemplateDefinitions } from '../utils/module-email-root.companion.utils';\nimport { pathToFileURL } from 'node:url';\nimport { render } from '@react-email/render';\nimport { injectable, inject } from 'inversify';\nimport {\n buildEmailBrandTokensFromConfig,\n mergeEmailComponentLabels,\n withEmailComponentLabels,\n type EmailTemplateDefinitionsMap,\n type EmailTemplateRegistryBackendService,\n LoggerService,\n ErrorBuilderBackendService,\n SAAS_SERVICE_TYPES,\n type AgentsBackendService,\n describeCaughtError,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n LLMProvider_GenerateTextInputSchema,\n LLMProvider_GenerateTextOutputSchema,\n LLMProvider_OperationContext_BaseSchema,\n} from '@wildo-ai/external-connectors-models';\nimport {\n getCompanionConfiguredFallbackLanguage,\n getCompanionConfiguredPrimaryLanguage,\n} from '../../core/config/primary-language.companion.utils';\nimport {\n applicationDisplayName,\n FlowsActors_Agent_Invocation,\n BrandAssetComposition,\n BrandAssetPurpose,\n ErrorType,\n ErrorCustomMessageReference,\n EmailTemplateType,\n type ObjectContext,\n type PrimaryScopeContext,\n EmailSubmissionOutcome,\n isWildoBackendError,\n} from '@wildo-ai/saas-models';\nimport { AvailableLanguage, LANGUAGE_INFO_MAP } from '@wildo-ai/presets-components-models';\nimport {\n resolveEmailTemplateArtifactPlacement,\n resolveEmailTemplateArtifactTargets,\n labelsFilePath,\n readUtf8File,\n writeUtf8File,\n fileExists,\n templateFilePath,\n templateRefToRelativeDir,\n listTemplateRefsUnderEmailRoot,\n withDeliveredCanonEngineRefs,\n type EmailTemplateArtifactTarget,\n type EmailTemplateOwnershipPlacement,\n} from '../utils/email-template-fs-discovery.utils';\nimport { flattenEmailLabelsTree, parseEmailLabelsTreeSource } from '../utils/email-labels-tree.utils';\nimport { getCompanionEnabledLocaleCodes } from '../../core/config/primary-language.companion.utils';\nimport {\n parseEmailLabelsTsSource,\n formatLabelsTsFile,\n} from '../utils/email-labels-file-source.utils';\nimport { COMPANION_SERVICE_TYPES } from '../../core/inject/models/service-types';\nimport type { CompanionContext } from '../../core/context/companion-context';\nimport {\n loadBackendCompanionExports,\n resolvePrimaryBackendServiceTarget,\n assertSpecificationsReadWhole,\n} from '../../core/context/companion-package-loaders.companion';\nimport { TranslationPlacementCompanionService } from '../../core/introspection/services/translation-placement.companion.service';\nimport { CompanionTraceabilityService } from '../../core/traceability/companion-traceability.service';\nimport { EmailSpecContextLoaderCompanionService } from './email-spec-context-loader.companion.service';\nimport { ApplicationEmailWordSourcesCompanionService } from './application-email-word-sources.companion.service';\nimport { EmailTemplateLabellingUnitsCompanionService } from '../../i18n-labelling/services/email-template-labelling-units.companion.service';\nimport { TranslateOrchestratorCompanionService } from '../../i18n-labelling/services/translate-orchestrator.companion.service';\nimport { I18nUnitRunStatus } from '../../i18n-labelling/models/labelling-unit.models';\nimport {\n CompanionTraceabilityLevel,\n CompanionTraceArtifactFormat,\n type CompanionExecutionSessionContext,\n} from '../../core/traceability/companion-traceability.models';\n\n// Import email services - these are injected via DI, so we only need the types\nimport type { AppConfigurationService } from '@wildo-ai/saas-backend-lib';\nimport type { EmailBackendService } from '@wildo-ai/saas-backend-lib';\nimport type { EmailTemplateValidatorBackendService } from '@wildo-ai/saas-backend-lib';\nimport type { LabellingProgressReporter } from '../../i18n-labelling/models/labelling-progress.models';\n\n/**\n * The framework's ENGINE email templates as an application receives them — `templates/saas/i18n/email`,\n * harvested from Wonder Todos and delivered into every application's `.wildo-saas/templates/`.\n */\nconst DELIVERED_EMAIL_CANON_RELATIVE = '.wildo-saas/templates/i18n/email' as const;\n\n/** Partial authoring-only object context; nested scope overrides retain synthetic defaults. */\nexport type EmailTemplateMockObjectContext = Omit<Partial<ObjectContext>, 'primaryScopeContext'> & {\n primaryScopeContext?: Partial<PrimaryScopeContext>;\n};\n\n/**\n * Request for generating email templates\n */\nexport interface GenerateEmailTemplatesRequest {\n /** Force regenerate even if template exists */\n forceRegenerate?: boolean;\n /** Specific template refs to generate (empty = all) */\n templateRefs?: string[];\n /** Specific locales to generate (empty = all configured) */\n locales?: AvailableLanguage[];\n}\n\n/**\n * Request for previewing an email template\n */\nexport interface PreviewEmailTemplateRequest {\n templateRef: string;\n locale: AvailableLanguage;\n /** Mock context data for preview */\n mockContext?: {\n currentObject?: Record<string, unknown>;\n objectContext?: EmailTemplateMockObjectContext;\n userContext?: {\n email: string;\n name?: string;\n firstName?: string;\n };\n additionalContext?: Record<string, unknown>;\n };\n}\n\n/**\n * Preview result\n */\nexport interface PreviewEmailTemplateResult {\n templateRef: string;\n locale: AvailableLanguage;\n resolvedLocale?: string;\n subject: string;\n bodyHtml: string;\n bodyText?: string;\n previewedAt: string;\n}\n\n/**\n * Request for sending a test email\n */\nexport interface TestSendEmailRequest {\n templateRef: string;\n locale: AvailableLanguage;\n /** Recipient email address for test */\n recipientEmail: string;\n /** Mock context data for test */\n mockContext?: {\n currentObject?: Record<string, unknown>;\n objectContext?: EmailTemplateMockObjectContext;\n userContext?: {\n email: string;\n name?: string;\n firstName?: string;\n };\n additionalContext?: Record<string, unknown>;\n };\n}\n\n/**\n * Test send result\n */\nexport interface TestSendEmailResult {\n success: boolean;\n submissionId: string;\n outcome: EmailSubmissionOutcome;\n retryable: boolean;\n deduplicated?: boolean;\n templateRef: string;\n locale: AvailableLanguage;\n recipientEmail: string;\n /** All provider receipts returned for the test submission. */\n providerMessageIds: string[];\n error?: string;\n sentAt: string;\n}\n\n/**\n * Template status result\n */\nexport interface EmailTemplateStatusResult {\n ownerId: string;\n templateRef: string;\n templatePath: string;\n templateExists: boolean;\n locales: Array<{\n locale: string;\n labelsPath: string;\n exists: boolean;\n updatedAt: string;\n }>;\n /**\n * Why the template has no place (#3904 review F2): its owner registers templates from no folder the companion can read,\n * so generation writes nothing for it. `templatePath` is then empty and `templateExists` false.\n */\n notPlacedBecause?: string;\n}\n\n/**\n * Translate filesystem `labels.{primaryLocale}.ts` → `labels.{targetLocale}.ts` for each template directory.\n *\n * The source locale is always the SaaS application's configured primary\n * language from `appPreferences.languages.defaultLanguage`.\n */\nexport interface TranslateEmailTemplateLabelsRequest {\n /** Target locale codes (e.g. fr, de) — must match `AvailableLanguage` enum values */\n targetLocales: string[];\n /** Limit to specific registry template refs; omit for all */\n templateRefs?: string[];\n /** When true, only report planned writes (no LLM, no disk writes) */\n dryRun?: boolean;\n}\n\nexport interface TranslateEmailTemplateLabelsResult {\n translatedFiles: number;\n skipped: number;\n failed: number;\n warnings: string[];\n details: Array<{\n ownerId: string;\n templateRef: string;\n targetLocale: string;\n success: boolean;\n outputPath?: string;\n error?: string;\n }>;\n completedAt: string;\n}\n\nexport interface GenerateEmailTemplatesResult {\n generated: number;\n skipped: number;\n failed: number;\n warnings: string[];\n details: Array<{\n ownerId: string;\n templateRef: string;\n locale: AvailableLanguage;\n success: boolean;\n skipped?: boolean;\n /** The template was copied from the delivered engine canon this run, with no model call (#3156). */\n seededFromCanon?: boolean;\n templatePath?: string;\n labelsPath?: string;\n errors?: string[];\n }>;\n generatedAt: string;\n}\n\ninterface GeneratedEmailTemplateBundle {\n templateSource: string;\n labels: Record<string, string>;\n}\n\nfunction formatUnknownError(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (typeof error === 'object' && error !== null) {\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n }\n\n return String(error);\n}\n\n/**\n * Email Template Companion Service\n * \n * Handles email template generation, preview, and testing operations\n * for the dev companion API.\n */\n@injectable()\nexport class EmailTemplateCompanionService {\n private readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.AgentsBackendService) private readonly agentsService: AgentsBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_SERVICE_TYPES.EmailTemplateValidator) private readonly emailTemplateValidator: EmailTemplateValidatorBackendService,\n @inject(SAAS_SERVICE_TYPES.EmailTemplateRegistry) private readonly emailTemplateRegistry: EmailTemplateRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.EmailService) private readonly emailService: EmailBackendService,\n @inject(COMPANION_SERVICE_TYPES.CompanionContext)\n private readonly companionContext: CompanionContext,\n @inject(COMPANION_SERVICE_TYPES.TranslationPlacementService)\n private readonly translationPlacementService: TranslationPlacementCompanionService,\n @inject(COMPANION_SERVICE_TYPES.TraceabilityService)\n private readonly traceabilityService: CompanionTraceabilityService,\n @inject(COMPANION_SERVICE_TYPES.EmailSpecContextLoader)\n private readonly emailSpecContextLoader: EmailSpecContextLoaderCompanionService,\n @inject(COMPANION_SERVICE_TYPES.EmailTemplateLabellingUnitsService)\n private readonly emailTemplateLabellingUnits: EmailTemplateLabellingUnitsCompanionService,\n @inject(COMPANION_SERVICE_TYPES.TranslateOrchestratorService)\n private readonly translateOrchestrator: TranslateOrchestratorCompanionService,\n @inject(COMPANION_SERVICE_TYPES.ApplicationEmailWordSources)\n private readonly applicationEmailWords: ApplicationEmailWordSourcesCompanionService,\n ) {\n this.logDebug = this.logger.debugByType('EmailTemplateCompanion');\n this.logger.setDebugTypeLogging('EmailTemplateCompanion', true);\n }\n\n /**\n * Generate primary-locale filesystem email template artifacts using LLM.\n */\n async generateTemplates(\n request: GenerateEmailTemplatesRequest,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<GenerateEmailTemplatesResult> {\n // The prompts are built from the package: a short read rewrites a template from less than it had (#3258).\n await assertSpecificationsReadWhole(this.companionContext, 'The email templates');\n this.logDebug('Generating email templates...', { request });\n const traceStep = this.createWrapperTraceStep(sessionContext, 'generate-templates');\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-generation-wrapper-start',\n 'Generate email templates',\n {\n forceRegenerate: request.forceRegenerate === true,\n templateRefs: request.templateRefs ?? [],\n locales: request.locales ?? [],\n },\n 'email-template-generation-wrapper-request.json',\n request,\n );\n\n try {\n const primaryLocale = this.resolvePrimaryGenerationLocale(request.locales);\n const snapshot = await this.translationPlacementService.getPlacementSnapshot({\n includeShared: false,\n includeFrontend: false,\n includeBackendEmail: true,\n });\n const ownership = await this.emailTemplateOwnershipWithCanon(snapshot.backendEmail);\n const { targets, unplaced } = resolveEmailTemplateArtifactPlacement(\n this.getWorkspaceRoot(),\n ownership,\n request.templateRefs,\n );\n // An unplaced template is a known ref, never \"unknown\": it is reported below, with why it was not written.\n this.assertResolvedEmailTargetsOrThrow([...targets, ...unplaced], snapshot.warnings, request.templateRefs);\n\n const details: GenerateEmailTemplatesResult['details'] = [];\n const runWarnings: string[] = [];\n let generated = 0;\n let skipped = 0;\n let failed = 0;\n\n /*\n * A template whose owner's registration cannot be read is NOT written (#3904 review F2): writing it under the\n * conventional folder is what put the `enquiries` template where nothing registered it. It fails, naming why, so the\n * step does not report a template it did not deliver, and `check:module-layout` is what moves the module.\n */\n for (const entry of unplaced) {\n failed++;\n runWarnings.push(`${entry.templateRef}: not written, ${entry.reason}.`);\n details.push({\n ownerId: entry.ownerId,\n templateRef: entry.templateRef,\n locale: primaryLocale,\n success: false,\n errors: [`Not written: ${entry.reason}.`],\n });\n }\n\n for (const target of targets) {\n const labelsPath = labelsFilePath(target.dirPath, primaryLocale);\n\n try {\n let hasTemplate = await fileExists(target.templatePath);\n /*\n * A template the application does not have is copied from the canon, forced or not (#3156): a forced run\n * regenerates the application's OWN templates, and one it does not hold yet is the engine's, the same in\n * every application, so paying a model call for it is the cost the canon exists to avoid. A just-copied\n * template is then delivered as it stands.\n */\n const seededFromCanon = !hasTemplate && await this.seedTemplateFromDeliveredCanon(target);\n hasTemplate = hasTemplate || seededFromCanon;\n const hasLabels = await fileExists(labelsPath);\n const existingLabels = hasLabels ? await this.tryReadExistingLabels(labelsPath) : null;\n /*\n * Engine templates key some words by a vocabulary (`stages.<stage>.subject`), which the FLAT reader refuses.\n * Reading that as \"no words\" sent a template that has its words to the flat generator, whose rewrite the import\n * validator refused (measured on Wonder Procurement, #3156: three system templates failed on every run). Such\n * a file is read with the keyed reader the translate lane uses; a file NEITHER reader parses is a failure that\n * names the file, never words and never wordless.\n */\n const keyedWordCount = hasLabels && existingLabels === null ? await this.countKeyedLabelWords(labelsPath) : null;\n if (hasLabels && existingLabels === null && keyedWordCount === null) {\n throw new Error(`Cannot read the words in ${labelsPath}: neither the flat nor the keyed labels reader parses it.`);\n }\n const hasWords = existingLabels !== null ? Object.keys(existingLabels).length > 0 : (keyedWordCount ?? 0) > 0;\n // The flat generator cannot write words keyed by a vocabulary, so even a forced run keeps them (and says so).\n const keyedWordsKept = request.forceRegenerate === true && !seededFromCanon && hasTemplate && (keyedWordCount ?? 0) > 0;\n if (keyedWordsKept) {\n runWarnings.push(`${target.templateRef}: kept as it stands; its words are keyed by a vocabulary, which the generator cannot write (edit ${labelsPath} by hand).`);\n }\n\n if (\n ((!request.forceRegenerate || seededFromCanon) || keyedWordsKept)\n && hasTemplate\n && hasWords\n ) {\n skipped++;\n details.push({\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n locale: primaryLocale,\n success: true,\n skipped: true,\n ...(seededFromCanon ? { seededFromCanon: true } : {}),\n templatePath: target.templatePath,\n labelsPath,\n });\n continue;\n }\n\n const currentTemplateSource = hasTemplate\n ? await readUtf8File(target.templatePath)\n : null;\n const labelsTypeName = this.buildLabelsTypeName(target.templateRef);\n const generatedBundle = await this.generateTemplateArtifactsWithAgent({\n templateRef: target.templateRef,\n locale: primaryLocale,\n labelsTypeName,\n currentTemplateSource,\n existingLabels: existingLabels ?? undefined,\n }, sessionContext);\n this.assertTemplateLabelsConsistencyOrThrow(\n generatedBundle.templateSource,\n generatedBundle.labels,\n );\n\n const validation = await this.emailTemplateValidator.validate(generatedBundle.templateSource);\n if (!validation.valid) {\n throw new Error(validation.errors.join(', '));\n }\n\n await writeUtf8File(target.templatePath, this.normalizeGeneratedTemplateSource(generatedBundle.templateSource));\n await writeUtf8File(\n labelsPath,\n formatLabelsTsFile({\n localeCode: primaryLocale,\n localeDisplayName: LANGUAGE_INFO_MAP[primaryLocale]?.name ?? primaryLocale,\n isPrimaryLocale: true,\n entries: generatedBundle.labels,\n labelsTypeName,\n usesAsConst: true,\n }),\n );\n\n generated++;\n details.push({\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n locale: primaryLocale,\n success: true,\n templatePath: target.templatePath,\n labelsPath,\n });\n } catch (error) {\n failed++;\n details.push({\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n locale: primaryLocale,\n success: false,\n templatePath: target.templatePath,\n labelsPath,\n errors: [formatUnknownError(error)],\n });\n }\n }\n\n // No registry refresh here (#3268): only a preview and a test send read the registry, and each refreshes it first.\n // Refreshing after a generation step re-imported the backend's companion graph into this process during a wave.\n\n const result = {\n generated,\n skipped,\n failed,\n warnings: [...snapshot.warnings, ...runWarnings],\n details,\n generatedAt: new Date().toISOString(),\n };\n const completedWithFailures = failed > 0;\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n completedWithFailures\n ? 'email-template-generation-wrapper-mixed-result'\n : 'email-template-generation-wrapper-success',\n completedWithFailures\n ? `Generated email templates for ${generated} targets with ${failed} failures`\n : `Generated email templates for ${generated} targets`,\n {\n generated,\n skipped,\n failed,\n warningCount: snapshot.warnings.length,\n },\n 'email-template-generation-wrapper-result.json',\n result,\n );\n return result;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-generation-wrapper-failure',\n 'Email template generation failed',\n error,\n {\n forceRegenerate: request.forceRegenerate === true,\n templateRefs: request.templateRefs ?? [],\n locales: request.locales ?? [],\n },\n );\n throw error;\n }\n }\n\n /**\n * Preview and test-send share the application's email logo resolver. Their synthetic names,\n * object ids and recipients remain distinct. Scope overrides merge over branding/defaults;\n * other object-context fields (parents and operation) survive without replacing that scope.\n * This is an authoring context, not a replay of a notification producer's real resource context.\n */\n private buildMockObjectContext(defaultScope: PrimaryScopeContext, overrides?: EmailTemplateMockObjectContext): ObjectContext {\n return {\n ...overrides,\n primaryScopeContext: {\n ...defaultScope,\n logoUrl: this.appConfigService.resolveBrandLogoAbsoluteUrl({\n composition: BrandAssetComposition.LOCKUP,\n purpose: BrandAssetPurpose.EMAIL,\n }) ?? undefined,\n ...overrides?.primaryScopeContext,\n },\n };\n }\n\n /**\n * Preview an email template with mock context\n */\n async previewTemplate(\n request: PreviewEmailTemplateRequest,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<PreviewEmailTemplateResult> {\n this.logDebug('Previewing email template...', { \n templateRef: request.templateRef, \n locale: request.locale,\n });\n\n const traceStep = this.createWrapperTraceStep(sessionContext, `preview-${request.templateRef}`);\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-preview-start',\n `Preview email template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n },\n 'email-template-preview-request.json',\n request,\n );\n\n try {\n\n await this.refreshEmailTemplateRegistry();\n const resolved = this.emailTemplateRegistry.resolve(\n request.templateRef,\n request.locale,\n this.getDefaultLocale(),\n this.getFallbackLocale(),\n );\n\n const defaultUserContext = {\n userId: 'preview-user-id',\n email: 'preview@example.com',\n name: 'Preview User',\n firstName: 'Preview',\n };\n \n const mockContext = {\n currentObject: request.mockContext?.currentObject || { _id: 'preview-id', title: 'Preview Object' },\n objectContext: this.buildMockObjectContext({\n appName: 'Preview App', applicationId: 'preview-app-id', organizationName: 'Preview Organization',\n }, request.mockContext?.objectContext),\n userContext: request.mockContext?.userContext \n ? { userId: 'preview-user-id', ...request.mockContext.userContext }\n : defaultUserContext,\n additionalContext: request.mockContext?.additionalContext || {},\n };\n\n const brandTokens = this.getDesignTokens();\n const templateProps = {\n context: mockContext,\n brand: brandTokens,\n labels: resolved.labels,\n locale: resolved.resolvedLocale,\n // An enum value's word, from the same label tree and cascade a send uses (#2884).\n fieldValueWord: this.emailService.fieldValueWordFor(resolved.resolvedLocale),\n providerName: this.emailService.providerNameFor(resolved.resolvedLocale),\n vocabularyWord: this.emailService.vocabularyWordFor(resolved.resolvedLocale),\n };\n\n const subject = resolved.definition.subject(templateProps);\n // As a send renders it: the shared components read their words in the language the template resolved in (#2884).\n const bodyElement = withEmailComponentLabels(\n resolved.definition.body(templateProps),\n this.emailTemplateRegistry.resolveComponentWords(resolved.resolvedLocale),\n );\n const bodyHtml = await render(bodyElement, { pretty: true });\n const bodyText = await render(bodyElement, { plainText: true });\n\n const previewResult = {\n templateRef: request.templateRef,\n locale: request.locale,\n resolvedLocale: resolved.resolvedLocale,\n subject,\n bodyHtml,\n bodyText,\n previewedAt: new Date().toISOString(),\n };\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-preview-success',\n `Previewed email template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n resolvedLocale: resolved.resolvedLocale ?? null,\n },\n 'email-template-preview-result.json',\n previewResult,\n );\n return previewResult;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-preview-failure',\n `Failed to preview email template ${request.templateRef}`,\n error,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n },\n );\n if (isWildoBackendError(error) || (error as { customMessageReference?: unknown })?.customMessageReference) {\n throw error;\n }\n\n this.logger.error('Failed to preview email template', {\n templateRef: request.templateRef,\n locale: request.locale,\n error: formatUnknownError(error),\n });\n\n throw this.errorBuilder.buildFromStandardError(error, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: { operation: 'previewTemplate' },\n });\n }\n }\n\n /**\n * Send a test email using a template\n */\n async testSend(\n request: TestSendEmailRequest,\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<TestSendEmailResult> {\n this.logDebug('Sending test email...', {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n });\n\n const traceStep = this.createWrapperTraceStep(sessionContext, `test-send-${request.templateRef}`);\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-test-send-start',\n `Send test email for template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n },\n 'email-template-test-send-request.json',\n request,\n );\n\n const submissionId = randomUUID();\n let submissionAttempted = false;\n let sendResult: TestSendEmailResult | undefined;\n try {\n\n await this.refreshEmailTemplateRegistry();\n const defaultUserContext = {\n userId: 'test-user-id',\n email: request.recipientEmail,\n name: 'Test User',\n firstName: 'Test',\n };\n \n const context = {\n currentObject: request.mockContext?.currentObject || { _id: 'test-id', title: 'Test Object' },\n objectContext: this.buildMockObjectContext({\n appName: 'Test App', applicationId: 'test-app-id', organizationName: 'Test Organization',\n }, request.mockContext?.objectContext),\n userContext: request.mockContext?.userContext \n ? { userId: 'test-user-id', ...request.mockContext.userContext }\n : defaultUserContext,\n additionalContext: request.mockContext?.additionalContext || {},\n };\n\n submissionAttempted = true;\n const result = await this.emailService.send({\n submissionId,\n templateRef: request.templateRef,\n locale: request.locale,\n type: EmailTemplateType.TRANSACTIONAL,\n to: request.recipientEmail,\n context,\n });\n\n sendResult = {\n success: result.success,\n submissionId: result.submissionId,\n outcome: result.outcome,\n retryable: result.retryable,\n deduplicated: result.deduplicated,\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n providerMessageIds: result.providerMessageIds,\n error: result.error,\n sentAt: new Date().toISOString(),\n };\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-test-send-success',\n `Completed test email attempt for template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n success: result.success,\n },\n 'email-template-test-send-result.json',\n sendResult,\n );\n return sendResult;\n } catch (error) {\n // Reporting failures cannot erase or contradict the sender's already-known outcome.\n if (sendResult) {\n this.logger.error('Failed to record test email trace', {\n submissionId: sendResult.submissionId,\n outcome: sendResult.outcome,\n providerMessageIds: sendResult.providerMessageIds,\n error: formatUnknownError(error),\n });\n return sendResult;\n }\n this.logger.error('Failed to send test email', {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n providerMessageIds: [],\n error: formatUnknownError(error),\n });\n\n const failureResult: TestSendEmailResult = {\n success: false,\n submissionId,\n outcome: submissionAttempted ? EmailSubmissionOutcome.ACCEPTANCE_UNKNOWN : EmailSubmissionOutcome.NOT_SUBMITTED,\n retryable: submissionAttempted,\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n providerMessageIds: [],\n error: formatUnknownError(error),\n sentAt: new Date().toISOString(),\n };\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-test-send-failure',\n `Failed to send test email for template ${request.templateRef}`,\n error,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n },\n );\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-test-send-result',\n `Recorded failed test email result for template ${request.templateRef}`,\n {\n templateRef: request.templateRef,\n locale: request.locale,\n recipientEmail: request.recipientEmail,\n success: false,\n },\n 'email-template-test-send-result.json',\n failureResult,\n );\n return failureResult;\n }\n }\n\n /**\n * Get filesystem-backed status of email template artifacts.\n */\n /**\n * The app-root-relative files the email-template pipelines are responsible for, for the given\n * locales: one `template.tsx` per owned template plus one `labels.<locale>.ts` per locale.\n *\n * This is the email domain's HALF of the build lane's landed-evidence contract: PLACEMENT — which\n * directory, which file names — is this domain's single authority (`resolveEmailTemplateArtifactTargets`\n * + `templateFilePath`/`labelsFilePath`), while the build lane owns what \"landed\" means (every path\n * committed in git). Derived from the live placement snapshot, so the set is re-derivable after a\n * restart, a fresh clone, or a branch switch — never a stored list.\n */\n async resolveExpectedArtifactRelativePaths(locales: readonly string[]): Promise<readonly string[]> {\n const snapshot = await this.translationPlacementService.getPlacementSnapshot({\n includeShared: false,\n includeFrontend: false,\n includeBackendEmail: true,\n });\n const ownership = snapshot.backendEmail.flatMap((entry) => entry.emailTemplateOwnership);\n const workspaceRoot = this.getWorkspaceRoot();\n /*\n * Only PLACED templates (#3904 review F2): one whose owner registers it from no folder the companion can read has no\n * path a landing could prove. It is not silent: the step's own result fails it with the reason and carries it in its\n * warnings, and when the cause is a misplaced module, `check:module-layout` fails the coding run that placed it.\n */\n const targets = resolveEmailTemplateArtifactTargets(workspaceRoot, ownership);\n return targets\n .flatMap((target) => [target.templatePath, ...locales.map((locale) => labelsFilePath(target.dirPath, locale))])\n .map((absolutePath) => path.relative(workspaceRoot, absolutePath).split(path.sep).join(path.posix.sep));\n }\n\n async getTemplateStatus(\n templateRefs?: string[],\n sessionContext?: CompanionExecutionSessionContext,\n ): Promise<EmailTemplateStatusResult[]> {\n this.logDebug('Getting template status...', { templateRefs });\n const traceStep = this.createWrapperTraceStep(sessionContext, 'status');\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-template-status-start',\n 'Get email template status',\n {\n templateRefs: templateRefs ?? [],\n },\n 'email-template-status-request.json',\n { templateRefs },\n );\n\n try {\n const snapshot = await this.translationPlacementService.getPlacementSnapshot({\n includeShared: false,\n includeFrontend: false,\n includeBackendEmail: true,\n });\n // Status lists what generation would deliver, the engine notices the application lacks included (#3156).\n const ownership = await this.emailTemplateOwnershipWithCanon(snapshot.backendEmail);\n const { targets, unplaced } = resolveEmailTemplateArtifactPlacement(\n this.getWorkspaceRoot(),\n ownership,\n templateRefs,\n );\n // An unplaced template is known, and listed with why it has no place, never reported as an unknown ref.\n this.assertResolvedEmailTargetsOrThrow([...targets, ...unplaced], snapshot.warnings, templateRefs);\n\n const unplacedResults = unplaced.map((entry): EmailTemplateStatusResult => ({\n ownerId: entry.ownerId,\n templateRef: entry.templateRef,\n templatePath: '',\n templateExists: false,\n locales: [],\n notPlacedBecause: entry.reason,\n }));\n const placedResults = await Promise.all(\n targets.map(async (target) => {\n const templateExists = await fileExists(target.templatePath);\n const localeStatuses = await this.getTemplateLocaleStatuses(target.dirPath);\n\n return {\n ownerId: target.ownerId,\n templateRef: target.templateRef,\n templatePath: target.templatePath,\n templateExists,\n locales: localeStatuses,\n } satisfies EmailTemplateStatusResult;\n }),\n );\n const statusResults = [...placedResults, ...unplacedResults];\n\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n 'email-template-status-success',\n `Resolved status for ${statusResults.length} email templates`,\n {\n templateRefs: templateRefs ?? [],\n resultCount: statusResults.length,\n },\n 'email-template-status-result.json',\n statusResults,\n );\n return statusResults;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-template-status-failure',\n 'Failed to resolve email template status',\n error,\n {\n templateRefs: templateRefs ?? [],\n },\n );\n this.logger.error('Failed to get template status', {\n error: formatUnknownError(error),\n });\n\n if (isWildoBackendError(error)) {\n throw error;\n }\n throw this.errorBuilder.buildFromStandardError(error, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: { operation: 'getTemplateStatus' },\n });\n }\n }\n\n /**\n * Translate owner-scoped email `labels.{source}.ts` files into\n * `labels.{target}.ts` using the companion labelling translation agent.\n *\n * Reads the app package root from the resolved `CompanionContext.saasRoot`\n * snapshot — the companion trusts the context established at bootstrap and\n * does not consult `process.env.COMPANION_WORKSPACE_ROOT` at runtime.\n */\n async translateEmailTemplateLabels(\n request: TranslateEmailTemplateLabelsRequest,\n sessionContext?: CompanionExecutionSessionContext,\n /** In-process only, never part of the request body: the build step's progress port (#2215). */\n options?: { readonly progress?: LabellingProgressReporter },\n ): Promise<TranslateEmailTemplateLabelsResult> {\n const traceStep = this.createWrapperTraceStep(sessionContext, 'translate-email-template-labels');\n await this.traceWrapperStart(\n sessionContext,\n traceStep,\n 'email-label-translation-wrapper-start',\n 'Translate email template labels',\n {\n primaryLocale: this.getDefaultLocale(),\n targetLocales: request.targetLocales ?? [],\n templateRefs: request.templateRefs ?? [],\n dryRun: request.dryRun === true,\n },\n 'email-label-translation-wrapper-request.json',\n request,\n );\n\n try {\n const primaryLocale = this.getDefaultLocale();\n const targetLocales = [...new Set(request.targetLocales ?? [])];\n\n if (!Array.isArray(targetLocales) || targetLocales.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { message: 'targetLocales is required and must be a non-empty array' },\n });\n }\n\n const resolvedTargets = targetLocales.map((code) => this.parseAvailableLanguageOrThrow(code));\n\n for (const t of resolvedTargets) {\n if (t === primaryLocale) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { message: `targetLocales must not include the primary locale (${primaryLocale})` },\n });\n }\n }\n\n /*\n * One translator for email words, not two (#1908). This method used to carry its own: it read\n * only FLAT label files (so it threw on every template keyed by stage or alert type), kept no\n * freshness state (so each run re-translated every email), checked no placeholder, and wrote\n * files the `wildo generate translate` lane knew nothing about. It now plans and runs that lane,\n * so `wildo generate email translate`, the email generation step and `wildo generate translate`\n * write the same files under the same lock and the same contract.\n */\n const plan = await this.emailTemplateLabellingUnits.planEmailTemplateUnits(request.templateRefs);\n this.assertResolvedEmailTargetsOrThrow(plan.units, plan.warnings, request.templateRefs);\n\n const details: TranslateEmailTemplateLabelsResult['details'] = [];\n let translatedFiles = 0;\n let skipped = 0;\n let failed = 0;\n\n if (request.dryRun) {\n for (const unit of plan.units) {\n for (const targetLocale of resolvedTargets) {\n details.push({\n ownerId: unit.ownerId,\n templateRef: unit.templateRef,\n targetLocale,\n success: true,\n outputPath: labelsFilePath(unit.templateDirectory, targetLocale),\n });\n translatedFiles++;\n }\n }\n } else {\n const run = await this.translateOrchestrator.translateEmailTemplates(\n {\n targetLocales: resolvedTargets,\n ...(request.templateRefs?.length ? { templateRefs: request.templateRefs } : {}),\n ...(options?.progress ? { progress: options.progress } : {}),\n },\n sessionContext,\n );\n const unitsById = new Map(plan.units.map((unit) => [unit.id, unit]));\n for (const detail of run.details) {\n const unit = unitsById.get(detail.unitId);\n const succeeded = detail.status === I18nUnitRunStatus.UPDATED || detail.status === I18nUnitRunStatus.FRESH;\n if (detail.status === I18nUnitRunStatus.UPDATED) translatedFiles++;\n else if (detail.status === I18nUnitRunStatus.FRESH || detail.status === I18nUnitRunStatus.SKIPPED) skipped++;\n else failed++;\n details.push({\n ownerId: unit?.ownerId ?? '',\n templateRef: unit?.templateRef ?? detail.unitId,\n targetLocale: detail.targetLocale,\n success: succeeded || detail.status === I18nUnitRunStatus.SKIPPED,\n ...(detail.filePath ? { outputPath: detail.filePath } : {}),\n ...(detail.error ? { error: detail.error } : {}),\n });\n }\n // No registry refresh (#3268): see `generateTemplates`. A preview or a test send refreshes before it reads.\n }\n\n const result = {\n translatedFiles,\n skipped,\n failed,\n warnings: plan.warnings,\n details,\n completedAt: new Date().toISOString(),\n };\n const completedWithFailures = failed > 0;\n await this.traceWrapperSuccess(\n sessionContext,\n traceStep,\n completedWithFailures\n ? 'email-label-translation-wrapper-mixed-result'\n : 'email-label-translation-wrapper-success',\n completedWithFailures\n ? `Translated ${translatedFiles} email label files with ${failed} failures`\n : `Translated ${translatedFiles} email label files`,\n {\n translatedFiles,\n skipped,\n failed,\n warningCount: plan.warnings.length,\n },\n 'email-label-translation-wrapper-result.json',\n result,\n );\n return result;\n } catch (error) {\n await this.traceWrapperFailure(\n sessionContext,\n traceStep,\n 'email-label-translation-wrapper-failure',\n 'Email label translation failed',\n error,\n {\n primaryLocale: this.getDefaultLocale(),\n targetLocales: request.targetLocales ?? [],\n templateRefs: request.templateRefs ?? [],\n dryRun: request.dryRun === true,\n },\n );\n throw error;\n }\n }\n\n private resolvePrimaryGenerationLocale(requestedLocales?: AvailableLanguage[]): AvailableLanguage {\n const resolvedDefault = this.getDefaultLocale();\n\n if (!requestedLocales?.length) {\n return resolvedDefault;\n }\n\n const resolvedRequested = requestedLocales.map((locale) =>\n this.parseAvailableLanguageOrThrow(locale),\n );\n\n if (resolvedRequested.some((locale) => locale !== resolvedDefault)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Email generation only writes the primary locale (${resolvedDefault}). Use /email-templates/translate for additional locales.`,\n },\n });\n }\n\n return resolvedDefault;\n }\n\n /**\n * How many non-empty words a labels file holds, read with the KEYED reader (`parseEmailLabelsTreeSource`, the one the\n * translate lane uses), or `null` when that reader cannot parse it either (#3156).\n */\n private async countKeyedLabelWords(labelsPath: string): Promise<number | null> {\n try {\n const { tree } = parseEmailLabelsTreeSource(await readUtf8File(labelsPath));\n return Object.values(flattenEmailLabelsTree(tree)).filter((word) => word.trim() !== '').length;\n } catch {\n return null;\n }\n }\n\n private async tryReadExistingLabels(\n labelsPath: string,\n ): Promise<Record<string, string> | null> {\n try {\n const source = await readUtf8File(labelsPath);\n return parseEmailLabelsTsSource(source).entries;\n } catch {\n return null;\n }\n }\n\n private buildLabelsTypeName(templateRef: string): string {\n const normalized = templateRef\n .replace(/^system\\./, '')\n .replace(/^email\\./, '')\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n\n return `${normalized || 'Template'}Labels`;\n }\n\n private normalizeGeneratedTemplateSource(templateSource: string): string {\n return templateSource.trimEnd() + '\\n';\n }\n\n private assertTemplateLabelsConsistencyOrThrow(\n templateSource: string,\n labels: Record<string, string>,\n ): void {\n const referencedKeys = new Set<string>();\n // Scan the EXECUTABLE body only — strip `import … from '…'` statements\n // first. The mandatory label-type import\n // (`import type { XLabels } from './labels.<locale>'`, required by the\n // generation prompt) otherwise matches the `labels.<key>` access pattern\n // below and reports the LOCALE segment (e.g. `en`) as a phantom missing\n // label key, failing generation for EVERY template by construction.\n // Labels are only ever READ inside subject()/body(), never in an import\n // specifier, so dropping import statements is safe and removes the whole\n // false-positive class. The lazy `[\\s\\S]*?` spans multi-line imports up to\n // their `from '…'` specifier.\n const scannableSource = templateSource.replace(\n /import\\b[\\s\\S]*?from\\s*['\"][^'\"]*['\"]\\s*;?/g,\n '',\n );\n const labelAccessPatterns = [\n /labels\\.([a-zA-Z0-9_]+)/g,\n /labels\\[['\"]([a-zA-Z0-9_]+)['\"]\\]/g,\n ];\n let match: RegExpExecArray | null = null;\n\n for (const pattern of labelAccessPatterns) {\n while ((match = pattern.exec(scannableSource)) !== null) {\n referencedKeys.add(match[1]);\n }\n }\n\n const destructurePattern = /\\{([^}]+)\\}\\s*=\\s*labels\\b/g;\n while ((match = destructurePattern.exec(scannableSource)) !== null) {\n const destructuredMembers = match[1]\n .split(',')\n .map((member) => member.trim())\n .filter(Boolean)\n .map((member) => member.split(':')[0]?.trim())\n .filter((member): member is string => Boolean(member));\n\n for (const member of destructuredMembers) {\n referencedKeys.add(member);\n }\n }\n\n const missingKeys = Array.from(referencedKeys).filter((key) => !(key in labels));\n if (missingKeys.length > 0) {\n throw new Error(\n `Generated template references missing label keys: ${missingKeys.join(', ')}`,\n );\n }\n }\n\n /**\n * Return the trusted SaaS app root for email template/label file operations.\n *\n * Always reads `this.companionContext.saasRoot`. `COMPANION_WORKSPACE_ROOT`\n * is only a subprocess bootstrap seed (written by\n * `applyTrustedHomesToChildProcess`) and must never override the resolved\n * CompanionContext snapshot at runtime — otherwise a stale env var could\n * silently misroute generated email artifacts to the wrong app.\n */\n private getWorkspaceRoot(): string {\n return this.companionContext.saasRoot;\n }\n\n /**\n * The email template owners, the ENGINE owner answering also for every template the delivered canon carries (#3156).\n * Its refs otherwise come from the application's own registry, which scans the folders it already has, so an engine\n * notice added after the application was created was in no target list and could not be delivered or named. One\n * derivation for generation and status, so status lists exactly what generation would deliver.\n *\n * The build lane's expected paths (`resolveExpectedArtifactRelativePaths`) deliberately keep the application's own\n * registry: they say what a landed build must have committed, and a canon template not yet delivered is not a build\n * step's artifact.\n */\n private async emailTemplateOwnershipWithCanon(\n backendEmail: ReadonlyArray<{ emailTemplateOwnership: EmailTemplateOwnershipPlacement[] }>,\n ): Promise<EmailTemplateOwnershipPlacement[]> {\n const canonRefs = await listTemplateRefsUnderEmailRoot(path.join(this.getWorkspaceRoot(), DELIVERED_EMAIL_CANON_RELATIVE));\n return withDeliveredCanonEngineRefs(backendEmail.flatMap((entry) => entry.emailTemplateOwnership), canonRefs);\n }\n\n /**\n * Answer a template the application does not have yet from the delivered engine canon, with no model\n * call. Answers whether the template now exists.\n *\n * `wildo init` copies the canon once, so an engine email added afterwards reached an existing\n * application only by generating it — the cost the canon exists to avoid, for a template that is the\n * same in every application. This is the email twin of the labelling run's base seeding. It copies\n * the template and the labels of each locale the application serves, and NEVER overwrites: a file\n * that exists is the application's, generated or edited. A template the canon does not carry — the\n * application's own — is generated as before.\n */\n private async seedTemplateFromDeliveredCanon(target: EmailTemplateArtifactTarget): Promise<boolean> {\n const canonDirectory = path.join(this.getWorkspaceRoot(), DELIVERED_EMAIL_CANON_RELATIVE, templateRefToRelativeDir(target.templateRef));\n if (!(await fileExists(templateFilePath(canonDirectory)))) return false;\n const locales = getCompanionEnabledLocaleCodes(this.appConfigService.config as Parameters<typeof getCompanionEnabledLocaleCodes>[0]);\n const copied: string[] = [];\n for (const fileName of [path.basename(templateFilePath(canonDirectory)), ...locales.map((locale) => path.basename(labelsFilePath(canonDirectory, locale)))]) {\n const source = path.join(canonDirectory, fileName);\n const destination = path.join(target.dirPath, fileName);\n if (!(await fileExists(source)) || (await fileExists(destination))) continue;\n await fs.mkdir(target.dirPath, { recursive: true });\n await fs.copyFile(source, destination);\n copied.push(fileName);\n }\n if (copied.length > 0) this.logDebug('Seeded an engine email template from the delivered canon', { templateRef: target.templateRef, copied });\n return fileExists(target.templatePath);\n }\n\n private assertResolvedEmailTargetsOrThrow(\n targets: Array<{ templateRef: string }>,\n warnings: string[],\n requestedTemplateRefs?: string[],\n ): void {\n if (requestedTemplateRefs?.length) {\n const resolvedRefs = new Set(targets.map((target) => target.templateRef));\n const missingRefs = requestedTemplateRefs.filter((templateRef) => !resolvedRefs.has(templateRef));\n\n if (missingRefs.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Unknown email template refs: ${missingRefs.join(', ')}`,\n missingTemplateRefs: missingRefs,\n },\n });\n }\n }\n\n if (targets.length > 0) {\n return;\n }\n\n if (requestedTemplateRefs?.length) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `No email template targets resolved for the requested templateRefs: ${requestedTemplateRefs.join(', ')}`,\n },\n });\n }\n\n if (warnings.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n message: `Email template placement resolution failed: ${warnings.join(' | ')}`,\n },\n });\n }\n }\n\n /**\n * Reload the backend email-definition modules and repopulate the in-memory registry so\n * preview/test-send use the latest filesystem email artifacts.\n */\n private async refreshEmailTemplateRegistry(): Promise<void> {\n const distRoot = this.getPrimaryBackendDistRoot();\n const cacheBust = `${Date.now()}`;\n\n process.env.WILDO_EMAIL_TEMPLATE_IMPORT_BUST = cacheBust;\n\n try {\n /*\n * IN-PROCESS, deliberately (#3268): a preview and a test send RENDER the application's email templates, which are\n * React components imported below, and word them from the initialization config's live label tree and resource\n * schemas. None of that is data. It runs only for a preview or a test send (an operator's action), never for a\n * generation step or a playbook run, so a build wave does not re-import the backend through it.\n */\n const { loadBackendModules, buildApplicationInitializationConfig } = await loadBackendCompanionExports(this.companionContext);\n const backendModules = await loadBackendModules();\n // The application's own label tree and resource schemas, which `EmailBackendService` reads for `fieldValueWord`\n // and `providerName` (bound as `EmailWordSources`), so the preview and test-send say what a send says (#2884).\n try {\n this.applicationEmailWords.load(buildApplicationInitializationConfig());\n } catch (error) {\n this.applicationEmailWords.clear();\n this.logger.warn('[EmailTemplateCompanion] The application\\'s initialization config could not be built; preview shows enum values and provider refs as they are', {\n error: describeCaughtError(error),\n });\n }\n const emailOwnerModules = backendModules.filter((ownedModule) =>\n Object.keys(ownedModule.emailTemplateDefinitions ?? {}).length > 0\n );\n const importedEmailModules = await Promise.all(\n emailOwnerModules.map(async (ownedModule) => {\n const definitionsEntryPath = ownedModule.kind === 'engine'\n ? path.join(distRoot, 'engine/email/email-template-definitions.js')\n // Where the module's own definitions file is (#3904), read from its source; compiled to the same place.\n : moduleEmailDefinitionsEntryPath(distRoot, ownedModule.moduleId);\n const definitionsModuleUrl = `${pathToFileURL(definitionsEntryPath).href}?refresh=${cacheBust}`;\n return import(definitionsModuleUrl) as Promise<{\n emailTemplateDefinitions?: Record<string, {\n template: unknown;\n labels: Record<string, Record<string, string>>;\n }>;\n moduleEmailTemplateDefinitions?: Record<string, {\n template: unknown;\n labels: Record<string, Record<string, string>>;\n }>;\n /** The shared components' words per locale (#2884), exported by the engine email root beside its templates. */\n emailComponentLabels?: Record<string, Record<string, string>>;\n default?: {\n emailTemplateDefinitions?: Record<string, {\n template: unknown;\n labels: Record<string, Record<string, string>>;\n }>;\n };\n }>;\n }),\n );\n\n // The map is chosen by CONTENT (#3904 review F1): a module's definitions file may export it under any name\n // (`clientDocumentsEmailTemplateDefinitions`), so the export whose keys are the module's own template refs is it.\n const refreshedDefinitions: EmailTemplateDefinitionsMap = Object.assign(\n {},\n ...importedEmailModules.map((ownerModule, index) => selectModuleEmailTemplateDefinitions(\n ownerModule as Record<string, unknown>,\n Object.keys(emailOwnerModules[index]?.emailTemplateDefinitions ?? {}),\n )),\n ) as EmailTemplateDefinitionsMap;\n\n this.emailTemplateRegistry.initialize(\n refreshedDefinitions,\n mergeEmailComponentLabels(\n ...importedEmailModules.map((ownerModule) => ownerModule.emailComponentLabels),\n // An owner with component words and no templates has no definitions module to re-import; its words come\n // from the module just loaded, as the placement (and so the translate lane) counts it (#2884).\n ...backendModules\n .filter((ownedModule) => Object.keys(ownedModule.emailTemplateDefinitions ?? {}).length === 0)\n .map((ownedModule) => ownedModule.emailComponentLabels),\n ),\n );\n } finally {\n delete process.env.WILDO_EMAIL_TEMPLATE_IMPORT_BUST;\n }\n }\n\n private getPrimaryBackendDistRoot(): string {\n const backendTarget = resolvePrimaryBackendServiceTarget(this.companionContext);\n return path.resolve(backendTarget.packageRoot, 'dist');\n }\n\n private buildTemplateArtifactGenerationPrompt(\n options: {\n templateRef: string;\n locale: AvailableLanguage;\n labelsTypeName: string;\n currentTemplateSource: string | null;\n existingLabels?: Record<string, string>;\n },\n specContextMarkdown?: string,\n correctionMarkdown?: string,\n ): string {\n const localeName = LANGUAGE_INFO_MAP[options.locale]?.name ?? options.locale;\n // The name a person reads, through the one resolver every email uses (#2873): the display name, else the\n // technical name. The local is named `appDisplayLabel` to avoid colliding with `appIdentity.appName`.\n const appDisplayLabel = applicationDisplayName(this.appConfigService.config.appIdentity);\n\n // Authored-spec context block (DD1: the CUSTOM_IMPLEMENTATION_CONTEXT\n // render — purpose, tone, text-slot meaning, event data, business\n // constraints). Empty when the templateRef has no authored\n // SystemEmailTemplateSpecification — the prompt then falls back to ref +\n // app name + current source only (the context-starved baseline).\n const specContextLines = specContextMarkdown\n ? [\n '',\n '# Email purpose & contract (authored specification — honor over assumptions)',\n 'Generate the template and labels to satisfy this authored spec. It defines',\n \"the email's purpose, tone, the meaning of each text slot, the event data the\",\n 'template receives at send time, and any business constraints. Prefer it over',\n 'inferring intent from the templateRef.',\n '',\n specContextMarkdown.trim(),\n ]\n : [];\n\n // Appended only on a retry — see generateTemplateArtifactsWithAgent's loop.\n const correctionLines = correctionMarkdown\n ? ['', '# Correction (your previous attempt was rejected)', correctionMarkdown.trim()]\n : [];\n\n return [\n `Rewrite or generate the email template artifacts for templateRef \"${options.templateRef}\".`,\n `Primary locale: ${options.locale} (${localeName}).`,\n `Application name: ${appDisplayLabel}.`,\n ...specContextLines,\n '',\n 'Return a JSON object only, with this shape:',\n '{',\n ' \"templateSource\": \"full TSX source for template.tsx\",',\n ' \"labels\": { \"flatLabelKey\": \"Primary locale string\" }',\n '}',\n '',\n 'Code conventions you MUST follow:',\n \"- `templateSource` must be a complete `template.tsx` file.\",\n \"- Import `* as React` from 'react'.\",\n \"- Import `{ type EmailTemplateDefinition, interpolateEmailLabel }` from '@wildo-ai/saas-backend-lib'.\",\n `- Import type \\`${options.labelsTypeName}\\` from './labels.${options.locale}'.`,\n \"- Import UI primitives only from '~backend-api/engine/email/components'.\",\n `- Export a default \\`const template: EmailTemplateDefinition<${options.labelsTypeName}>\\`.`,\n '- Keep all user-visible copy in the `labels` object, not inline in JSX or subject strings.',\n '- Access label values only as direct `labels.someKey` property reads. Do not destructure `labels` and do not use bracket notation.',\n '- Use `interpolateEmailLabel(labels.someKey, { placeholder })` for label strings that contain placeholders like `{appName}`.',\n '- Keep the label object flat and string-only.',\n '- Preserve the current business behavior and context-field access whenever the existing template already expresses it correctly.',\n '',\n 'Current template source (use this as the behavioral source of truth when present):',\n '```tsx',\n options.currentTemplateSource ?? '// No current template source available. Generate a sensible template from scratch.',\n '```',\n '',\n 'Existing primary-locale labels (reuse stable keys when sensible):',\n JSON.stringify(options.existingLabels ?? {}, null, 2),\n ...correctionLines,\n ].join('\\n');\n }\n\n private async generateTemplateArtifactsWithAgent(options: {\n templateRef: string;\n locale: AvailableLanguage;\n labelsTypeName: string;\n currentTemplateSource: string | null;\n existingLabels?: Record<string, string>;\n }, sessionContext?: CompanionExecutionSessionContext): Promise<GeneratedEmailTemplateBundle> {\n // Resolve the authored SystemEmailTemplateSpecification context (purpose,\n // tone, per-slot text-slot meaning, event data, business constraints) and\n // inject it into the prompt so the LLM generates from the email's real\n // contract — not just the templateRef string + current source. Best-effort:\n // a ref with no authored spec generates with generic context (the loader\n // warns and returns undefined; never throws).\n const specContext = await this.emailSpecContextLoader.loadGenerationContext(options.templateRef);\n\n const traceStep = sessionContext\n ? this.traceabilityService.createStep(sessionContext, {\n kind: 'agent-invocation',\n label: `email-template-generation-${options.templateRef}`,\n })\n : undefined;\n\n if (sessionContext) {\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: 'agent-email-template-generation-start',\n summary: `Generate email template artifacts for ${options.templateRef}`,\n payload: {\n templateRef: options.templateRef,\n locale: options.locale,\n hasSpecContext: Boolean(specContext?.description),\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n // spec-context.json — the per-template \"what authored context did this\n // generation receive?\" record. `hasSpecContext:false` flags a ref whose\n // authored SystemEmailTemplateSpecification is missing (the enrichment\n // worklist), mirroring the labellize orchestrator's spec-context.json.\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation.spec-context.json',\n content: {\n templateRef: options.templateRef,\n locale: options.locale,\n hasSpecContext: Boolean(specContext?.description),\n description: specContext?.description ?? null,\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation-input.json',\n content: { options },\n ...(traceStep ? { step: traceStep } : {}),\n });\n }\n\n // Bounded generate → parse/validate → retry-with-correction loop. The LLM\n // occasionally wraps the JSON in prose or emits a malformed object; rather\n // than failing the target outright we re-prompt once with the specific\n // rejection reason appended as a `# Correction` block (mirrors the labellize\n // orchestrator's correction-on-retry). GENERATE_TEXT is retained — the\n // GENERATE_STRUCTURED flip (DD4) stays gated on a provider large-TSX-field\n // truncation check — so the retry delivers the reliability win without it.\n const MAX_ATTEMPTS = 2;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n const prompt = this.buildTemplateArtifactGenerationPrompt(\n options,\n specContext?.description,\n attempt > 1 ? this.buildGenerationCorrection(lastError) : undefined,\n );\n\n const invocation: FlowsActors_Agent_Invocation<\n typeof LLMProvider_GenerateTextInputSchema,\n typeof LLMProvider_GenerateTextOutputSchema,\n typeof LLMProvider_OperationContext_BaseSchema\n > = {\n agentRef: 'email-template.generation.agent',\n initiator: {},\n invocationContext: [],\n input: { prompt },\n output: { text: '' },\n executionContext: { callTimestamp: new Date().toISOString() },\n artifactBindings: [],\n };\n\n // Correlate this attempt so the engine AgentCallTraceSink writes the prompt\n // + output (+usage/latency) into THIS step, keyed by attempt (the attempt\n // rides in the label → filenames stay `…attempt-${n}.prompt.txt/.output.json`).\n // The caller keeps only its composed artifacts (generated.tsx, generated-labels).\n const traceContext = sessionContext && traceStep\n ? {\n sessionRef: sessionContext.sessionId,\n stepRef: traceStep.stepId,\n label: `email-template-generation.attempt-${attempt}`,\n attributes: { templateRef: options.templateRef, locale: options.locale, attempt },\n }\n : undefined;\n\n try {\n const result = await this.agentsService.invokeAgent(invocation, traceContext);\n const bundle = this.parseGeneratedBundle(result.output);\n\n if (sessionContext) {\n // Human-readable twins of the generated output: the template as real\n // TSX (not a JSON-escaped blob) and the labels as pretty JSON.\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation.generated.tsx',\n content: bundle.templateSource,\n format: CompanionTraceArtifactFormat.TEXT,\n ...(traceStep ? { step: traceStep } : {}),\n });\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation.generated-labels.json',\n content: bundle.labels,\n ...(traceStep ? { step: traceStep } : {}),\n });\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: 'agent-email-template-generation-success',\n summary: `Generated email template artifacts for ${options.templateRef}`,\n payload: {\n templateRef: options.templateRef,\n labelCount: Object.keys(bundle.labels).length,\n attempt,\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n }\n\n return bundle;\n } catch (error) {\n lastError = error;\n const isLastAttempt = attempt >= MAX_ATTEMPTS;\n\n if (sessionContext) {\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type: isLastAttempt\n ? 'agent-email-template-generation-failure'\n : 'agent-email-template-generation-retry',\n summary: isLastAttempt\n ? `Failed to generate email template artifacts for ${options.templateRef} after ${attempt} attempt(s)`\n : `Email generation attempt ${attempt} for ${options.templateRef} failed; retrying with correction`,\n payload: {\n templateRef: options.templateRef,\n locale: options.locale,\n attempt,\n error: this.buildTraceErrorPayload(error),\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n if (isLastAttempt) {\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: 'email-template-generation-failure.json',\n content: {\n templateRef: options.templateRef,\n locale: options.locale,\n attempts: attempt,\n error: this.buildTraceErrorPayload(error),\n },\n ...(traceStep ? { step: traceStep } : {}),\n });\n }\n }\n\n if (isLastAttempt) {\n throw error;\n }\n }\n }\n\n // Unreachable: the loop returns a bundle or throws on the final attempt.\n throw lastError;\n }\n\n /**\n * Parse + validate the email-generation agent's raw text output into a\n * `{ templateSource, labels }` bundle. Throws with a specific message (fed\n * back to the model by the retry loop) on empty output, non-JSON output, a\n * missing/blank `templateSource`, or a missing / non-flat / empty `labels`.\n */\n private parseGeneratedBundle(output: unknown): GeneratedEmailTemplateBundle {\n const rawText = (output as { text?: string })?.text;\n if (!rawText || typeof rawText !== 'string') {\n throw new Error('Email generation agent returned empty output');\n }\n\n const jsonMatch = rawText.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n const jsonText = jsonMatch?.[1]?.trim() ?? rawText.trim();\n let parsed: { templateSource?: unknown; labels?: unknown };\n try {\n parsed = JSON.parse(jsonText) as { templateSource?: unknown; labels?: unknown };\n } catch (err) {\n throw new Error(\n `Email generation output was not valid JSON: ${describeCaughtError(err)}`,\n );\n }\n\n if (typeof parsed.templateSource !== 'string' || !parsed.templateSource.trim().length) {\n throw new Error('Email generation output is missing templateSource');\n }\n const templateSource = parsed.templateSource;\n\n if (!parsed.labels || typeof parsed.labels !== 'object' || Array.isArray(parsed.labels)) {\n throw new Error('Email generation output is missing a flat labels object');\n }\n\n const labels: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed.labels as Record<string, unknown>)) {\n if (typeof value !== 'string' || !value.trim().length) {\n throw new Error(`Email generation returned an invalid label for key \"${key}\"`);\n }\n labels[key] = value;\n }\n\n if (Object.keys(labels).length === 0) {\n throw new Error('Email generation returned an empty labels object');\n }\n\n return { templateSource, labels };\n }\n\n /**\n * Build the `# Correction` block appended to the prompt on a retry — feeds\n * the specific rejection reason back so the model fixes exactly that.\n */\n private buildGenerationCorrection(error: unknown): string {\n const reason = describeCaughtError(error);\n return [\n `Your previous attempt was rejected: ${reason}`,\n 'Return ONLY a single JSON object of the exact shape '\n + '{ \"templateSource\": \"<full template.tsx>\", \"labels\": { \"<key>\": \"<non-empty string>\" } } '\n + '— no prose before or after, every label value a non-empty string, the labels object flat.',\n ].join('\\n');\n }\n\n private parseAvailableLanguageOrThrow(code: string): AvailableLanguage {\n const found = Object.values(AvailableLanguage).find((v) => v === code);\n if (!found) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n message: `Unknown locale code \"${code}\". Use an AvailableLanguage value (e.g. en, fr, de).`,\n },\n });\n }\n return found as AvailableLanguage;\n }\n\n private createWrapperTraceStep(\n sessionContext: CompanionExecutionSessionContext | undefined,\n label: string,\n ) {\n return sessionContext\n ? this.traceabilityService.createStep(sessionContext, {\n kind: 'email-template',\n label,\n })\n : undefined;\n }\n\n private async traceWrapperStart(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n type: string,\n summary: string,\n payload: Record<string, unknown>,\n artifactFileName: string,\n artifactContent: unknown,\n ): Promise<void> {\n if (!sessionContext) {\n return;\n }\n\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type,\n summary,\n payload,\n ...(step ? { step } : {}),\n });\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: artifactFileName,\n content: artifactContent,\n ...(step ? { step } : {}),\n });\n }\n\n private async traceWrapperSuccess(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n type: string,\n summary: string,\n payload: Record<string, unknown>,\n artifactFileName: string,\n artifactContent: unknown,\n ): Promise<void> {\n if (!sessionContext) {\n return;\n }\n\n await this.traceabilityService.writeArtifact({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG_VERBOSE,\n fileName: artifactFileName,\n content: artifactContent,\n ...(step ? { step } : {}),\n });\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type,\n summary,\n payload,\n ...(step ? { step } : {}),\n });\n }\n\n private async traceWrapperFailure(\n sessionContext: CompanionExecutionSessionContext | undefined,\n step: ReturnType<CompanionTraceabilityService['createStep']> | undefined,\n type: string,\n summary: string,\n error: unknown,\n payload: Record<string, unknown>,\n ): Promise<void> {\n if (!sessionContext) {\n return;\n }\n\n await this.traceabilityService.traceEvent({\n session: sessionContext,\n minimumLevel: CompanionTraceabilityLevel.DEBUG,\n type,\n summary,\n payload: {\n ...payload,\n error: this.buildTraceErrorPayload(error),\n },\n ...(step ? { step } : {}),\n });\n }\n\n private buildTraceErrorPayload(error: unknown) {\n if (isWildoBackendError(error)) {\n return error;\n }\n\n if (error instanceof Error) {\n return {\n message: error.message,\n name: error.name,\n ...(error.stack ? { stack: error.stack } : {}),\n };\n }\n\n return {\n message: formatUnknownError(error),\n };\n }\n\n /**\n * Resolve the application's default locale for email fallback.\n */\n private getDefaultLocale(): AvailableLanguage {\n return getCompanionConfiguredPrimaryLanguage(this.appConfigService.config);\n }\n\n private getFallbackLocale(): AvailableLanguage {\n return getCompanionConfiguredFallbackLanguage(this.appConfigService.config);\n }\n\n /**\n * Resolve brand tokens the same way the runtime email backend does.\n */\n private getDesignTokens() {\n return buildEmailBrandTokensFromConfig(this.appConfigService.config.email?.brandTokens);\n }\n\n /**\n * List existing locale label artifacts for one filesystem template directory.\n */\n private async getTemplateLocaleStatuses(\n dirPath: string,\n ): Promise<EmailTemplateStatusResult['locales']> {\n let entries: Array<{ name: string; isFile(): boolean }>;\n try {\n entries = (await fs.readdir(dirPath, {\n withFileTypes: true,\n encoding: 'utf8',\n })) as Array<{ name: string; isFile(): boolean }>;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n\n const localeEntries = await Promise.all(\n entries\n .filter((entry) => entry.isFile() && /^labels\\.(.+)\\.ts$/.test(entry.name))\n .map(async (entry) => {\n const localeMatch = entry.name.match(/^labels\\.(.+)\\.ts$/);\n const locale = localeMatch?.[1] ?? 'unknown';\n const labelsPath = labelsFilePath(dirPath, locale);\n const stat = await fs.stat(labelsPath);\n\n return {\n locale,\n labelsPath,\n exists: true,\n updatedAt: stat.mtime.toISOString(),\n };\n }),\n );\n\n return localeEntries.sort((left, right) => left.locale.localeCompare(right.locale));\n }\n}\n"]}
|