@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":"start-companion-application.service.js","sourceRoot":"","sources":["../../../../../src/core/runtime/services/start-companion-application.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,wCAAwC,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,uCAAuC,EAAE,kCAAkC,EAAE,MAAM,mCAAmC,CAAC;AAEhI,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EACL,kBAAkB,EAGlB,kBAAkB,EAClB,wBAAwB,EACxB,cAAc,EACd,gCAAgC,EAChC,YAAY,EACZ,+BAA+B,EAC/B,uCAAuC,EACvC,2BAA2B,EAC3B,mCAAmC,EACnC,0BAA0B,EAC1B,wCAAwC,EACxC,+BAA+B,EAC/B,qCAAqC,EACrC,yCAAyC,EACzC,2DAA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9D,YAAA,MAAM,CAAC,kBAAkB,CAAC,0BAA0B,CAAC,CAAA;IAGrD,YAAA,MAAM,CAAC,kBAAkB,CAAC,4BAA4B,CAAC,CAAA;IAEvD,YAAA,MAAM,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAA;IAG9C,YAAA,MAAM,CAAC,kBAAkB,CAAC,0BAA0B,CAAC,CAAA;IAGrD,YAAA,MAAM,CAAC,uBAAuB,CAAC,mBAAmB,CAAC,CAAA;IAGnD,YAAA,MAAM,CAAC,uBAAuB,CAAC,+BAA+B,CAAC,CAAA;IAE/D,YAAA,MAAM,CAAC,kBAAkB,CAAC,oBAAoB,CAAC,CAAA;IAG/C,YAAA,MAAM,CAAC,uBAAuB,CAAC,iCAAiC,CAAC,CAAA;IAAE,YAAA,QAAQ,EAAE,CAAA;+CArFI,wBAAwB;QAC9B,cAAc;QACQ,gCAAgC;QAC1D,YAAY;QACF,+BAA+B,UAM9D,uCAAuC;QAE5C,2BAA2B;QAEjC,mCAAmC;QAE9B,0BAA0B;QAE5B,+BAA+B;QAE7B,wCAAwC,8DAmBvD,kBAAkB;QAEN,qCAAqC;QAE1C,2DAA2D;QAElD,yCAAyC,oBAMpD,kCAAkC;QAExB,mCAAmC;QAE3C,0CAA0C;QAElC,0CAA0C;QAEvC,6CAA6C;QAE/C,2CAA2C;QAG/C,uCAAuC;GAlFxE,gCAAgC,CAo5C5C","sourcesContent":["import { chmodSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { COMPANION_MODEL_APPLICABILITY_PREFERENCE } from '../companion-model-preference';\nimport { createLanguageModelRunHeartbeatReporter, resolveCompanionLanguageModelRoute } from '../companion-language-model-route';\n\nimport { injectable, inject, optional } from 'inversify';\nimport type { AvailableLanguage } from '@wildo-ai/presets-components-models';\nimport {\n I18nBackendService,\n type AgentsBackendService,\n type ConversationalExecutionBackendService,\n SAAS_SERVICE_TYPES,\n HttpServerBackendService,\n MongoDBService,\n PostgreSQLDatabaseBackendService,\n RedisService,\n FileStorageRouterBackendService,\n ExternalProvidersRegistryBackendService,\n ObservabilityBackendService,\n WorkerShutdownManagerBackendService,\n FlowsActorsRegistryService,\n ControllersRegistryHandlerBackendService,\n ResourcesRegistryBackendService,\n ServicesRegistryHandlerBackendService,\n RepositoriesRegistryHandlerBackendService,\n ResourceOperationCustomImplementationRegistryBackendService,\n mergeBackendDomainModules,\n projectCaughtErrorLogFields,\n projectRetriedAttemptErrorLogFields,\n resolveBackendProviderRegistry,\n type AbstractControllerBackendService,\n type ActorsSystemBackendService,\n type ApplicationInitializationConfig,\n type AppConfiguration_BackendAuthored,\n type ApplicationIdentityBackendService,\n type LoggerService,\n type PdfCollectionExportTemplateBackendService,\n describeCaughtError,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n CoreResourceType, buildSharedSaaSModulesRegistry,\n ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES,\n} from '@wildo-ai/saas-models';\nimport type {\n ResourceConfiguration,\n ResourceConfiguration_InitializationFactoryMap,\n ResourceConfiguration_InitializationFactory,\n ResourceRelationship,\n ResourceType,\n} from '@wildo-ai/saas-models';\nimport {\n registerFeatureSpecifications,\n registerRoleSpecifications,\n type FeatureSpecification,\n type RoleSpecification,\n} from '@wildo-ai/saas-specifications';\nimport {\n PLATFORM_SHARED_SERVICE_TYPES,\n type PlatformAppConfigInitializerService,\n} from '@wildo-ai/platform-shared-lib';\nimport type { SaasRuntimeProvidersArtifact } from '@wildo-ai/platform-config-lib';\nimport { WILDO_PLATFORM_ORGANIZATION_TYPES } from '@wildo-ai/platform-config-lib';\n\nimport { COMPANION_SERVICE_TYPES } from '../../../core/inject/models/service-types';\nimport type { CompanionTraceabilityService } from '../../traceability/companion-traceability.service';\nimport { resolveSchemaPlanSyncState } from '../../../meta-workflows/services/application-build-generation-step.companion.service';\nimport { startSchemaPlanFreshnessLoop } from '../../../meta-workflows/services/schema-plan-freshness-loop.companion';\nimport type { DossierCompanionService } from '../../../meta-workflows/services/dossier.companion.service';\nimport { createWorkbenchGovernedDocumentsPdfTemplate } from '../../../meta-workflows/services/governed-documents-pdf.companion';\nimport { IntrospectionSourceWatcherCompanionService } from '../../introspection/services/introspection-source-watcher.companion.service';\nimport { EventLoopStallMonitor, createEventLoopUtilizationReader } from '../event-loop-stall-monitor.companion';\nimport { HeapPressureMonitor, readCompanionRestartExitCode } from '../heap-pressure-restart.companion';\nimport { startOwedActorReviewRecordRepairTick } from '../owed-actor-review-record-repair-tick.companion';\nimport type { CompanionActorQuestionDeadlineSweepService } from '../../../meta-workflows/services/companion-actor-question-deadline-sweep.companion.service';\nimport { requestCompanionRestart } from '../companion-self-restart.companion';\nimport { IntrospectionResourceNotifierCompanionService } from '../../introspection/resources/introspection-resource-notifier.companion.service';\nimport { IntrospectionResourceSourceCompanionService } from '../../introspection/resources/introspection-resource-source.companion.service';\nimport { CreationPlaneProjectionCompanionService } from '../../introspection/resources/creation-plane-projection.companion.service';\nimport type { ApplicationBuildDispatchCompanionService } from '../../../meta-workflows/services/application-build-dispatch.companion.service';\nimport { createCreationPlaneDispatchFactories } from '../../introspection/resources/creation-plane-dispatch.custom-impl.companion.service';\nimport { CompanionAuthFloorCompanionService } from '../../auth/companion-auth-floor.companion.service';\nimport type { CompanionContext } from '../../context/companion-context';\nimport { META_WORKFLOWS_SYSTEM_REF } from '../../../meta-workflows/models/meta-workflows-lane.models';\nimport { APPLICATION_BUILD_SYSTEM_REF } from '../../../meta-workflows/models/application-build.actors-system.definitions';\nimport {\n buildCompanionResolvedAppConfig,\n parseCompanionPlatformEnv,\n planCompanionPlatformStoreConnections,\n} from '../utils/companion-platform-config.companion';\nimport { CustomShared_ResourceType, WORKBENCH_CREATION_CONVERSATION_SYSTEM_REF, WorkbenchShared_ResourceType } from '@wildo-ai/platform-core-shared';\nimport {\n companionPlatformCoreBackendModule,\n companionPlatformCoreSharedModule,\n companionWorkbenchSharedModule,\n} from '../utils/platform-core-domain-modules.companion';\nimport {\n loadBackendCompanionExports,\n loadSharedLibraryCompanionExports,\n loadSpecificationsCompanionData,\n} from '../../context/companion-package-loaders.companion';\n\n/**\n * Where the companion's resource-registry vocabulary came from at startup.\n * Logged as `registrySource` — the load-bearing diagnostic for the recurring\n * \"companion didn't see the app's resources\" bug class.\n */\nenum ResourceRegistryInitSource {\n /**\n * The application's companion-export surface loaded successfully; the\n * registry mirrors the backend API's vocabulary, unioned with the\n * platform-core persistence vocabulary.\n */\n APP_COMPANION_EXPORTS = 'app-companion-exports',\n /**\n * The app companion-exports could not be loaded (e.g. a not-yet-built\n * `dist`); only the statically-imported platform-core engine vocabulary is\n * registered. App-resource labelling is degraded but startup is never\n * blocked.\n */\n PLATFORM_CORE_FALLBACK = 'platform-core-fallback',\n}\nimport { CodingAgentDispatchCompanionService, type InterruptedRun } from '../../../claude-cli/services/coding-agent-dispatch.companion.service';\nimport { CreationInterventionLedgerCompanionService } from '../../../meta-workflows/services/creation-intervention-ledger.companion.service';\nimport { companionCustomLabels } from '../../../i18n';\nimport { initializeFileStorageWithRetry } from './file-storage-initialization.companion';\n\nexport interface CompanionStartupConfig {\n customControllers: AbstractControllerBackendService[];\n backendConfig?: AppConfiguration_BackendAuthored;\n backendProviderRegistry?: unknown;\n providerRuntime?: SaasRuntimeProvidersArtifact;\n flowsActorsRegistry?: ApplicationInitializationConfig['flowsActorsRegistry'];\n}\n\nconst COMPANION_SHUTDOWN_STEP_TIMEOUT_MS = 5_000;\n\n/**\n * Start Companion Application Service\n *\n * Minimal startup orchestrator for the Dev Companion.\n * The companion API lane now consumes a platform-style env contract, but it\n * still needs local app semantics for label/email/tooling services. The startup\n * path therefore hydrates `AppConfigurationService` itself before handing off to\n * the standard backend runtime bootstrap.\n */\n/**\n * `CompanionStartupConfig.backendProviderRegistry` is typed `unknown` — deliberately, so the companion\n * does not take a type dependency on the private connectors package — so it is CHECKED here rather\n * than cast. A value that is not a fragment is dropped, and the companion then runs on exactly what\n * its own artifact declares, which is the honest outcome: a malformed hand-off should not silently\n * become an unfiltered catalogue.\n */\nfunction asBackendProviderFragment(\n candidate: unknown,\n): Parameters<typeof resolveBackendProviderRegistry>[0]['applicationFragment'] {\n if (typeof candidate !== 'object' || candidate === null) {\n return undefined;\n }\n const modules = (candidate as { modules?: unknown }).modules;\n return modules instanceof Map\n ? (candidate as Parameters<typeof resolveBackendProviderRegistry>[0]['applicationFragment'])\n : undefined;\n}\n\n@injectable()\nexport class StartCompanionApplicationService {\n private readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n private readonly readinessObservationProducerInstanceId = `${process.pid}-${Date.now()}`;\n private readinessObservationHeartbeat: NodeJS.Timeout | null = null;\n private initialized = false;\n private shutdownLifecycleRegistered = false;\n /** See {@link startEventLoopStallMonitor}. */\n private eventLoopStallMonitor: EventLoopStallMonitor | null = null;\n private heapPressureMonitor: HeapPressureMonitor | null = null;\n /** Stops the background schema-plan refresher; the timer is unref'd, so this is hygiene rather than a latch. */\n private stopSchemaPlanFreshnessLoop: (() => void) | null = null;\n /** Stops the periodic owed-actor-review-record repair (#2189); the timer is unref'd, so this is hygiene. */\n private stopOwedActorReviewRecordRepairTick: (() => void) | null = null;\n /** Stops the periodic actor question deadline sweep (#2807); the timer is unref'd, so this is hygiene. */\n private stopActorQuestionDeadlineSweep: (() => void) | null = null;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.HttpServerService) private readonly httpServerService: HttpServerBackendService,\n @inject(SAAS_SERVICE_TYPES.MongoDBService) private readonly mongoDBService: MongoDBService,\n @inject(SAAS_SERVICE_TYPES.PostgreSQLDatabaseService) private readonly postgresqlDatabaseService: PostgreSQLDatabaseBackendService,\n @inject(SAAS_SERVICE_TYPES.RedisService) private readonly redisService: RedisService,\n @inject(SAAS_SERVICE_TYPES.FileStorageRouter) private readonly fileStorageRouter: FileStorageRouterBackendService,\n @inject(SAAS_SERVICE_TYPES.BackendProviderRegistryService)\n private readonly backendProviderRegistryService: {\n initialize(registry: unknown, providerRuntime?: unknown, unresolvedReasons?: ReadonlyMap<string, string>): void;\n },\n @inject(SAAS_SERVICE_TYPES.ExternalProvidersRegistryService)\n private readonly externalProvidersRegistryService: ExternalProvidersRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ObservabilityBackendService)\n private readonly observabilityBackendService: ObservabilityBackendService,\n @inject(SAAS_SERVICE_TYPES.WorkerShutdownManagerService)\n private readonly workerShutdownManager: WorkerShutdownManagerBackendService,\n @inject(SAAS_SERVICE_TYPES.FlowsActorsRegistryService)\n private readonly flowsActorsRegistryService: FlowsActorsRegistryService,\n @inject(SAAS_SERVICE_TYPES.ResourceRegistryService)\n private readonly resourcesRegistryService: ResourcesRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ControllersRegistryHandlerService)\n private readonly controllersRegistryService: ControllersRegistryHandlerBackendService,\n /*\n * The two engine manual controllers the companion mounts for its FRONTEND — injected by token\n * rather than resolved from a container reference, so the dependency is declared where every\n * other one is and a missing binding fails at construction instead of mid-startup.\n */\n @inject(SAAS_SERVICE_TYPES.I18nController)\n private readonly i18nController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.ApplicationConfigController)\n private readonly applicationConfigController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.AuthenticationController)\n private readonly authenticationController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.FeaturesController)\n private readonly featuresController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.FlowsActorsController)\n private readonly flowsActorsController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.ConversationalExecutionBackendService)\n private readonly conversationalExecution: ConversationalExecutionBackendService,\n @inject(SAAS_SERVICE_TYPES.I18nService)\n private readonly i18nService: I18nBackendService,\n @inject(SAAS_SERVICE_TYPES.ServicesRegistryHandlerService)\n private readonly servicesRegistryService: ServicesRegistryHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceOperationCustomImplementationRegistryService)\n private readonly customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService)\n private readonly repositoriesRegistryService: RepositoriesRegistryHandlerBackendService,\n @inject(PLATFORM_SHARED_SERVICE_TYPES.PlatformAppConfigInitializerService)\n private readonly appConfigInitializer: PlatformAppConfigInitializerService,\n @inject(COMPANION_SERVICE_TYPES.CompanionContext)\n private readonly companionContext: CompanionContext,\n @inject(COMPANION_SERVICE_TYPES.AuthFloorService)\n private readonly authFloorService: CompanionAuthFloorCompanionService,\n @inject(COMPANION_SERVICE_TYPES.CodingAgentDispatchService)\n private readonly codingAgentDispatchService: CodingAgentDispatchCompanionService,\n @inject(COMPANION_SERVICE_TYPES.CreationInterventionLedgerService)\n private readonly interventionLedger: CreationInterventionLedgerCompanionService,\n @inject(COMPANION_SERVICE_TYPES.IntrospectionSourceWatcherService)\n private readonly introspectionSourceWatcher: IntrospectionSourceWatcherCompanionService,\n @inject(COMPANION_SERVICE_TYPES.IntrospectionResourceNotifierService)\n private readonly introspectionResourceNotifier: IntrospectionResourceNotifierCompanionService,\n @inject(SAAS_SERVICE_TYPES.IntrospectionResourceSource)\n private readonly introspectionResourceSource: IntrospectionResourceSourceCompanionService,\n /* The creation-plane boards' input signature (#1310): started beside the watcher it listens to. */\n @inject(COMPANION_SERVICE_TYPES.CreationPlaneProjectionService)\n private readonly creationPlaneProjection: CreationPlaneProjectionCompanionService,\n /** The engine's execution driver — settles the playbook runs a previous process left PROCESSING (#1360). */\n @inject(SAAS_SERVICE_TYPES.ActorsSystemBackendService)\n private readonly actorsSystemService: ActorsSystemBackendService,\n /* The collection-export PDF templates (#1645) and the dossier the governed-documents one reads its texts from. */\n @inject(SAAS_SERVICE_TYPES.PdfCollectionExportTemplates)\n private readonly pdfCollectionExportTemplates: PdfCollectionExportTemplateBackendService,\n @inject(COMPANION_SERVICE_TYPES.DossierService)\n private readonly dossierService: DossierCompanionService,\n /* The APPLICATION record's identity, primed at startup because this class replaces the engine's startup (#1767). */\n @inject(SAAS_SERVICE_TYPES.ApplicationIdentityService)\n private readonly applicationIdentity: ApplicationIdentityBackendService,\n /* Trace-session retention, started at boot so a companion that serves few requests still sheds its expired sessions. */\n @inject(COMPANION_SERVICE_TYPES.TraceabilityService)\n private readonly traceabilityService: CompanionTraceabilityService,\n /* The website-copy review sweep (#2593), started once the companion serves: a review a restart lost is redone here. */\n @inject(COMPANION_SERVICE_TYPES.ApplicationBuildDispatchService)\n private readonly buildDispatchService: ApplicationBuildDispatchCompanionService,\n @inject(SAAS_SERVICE_TYPES.AgentsBackendService)\n private readonly agentsService: AgentsBackendService,\n /** #2807: lapses and reminds the companion's own actor questions. Optional and last, so a harness may omit it. */\n @inject(COMPANION_SERVICE_TYPES.ActorQuestionDeadlineSweepService) @optional()\n private readonly actorQuestionDeadlineSweep?: CompanionActorQuestionDeadlineSweepService,\n ) {\n this.logDebug = this.logger.debugByType('StartCompanionApplication');\n this.logger.setDebugTypeLogging('StartCompanionApplication', true);\n }\n\n /**\n * Initialize the companion application using the typed config object.\n */\n public async initialize(config: CompanionStartupConfig): Promise<void> {\n if (this.initialized) {\n this.logDebug('Companion runtime already initialized, skipping');\n return;\n }\n\n this.registerCompanionShutdownLifecycle();\n\n // Start the best-effort heartbeat before the first external dependency can\n // block. A hung Mongo/config/bootstrap phase is then distinguishable from\n // an old companion that never implemented the observation protocol.\n this.startLocalReadinessObservation();\n this.startEventLoopStallMonitor();\n this.startHeapPressureMonitor();\n\n const runtimeEnv = parseCompanionPlatformEnv();\n\n /*\n * Connect whichever platform store this environment actually declares.\n *\n * Unconditional MongoDB until 2026-08-28 (issue #94). On a PostgreSQL-engined platform\n * that made the companion read platform rows — `wildoapplication`, actor tasks, execution\n * rows — from a database the platform had stopped using. Nothing failed: it connected\n * successfully to an EMPTY store, so `resolveOwnership` reported the application as\n * unregistered and every companion execution refused, while the row sat in PostgreSQL.\n * A wrong connection presenting as missing data is why it was misdiagnosed as an\n * uninitialized platform.\n *\n * The env schema has already refused an environment declaring neither store, and refused a\n * selected store without its URL (`DATABASE_DEFAULT_ADAPTER=postgresql` without PG_CONNECT_URL, and\n * since #1117 a MongoDB selection without MONGO_CONNECT_URL), so both branches here are\n * genuinely optional rather than silently permissive.\n */\n const storeConnections = planCompanionPlatformStoreConnections(runtimeEnv);\n if (storeConnections.mongoConnectUrl) {\n this.logDebug('Connecting companion platform MongoDB from env');\n await this.mongoDBService.connectWithUri(storeConnections.mongoConnectUrl);\n }\n if (storeConnections.postgresConnectUrl) {\n // Lazy pool — zero I/O here. The connection must exist before any repository is\n // constructed, because the repositories bind to it at construction time.\n this.logDebug('Connecting companion platform PostgreSQL from env');\n this.postgresqlDatabaseService.connectWithUrl(storeConnections.postgresConnectUrl);\n }\n\n const resolvedAppConfig = await buildCompanionResolvedAppConfig({\n companionContext: this.companionContext,\n env: runtimeEnv,\n backendConfig: config.backendConfig,\n providerRuntime: config.providerRuntime,\n });\n\n this.appConfigInitializer.initializeWithFullConfig({\n serviceName: runtimeEnv.SERVICE_NAME,\n applicationId: runtimeEnv.APPLICATION_ID,\n appSlug: this.companionContext.saasConfig.slug,\n appName: this.companionContext.saasConfig.displayName,\n port: runtimeEnv.PORT,\n fullAppConfig: resolvedAppConfig,\n // The companion hydrates the application's configuration but serves none of its end-user logins.\n servesAuthentication: false,\n });\n\n await this.initializePlatformExecutionPersistence();\n /*\n * The workbench runtimes were initialised here: a domain-plan inbox, an evolution overview and the SPA\n * host, each bound to a durable journal generation and an evolution verification port.\n *\n * All three projected an accepted-state ledger that no longer exists, so they were deleted rather than\n * repointed. When the operator surface returns it initialises at exactly this point — after continuity\n * is ready and before any semantic route is mounted — reading what it shows from git and the run\n * journal.\n */\n\n await this.registerApplicationDefinitionSpecifications();\n await this.initializeCompanionProviderDependencies(config.backendProviderRegistry, config.providerRuntime);\n // Observability reconcile + graceful-flush wiring. The companion does NOT\n // run `StartApplicationBackendService.initialize()` (custom startup), so\n // without this explicit call the LLM-observability sink flush would never\n // be registered with the shutdown coordinator and a supervisor SIGTERM\n // would drop the last buffered `$ai_generation` batch. Must run AFTER\n // `initializeCompanionProviderDependencies` (the provider registry must be\n // initialized for the LLM_OBSERVABILITY / OBSERVABILITY_TELEMETRY selection\n // lookups); never throws.\n this.observabilityBackendService.initialize();\n await this.initializeCompanionFlowsActors(config.flowsActorsRegistry);\n await this.initializePlatformRuntimeDependencies();\n await this.primeApplicationIdentity();\n /*\n * Restart reconciliation of interrupted coding runs — wired 2026-08-24 at exactly the point the\n * 2026-08-23 note reserved (after the runtime dependencies, BEFORE any semantic route is mounted,\n * so no admission can race a stale PROCESSING row). A fresh process cannot prove a previous\n * process's Claude Code subprocess is gone, so each such row terminalizes as ABORTED /\n * INTERRUPTED_REQUIRES_REVIEW with a captured worktree snapshot — evidence for the human, never a\n * revert. BEST-EFFORT: a boot path must not fail closed on something whose remedy needs the very\n * companion it would stop (`continuity-drift-and-cas-basis.md`, Rule 3).\n */\n /*\n * Every run this restart interrupted, coding runs and generation steps alike: their writes are\n * recovered in ONE pass after both sweeps (#1805). They shared one tree, so recovering each kind in\n * its own sweep committed the other kind's files under the first run's name. Collected as each sweep\n * FINDS them, not from what it returns: a sweep can still throw after settling a run ABORTED, and a\n * run lost here is found by no later boot.\n */\n const interruptedRuns: InterruptedRun[] = [];\n const collectInterrupted = (run: InterruptedRun): void => { interruptedRuns.push(run); };\n /*\n * What this boot found in flight, for the intervention ledger (#2231): a boot with runs in flight IS a\n * restart, and this is the only moment that is known — the rows only say each run was interrupted.\n */\n const bootAt = new Date().toISOString();\n const restart = { codingTaskIds: [] as string[], playbookExecutionIds: [] as string[], generationExecutionIds: [] as string[] };\n try {\n const { reconciledTaskIds } = await this.codingAgentDispatchService.reconcileInterruptedApplicationCodingTasks(undefined, { onInterrupted: collectInterrupted });\n restart.codingTaskIds.push(...reconciledTaskIds);\n // Always logged, so \"the reconciliation ran and found nothing\" is distinguishable from \"it never\n // ran\" — a silent best-effort step is unverifiable (negative-results rule).\n this.logDebug('Startup coding-task reconciliation completed', { interrupted: reconciledTaskIds.length });\n if (reconciledTaskIds.length > 0) {\n this.logger.warn(\n 'Startup reconciliation terminalized interrupted application-coding task(s) as '\n + 'INTERRUPTED_REQUIRES_REVIEW — a previous companion process left them PROCESSING. '\n + 'Review their captured change sets before retrying.',\n { reconciledTaskIds },\n );\n }\n } catch (error) {\n this.logger.warn('Startup coding-task reconciliation failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n /*\n * Restart reconciliation of ORPHANED playbook runs (#1360). Since #1358 a playbook run is an actor\n * execution the engine's driver opens and settles — and the only thing that settles it is the\n * driver in the process that opened it. A companion taken away mid-run (ordinary here: parallel\n * sessions land engine code and the supervisor respawns it) left that execution and its task at\n * PROCESSING forever, a run that reads as \"running\" with nothing running it. A companion that has\n * just started is running nothing, and there is one per application, so every PROCESSING\n * execution of its system is an orphan by construction: settled ABORTED, its progress checkpoint\n * left in place so re-running the composite continues it.\n *\n * Same place and same posture as the coding reconciliation above: before any semantic route is\n * mounted, and BEST-EFFORT — a boot path must not fail closed on something whose remedy needs the\n * very companion it would stop.\n */\n try {\n const { aborted, restored } = await this.actorsSystemService.reconcileOrphanedActorExecutions(META_WORKFLOWS_SYSTEM_REF);\n restart.playbookExecutionIds.push(...aborted, ...restored);\n this.logDebug('Startup playbook-run reconciliation completed', { aborted: aborted.length, restored: restored.length });\n if (restored.length > 0) {\n this.logger.warn(\n 'Startup reconciliation put playbook run(s) back to waiting on their question — a previous companion process '\n + 'stopped while continuing an answer. Answer again to continue.',\n { restored },\n );\n }\n if (aborted.length > 0) {\n this.logger.warn(\n 'Startup reconciliation settled orphaned playbook run(s) ABORTED — a previous companion process left them '\n + 'PROCESSING. A composite among them keeps its progress checkpoint: re-run it to continue.',\n { aborted },\n );\n }\n } catch (error) {\n this.logger.warn('Startup playbook-run reconciliation failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n /*\n * The agent-work records a previous process OWED (#1599 I3, #1922): a review of an actor's work whose settle won\n * and whose process died before its record. The settling swap left the whole record on the row; this writes it\n * (`ROW_REPAIR`, metadata only). No grace: a companion that has just started holds no settle in flight, and it is\n * the only writer of its application's actor rows. Best-effort, like the reconciliations above — a repair that\n * fails leaves its marker for the next start.\n */\n try {\n const repair = await this.actorsSystemService.repairOwedActorCorrectionRecords(undefined, { graceMs: 0 });\n if (repair.failed > 0) {\n this.logger.warn('Startup could not write every owed actor review record; their markers stay for the next repair tick.', { ...repair });\n }\n } catch (error) {\n this.logger.warn('Startup actor review record repair failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n // And on a clock (#2189): a record write that failed without a crash is repaired within a minute, not at the next start.\n this.stopOwedActorReviewRecordRepairTick ??= startOwedActorReviewRecordRepairTick({\n repair: () => this.actorsSystemService.repairOwedActorCorrectionRecords(),\n logger: this.logger,\n describeError: describeCaughtError,\n });\n /*\n * And the clocks of the companion's own actor questions (#2807): a question whose system declares deadlines lapses\n * LAPSED and fires each reminder stage once, every minute. The engine's sweep reads only an application's actor plane\n * and is inert here. Nothing to read until a companion system declares deadlines.\n */\n this.stopActorQuestionDeadlineSweep ??= this.actorQuestionDeadlineSweep?.startPeriodicSweep() ?? null;\n /*\n * And the build system's (#1359): a companion GENERATION STEP is an execution too, since the day\n * it stopped living in an in-memory list of the last five dispatches. A restart in the middle of a\n * forty-minute label pass used to leave nothing anywhere saying it had been running; it now leaves\n * an orphan, settled ABORTED here. Its product is files on disk and the pipelines skip fresh\n * units, so re-dispatching the step continues rather than repeats. A coding dispatch that was\n * SELECTED and never admitted is swept by the coding reconciliation above — the engine reads\n * PENDING as well as PROCESSING.\n */\n try {\n const { aborted } = await this.codingAgentDispatchService.reconcileInterruptedBuildGenerationSteps(APPLICATION_BUILD_SYSTEM_REF, undefined, { onInterrupted: collectInterrupted });\n restart.generationExecutionIds.push(...aborted);\n this.logDebug('Startup build-dispatch reconciliation completed', { aborted: aborted.length });\n if (aborted.length > 0) {\n this.logger.warn(\n 'Startup reconciliation settled orphaned build generation step(s) ABORTED — a previous companion process '\n + 'left them running. What they had written is recovered next, under the autonomy posture; re-dispatch the step '\n + 'and its pipelines skip the units that are already fresh.',\n { aborted },\n );\n }\n } catch (error) {\n this.logger.warn('Startup build-dispatch reconciliation failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n try {\n await this.codingAgentDispatchService.recoverWritesOfInterruptedRuns(interruptedRuns);\n } catch (error) {\n this.logger.warn('Startup recovery of interrupted runs\\' writes failed; they stay for review (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n // Never throws: a report must not stop a boot. Writes nothing when nothing was in flight.\n await this.interventionLedger.recordRestart({ bootAt, ...restart });\n await this.initializePlatformHttpServer(config.customControllers);\n\n this.initialized = true;\n /*\n * Shed expired read-request trace sessions now, not only when the first request arrives: the sweep was\n * request-triggered, so an application whose companion is started and barely used kept its backlog\n * indefinitely (5.9 GB measured on scratch-journey). Fire-and-forget and best-effort inside the service.\n */\n this.traceabilityService.startReadRequestSessionRetention();\n this.startLocalReadinessObservation();\n this.logDebug('Dev Companion Application started');\n }\n\n private async initializePlatformExecutionPersistence(): Promise<void> {\n const registryInit = await this.resolveResourceRegistryInitInputs();\n\n // The companion signs people in against the PLATFORM database, whose organizations are of the platform's own type, so\n // the role rule must know that type (#3202). The configuration keeps the application's types: it describes the\n // application, and the configuration boundary refuses any other `organizationTypes`.\n this.resourcesRegistryService.useIdentityStoreOrganizationTypes(WILDO_PLATFORM_ORGANIZATION_TYPES);\n\n /*\n * The two `as never` crossings that stood here are gone: `ResourceConfiguration_InitializationFactoryMap`\n * used without a type argument resolved to `undefined`, so the engine signature literally accepted\n * `undefined` and these real maps had to be forced through it. The bare form now resolves to the\n * open map, so the maps assembled above are assignable on their own terms (#44).\n */\n await this.resourcesRegistryService.initialize(\n registryInit.sharedConfigurations,\n registryInit.sharedFieldIdentifiers,\n registryInit.sharedRelationships,\n registryInit.backendConfigurations,\n registryInit.backendFieldIdentifiers,\n registryInit.backendRelationships,\n );\n\n const resourcesRegistry = this.resourcesRegistryService.getResourcesRegistry();\n const resourceConfigurations = new Map(\n Object.entries(resourcesRegistry.resourceConfigurations) as [\n ResourceType,\n ResourceConfiguration<any, any, any>,\n ][],\n );\n\n await this.repositoriesRegistryService.initializeRepositories(\n resourceConfigurations,\n this.mongoDBService.getConnection() || undefined,\n );\n\n // Keep the registry-mirror signal (source + count) but NOT the full\n // resourceTypes list: dumping all ~78 keys floods the dev console on every\n // startup. `registrySource` (a `ResourceRegistryInitSource` value)\n // and `resourceCount` are enough to confirm the companion mirrored the\n // backend registry — the load-bearing diagnostic for the recurring\n // \"companion didn't see the app's resources\" bug class.\n this.logDebug('Companion platform execution persistence initialized', {\n registrySource: registryInit.source,\n resourceCount: resourceConfigurations.size,\n });\n }\n\n /**\n * Register the application's app-level definition specifications (roles +\n * features) into the `@wildo-ai/saas-specifications` cross-registry — the\n * missing app half of a documented two-step registration chain.\n *\n * `getAllRegisteredRoleSpecifications()` (and the feature twin) is the source\n * of truth the companion i18n labelling collector reads (`collectRoleKeys()`\n * in `i18n-labelling/utils/role-lifecycle-keys.utils.ts` derives\n * `roles.<ref>.{label,description}` from it) AND the source the cross-registry\n * assertions resolve `roleRefs` / `requiredFeatures` against. The engine\n * registers its 12 core roles + baseline features as an import side-effect of\n * `@wildo-ai/saas-specifications` (`engine/_bootstrap.ts`), but an\n * application's OWN roles/features — the extendable-enum arm\n * (`RolesSchema = … | z.string().min(1)`, for example application-defined\n * `CUSTOM_APP_MANAGER` / `CUSTOM_ORG_SUPERVISOR`) — were only ever handed to\n * the companion as companion-export DATA for the context factory; nothing ever\n * registered them. Consequence (the bug this fixes): `collectRoleKeys()` saw\n * only the engine baseline, so every app-defined role got NO label key and\n * fell back to a humanized token at runtime.\n *\n * Safe by construction: the app's `roleSpecifications` / `featureSpecifications`\n * companion-exports already spread the engine baseline in FIRST (see the app's\n * `buildRoleSpecificationMap(...engineRoleSpecifications, …customRoles)`), and\n * `register*Specifications` is idempotent with a shape-equality guard — so\n * re-registering the engine entries is a no-op and only the app's own entries\n * are actually added.\n *\n * Scope — roles + features ONLY. Both are already in populated / fail-closed\n * mode from the engine bootstrap, so adding app entries cannot flip validation\n * semantics. Milestone/product are engine-EMPTY (fail-soft pass-through);\n * registering them would flip fail-soft → fail-closed and could surface a\n * previously-tolerated dangling ref, so they are deliberately out of scope and\n * belong in a dedicated pass.\n *\n * Best-effort: a specifications package whose authored source cannot be\n * evaluated yet (mid-edit, or importing a sibling package that is not built)\n * must not block companion startup (mirrors\n * {@link resolveResourceRegistryInitInputs}). On failure the\n * companion still starts; app-defined role/feature labels simply stay\n * un-generated until the package resolves.\n */\n private async registerApplicationDefinitionSpecifications(): Promise<void> {\n try {\n const specExports = await loadSpecificationsCompanionData(this.companionContext);\n\n const roleSpecifications = specExports.roleSpecifications as RoleSpecification | undefined;\n const featureSpecifications = specExports.featureSpecifications as\n | FeatureSpecification\n | undefined;\n\n if (roleSpecifications) registerRoleSpecifications(roleSpecifications);\n if (featureSpecifications) registerFeatureSpecifications(featureSpecifications);\n\n this.logDebug('Companion registered application definition specifications', {\n roleSpecCount: roleSpecifications ? Object.keys(roleSpecifications).length : 0,\n featureSpecCount: featureSpecifications ? Object.keys(featureSpecifications).length : 0,\n });\n } catch (error: unknown) {\n this.logger.warn(\n 'Companion could not register application role/feature specifications into the '\n + 'specifications cross-registry; app-defined roles/features will be ABSENT from i18n '\n + 'label-key collection and cross-registry assertions until this resolves.',\n { error: describeCaughtError(error) },\n );\n }\n }\n\n /**\n * Resolve the inputs for the companion's `ResourcesRegistry` initialization.\n *\n * The companion must see the SAME resource vocabulary the backend API runtime\n * sees — engine resources AND the application's own domain resources — so that\n * every registry-driven companion lane materializes the full surface. The most\n * load-bearing consumer today is the i18n labelling planner: `planResourceUnits`\n * enumerates `resourcesRegistryService.getResourcesRegistry().resourceConfigurations`\n * and emits one `resource:<type>` unit per entry. If the app's resources are\n * absent here, they are labellized by NOBODY (the frontend-derived lane\n * deliberately drops `resources.*`, deferring to `planResourceUnits`), and the\n * app's own resources fall back at runtime to humanized field names.\n *\n * The application exposes its full module set through the standard\n * companion-export surface — `loadSharedModules()` returns\n * `[engineSharedModule, ...appSharedModules]` and `loadBackendModules()` the\n * matching backend owners — the SAME set the backend API builds its registry\n * from (`buildSharedSaaSModulesRegistry` + `mergeBackendDomainModules`). We\n * mirror that assembly here — and then UNION the platform-core persistence\n * vocabulary on top (see the inline comment in the success branch): the\n * companion is also the local platform microservice for execution rows, so\n * its registry = backend-API vocabulary ∪ platform-core persistence\n * vocabulary, with app/engine registrations winning on key collisions.\n *\n * Best-effort with a hard fallback: if the app companion-exports cannot be\n * loaded (e.g. a not-yet-built `dist`), fall back to the statically-imported\n * platform-core engine vocabulary so the companion still starts. The fallback\n * degrades app-resource labelling but never blocks startup — strictly no worse\n * than the prior platform-core-only behavior.\n */\n private async resolveResourceRegistryInitInputs(): Promise<{\n source: ResourceRegistryInitSource;\n sharedConfigurations: Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>;\n sharedFieldIdentifiers: { [key: string]: string } | undefined;\n sharedRelationships: ResourceRelationship[];\n backendConfigurations: Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>;\n backendFieldIdentifiers: { [key: string]: string } | undefined;\n backendRelationships: ResourceRelationship[];\n }> {\n try {\n /*\n * IN-PROCESS, deliberately (#3268): the companion's own resource registry is built from these modules, whose\n * resource configurations are FACTORIES this process calls, so they cannot arrive as data. This runs once, at\n * boot, in the same module generation as the assembly's backend read; no reader of a build wave re-imports either\n * package for it.\n */\n const [sharedExports, backendExports] = await Promise.all([\n loadSharedLibraryCompanionExports(this.companionContext),\n loadBackendCompanionExports(this.companionContext),\n ]);\n const [sharedModules, backendOwnedModules] = await Promise.all([\n sharedExports.loadSharedModules(),\n backendExports.loadBackendModules(),\n ]);\n\n const sharedRegistry = buildSharedSaaSModulesRegistry(...sharedModules);\n const mergedBackend = mergeBackendDomainModules(\n ...backendOwnedModules.flatMap((ownedModule) =>\n ownedModule.backendModule ? [ownedModule.backendModule] : [],\n ),\n );\n\n // UNION, not either/or: the app companion-exports mirror carries the\n // backend-API vocabulary (engine + app modules — what labelling and\n // spec lanes need), but the companion is ALSO the local platform\n // microservice that persists execution rows (`wildoApplication`,\n // `wildoApplicationActorSystemExecutions`, `wildoApplicationActorTasks`,\n // …) — a PLATFORM-plane vocabulary the backend-API registry does NOT\n // contain. The 2026-06-17 mirror fix made this branch app-exports-only,\n // silently evicting those platform resources: every live\n // `CompanionExecutionsCompanionService` call then failed ownership\n // resolution with `repositories_registry_not_found` (it reads the\n // `wildoApplication` repo first). Unit tests mock the repositories, so\n // the first live coding-agent dispatch (meta-workflows Step 4,\n // 2026-07-03) is what surfaced it. Spread order pins app/engine\n // registrations to WIN over a same-keyed platform-core entry.\n return {\n source: ResourceRegistryInitSource.APP_COMPANION_EXPORTS,\n // These spreads carried a `Record<string, unknown>` cast each, plus an extra `unknown` hop on\n // the app registry, and an outer assertion to put the factory type back. All of it existed\n // because `ResourceConfiguration_InitializationFactoryMap` used without a type argument\n // resolved to `undefined`, so every field carrying that alias was statically `undefined`\n // while holding a real map. The alias now resolves to the open map, so the spreads type\n // themselves (#44).\n /*\n * The workbench module is spread FIRST so the existing precedence is untouched: an app or\n * engine registration of the same key still wins, exactly as it wins over platform-core.\n * Its keys are workbench-specific (`workbench*`), so a collision would itself be a defect.\n */\n sharedConfigurations: {\n ...companionWorkbenchSharedModule.resourceConfigurations,\n ...companionPlatformCoreSharedModule.resourceConfigurations,\n ...sharedRegistry.resourceConfigurations,\n },\n sharedFieldIdentifiers: {\n ...(companionWorkbenchSharedModule.resourceFieldIdentifiers ?? {}),\n ...(companionPlatformCoreSharedModule.resourceFieldIdentifiers ?? {}),\n ...(sharedRegistry.resourceFieldIdentifiers ?? {}),\n },\n sharedRelationships: [\n ...(companionWorkbenchSharedModule.resourceRelationships ?? []),\n ...(companionPlatformCoreSharedModule.resourceRelationships ?? []),\n ...(sharedRegistry.resourceRelationships ?? []),\n ],\n backendConfigurations: {\n ...(companionPlatformCoreBackendModule.resourceConfigurations ?? {}),\n ...(mergedBackend.resourceConfigurations ?? {}),\n },\n backendFieldIdentifiers: {\n ...(companionPlatformCoreBackendModule.resourceFieldIdentifiers ?? {}),\n ...(mergedBackend.resourceFieldIdentifiers ?? {}),\n },\n backendRelationships: [\n ...(companionPlatformCoreBackendModule.resourceRelationships ?? []),\n ...(mergedBackend.resourceRelationships ?? []),\n ],\n };\n } catch (error: unknown) {\n this.logger.warn(\n 'Companion could not load application companion-exports for the resources registry; falling back to platform-core engine vocabulary only. Application-owned resources will be ABSENT from the companion registry — their i18n labels will not be generated until this resolves.',\n { error: describeCaughtError(error) },\n );\n /*\n * The workbench vocabulary is unioned HERE TOO, and that is the point of this block existing\n * separately: its resources are INTROSPECTION-backed projections served by this companion, so\n * they are exactly the ones that must survive an application whose companion-exports failed to\n * load. Registering them only on the success path would make the operator surface disappear\n * precisely when someone needs it to see WHY the application will not load.\n */\n return {\n source: ResourceRegistryInitSource.PLATFORM_CORE_FALLBACK,\n sharedConfigurations: {\n ...(companionWorkbenchSharedModule.resourceConfigurations as Record<string, unknown>),\n ...(companionPlatformCoreSharedModule.resourceConfigurations as Record<string, unknown>),\n } as Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>,\n sharedFieldIdentifiers: {\n ...(companionWorkbenchSharedModule.resourceFieldIdentifiers ?? {}),\n ...(companionPlatformCoreSharedModule.resourceFieldIdentifiers ?? {}),\n },\n sharedRelationships: [\n ...(companionWorkbenchSharedModule.resourceRelationships ?? []),\n ...(companionPlatformCoreSharedModule.resourceRelationships ?? []),\n ],\n backendConfigurations:\n (companionPlatformCoreBackendModule.resourceConfigurations ?? {}) as Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>,\n backendFieldIdentifiers: companionPlatformCoreBackendModule.resourceFieldIdentifiers,\n backendRelationships: companionPlatformCoreBackendModule.resourceRelationships ?? [],\n };\n }\n }\n\n /**\n * The companion is the FOURTH host of the on-demand provider loader (#330), and the only one that\n * used to pass no topology at all.\n *\n * It already loaded its own `companion.runtime-providers.generated.json` — `loadProviderRuntime` in\n * `companion-startup-assembly.ts` reads it and hands it over as `config.providerRuntime` — and then\n * initialised the registry without it, which meant the companion process received the ENGINE'S\n * WHOLE CATALOGUE: twenty-two provider modules, six pulling a model SDK, for a scope that names a\n * handful. So closing this seam needed no new request shape and no new file, only the wiring of a\n * value that was already in hand.\n *\n * The artifact reaches `initialize` too, so the companion gets the same fail-loud refusal every\n * other host gets when its scope names a provider nothing can supply.\n */\n private async initializeCompanionProviderDependencies(\n backendProviderRegistry: unknown,\n providerRuntime: CompanionStartupConfig['providerRuntime'],\n ): Promise<void> {\n const resolved = await resolveBackendProviderRegistry({\n // The companion artifact is single-scope (`artifactKind: 'companion'`, `scope` already projected\n // by the CLI). It satisfies the loader's `DeclaredProviderTopology` structurally, which is why\n // that contract is stated as a shape rather than as the backend's nominal artifact type.\n providerRuntime,\n applicationFragment: asBackendProviderFragment(backendProviderRegistry),\n });\n this.backendProviderRegistryService.initialize(resolved.registry, providerRuntime, resolved.unresolved);\n this.logDebug('Companion backend provider registry initialized', {\n providerRuntimeApplied: Boolean(providerRuntime),\n providerCount: resolved.registry.modules.size,\n });\n\n await this.externalProvidersRegistryService.refreshFromConfig();\n // #3002: a configuration pointing a provider at a secret its module does not declare is refused here as in the\n // application backend, so the companion does not start reading it as \"not enabled\". The remedy is a file edit.\n this.externalProvidersRegistryService.assertAuthoredSecretRefsDeclared();\n }\n\n private async initializeCompanionFlowsActors(flowsActorsRegistry: CompanionStartupConfig['flowsActorsRegistry']): Promise<void> {\n // The companion's judgment work runs on Opus 5.5, not the framework default (2026-11-06): set before any agent resolves.\n this.flowsActorsRegistryService.useModelApplicabilityPreference(COMPANION_MODEL_APPLICABILITY_PREFERENCE);\n await this.flowsActorsRegistryService.initialize(\n flowsActorsRegistry?.flowActorSystemsFactoryMap,\n flowsActorsRegistry?.agents,\n /*\n * The third collection the engine's own startup passes and this one never did: without it an\n * agent's declared function refs resolve to nothing. The creation assistant (#1454) is the\n * first companion agent whose work IS its function tools.\n */\n flowsActorsRegistry?.functionTools,\n );\n this.installLanguageModelRoute();\n }\n\n /**\n * Route the companion's language-model calls through Claude Code over ACP (#3472), unless\n * `WILDO_LANGUAGE_MODEL_TRANSPORT=api`.\n *\n * A route that cannot be installed — the ACP binding not enabled in this application's provider configuration — is\n * reported as an ERROR naming the consequence, and the calls stay on the API keys: refusing to start would take down\n * every surface of the companion for a cost concern, and the error is what makes the cost visible.\n */\n private installLanguageModelRoute(): void {\n // The heartbeat that holds a supervisor restart while a routed call's agent is running (#3472, 2026-11-15).\n const route = resolveCompanionLanguageModelRoute(\n process.env,\n createLanguageModelRunHeartbeatReporter(this.companionContext.saasRoot, (message, error) =>\n this.logger.warn(message, { reason: describeCaughtError(error) })),\n );\n if (route === undefined) {\n this.logger.info('Language-model calls stay on the API keys (WILDO_LANGUAGE_MODEL_TRANSPORT=api)');\n return;\n }\n try {\n this.agentsService.routeLanguageModelCallsOverAgentClientProtocol(route);\n } catch (error) {\n this.logger.error('Language-model calls could NOT be routed over ACP and will spend the API keys', {\n acpProviderRef: route.acpProviderRef,\n executionProfileRef: route.executionProfileRef,\n model: route.model,\n reason: describeCaughtError(error),\n });\n }\n }\n\n /**\n * Platform-mode startup in `StartApplicationBackendService` intentionally skips\n * provider, Redis, storage, and HTTP phases because platform owners usually\n * restore them explicitly once their config is hydrated. The companion uses the\n * same pattern so its API lane becomes a truthful local platform microservice\n * rather than a partially initialized app-backend bootstrap.\n */\n private async initializePlatformRuntimeDependencies(): Promise<void> {\n if (this.fileStorageRouter.isConfigured()) {\n /*\n * Retried rather than attempted once (#1195): these credentials come from apps-manager, which the\n * companion routinely starts alongside, and storage is fail-closed — so losing that race once left\n * file operations dead for the whole process lifetime while readiness kept answering 200.\n */\n await initializeFileStorageWithRetry({\n initialize: () => this.fileStorageRouter.initialize(),\n onReady: (attempt) => { this.logDebug('Companion file storage initialized', { attempt }); },\n onRetry: ({ attempt, error }) => {\n // Without the level floor: an attempt the loop repeats is not the fault — `onExhausted` is,\n // and it keeps the floor (#1637; `projectRetriedAttemptErrorLogFields`).\n this.logDebug('Companion file storage initialization failed; retrying', {\n attempt,\n ...projectRetriedAttemptErrorLogFields(error),\n });\n },\n onExhausted: ({ attempts, error }) => {\n this.logger.warn(\n 'Companion file storage initialization failed; file operations may fail at runtime',\n {\n // NOT `error instanceof Error ? … : String(error)`. `WildoError_Backend`\n // is a plain object, never an `Error`, so that ternary rendered the one\n // diagnostic this path produces as the literal '[object Object]' — which\n // is non-empty and carries exactly as much information as empty. Storage\n // is fail-closed with no fallback, so this message is all a reader gets.\n attempts,\n ...projectCaughtErrorLogFields(error),\n },\n );\n },\n });\n }\n\n await this.externalProvidersRegistryService.refreshFromConfig();\n // #3002: as after the provider registry's first refresh above.\n this.externalProvidersRegistryService.assertAuthoredSecretRefsDeclared();\n\n try {\n await this.redisService.connect();\n this.logDebug('Companion Redis connection established');\n } catch (error) {\n this.logger.warn(\n 'Companion Redis connection failed; runtime fallbacks may be used where supported',\n {\n error: describeCaughtError(error),\n },\n );\n }\n }\n\n /**\n * Settle the creation CONVERSATION's turns this companion was running when it stopped (#1601): such a\n * turn is left PROCESSING for ever, and the creator's message reads as unanswered with nothing saying\n * why. The companion is the only host of this system, which is what makes a startup settlement\n * correct (see `settleInterruptedTurns`). Best-effort, like the startup reconciliations.\n *\n * ORDER IS THE WHOLE CONTRACT, on both sides:\n * - AFTER `initializeWorkbenchResourceControllers`, which is where the three `*FlowActorExecutions`\n * services come into existence. Called earlier (as it first was, 150451c8), every listing answered\n * `service_not_found` and the settlement reported `settled: 0` on every boot — inert, and quiet\n * about it, measured 2026-09-25.\n * - BEFORE the HTTP and WebSocket server listens, so no turn started by THIS process can exist yet:\n * everything still PROCESSING belongs to a host that is gone.\n */\n private async settleInterruptedConversationTurns(): Promise<void> {\n try {\n await this.conversationalExecution.settleInterruptedTurns([WORKBENCH_CREATION_CONVERSATION_SYSTEM_REF]);\n } catch (error) {\n this.logger.warn('Startup conversation-turn settlement failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n }\n\n private async initializePlatformHttpServer(\n customControllers: AbstractControllerBackendService[],\n ): Promise<void> {\n // P-29 auth floor — BEFORE the server starts listening: fail-closed\n // loopback assertion (no override env) + companion.token (0600) for\n // the token middleware on mutating routes. Runs after app-config\n // hydration because host resolution reads `runtime.endPoints`.\n await this.authFloorService.enforceStartupInvariants();\n\n await this.registerCustomControllers(customControllers);\n await this.initializeWorkbenchResourceControllers();\n await this.settleInterruptedConversationTurns();\n /*\n * The WebSocket server is MOUNTED, because this companion serves a frontend.\n *\n * It was skipped when the companion answered only the CLI. The workbench changed that: an\n * authenticated Wildo frontend opens a socket unconditionally — `UserOrgsContext` calls\n * `connectWebSocket` the moment a session restores, and there is no configuration that says\n * \"this backend has no realtime\". So skipping it does not mean \"no realtime\", it means a socket\n * that retries forever against a port with nothing listening, which the operator sees as a\n * permanent \"Reconnecting\" and which no log explains.\n */\n await this.httpServerService.initialize({ skipWebSocket: false });\n\n await this.startIntrospectionFreshnessPlane();\n this.startWebsiteCopyReviewSweep();\n this.startWebsiteVisualReviewSweep();\n }\n\n /**\n * Review the website runs whose copy review is missing or out of date (#2593). A run's review is started when the run\n * completes and is lost when the companion restarts during the judge call, which every engine change can cause; this\n * is where it is redone, and where a review that failed before (NOT_REVIEWED) is retried. Started and not awaited:\n * each review is a model call, and none of it is something startup should wait for or fail on.\n */\n private startWebsiteCopyReviewSweep(): void {\n void this.buildDispatchService.requestWebsiteCopySweep({ retryNotReviewed: true }).catch((error: unknown) => {\n this.logger.warn('The website copy review sweep could not start', { error: describeCaughtError(error) });\n });\n }\n\n /**\n * Review the website runs whose drawing has no review (#2785), retrying one that could not be reviewed before (the\n * website was not running, the camera was missing). Started and not awaited, like the copy sweep: each review\n * photographs a page and calls a model, and startup neither waits for it nor fails on it.\n */\n private startWebsiteVisualReviewSweep(): void {\n void this.buildDispatchService.requestWebsiteVisualSweep({ retryNotReviewed: true }).catch((error: unknown) => {\n this.logger.warn('The website visual review sweep could not start', { error: describeCaughtError(error) });\n });\n }\n\n /**\n * Resolve and cache the APPLICATION record's identity, which the engine's own startup does at its\n * step 7.65 and this custom startup must do itself.\n *\n * Every SYNCHRONOUS reader of the canonical id throws until this has run: the introspection\n * notifier, which names the APPLICATION collection room by it (#1767), and the engine's file, PDF\n * and feature-resolution scope derivations. Nothing in the companion called it, so those readers\n * worked only after some ASYNC reader happened to settle the identity — in practice the first model\n * call — and after every restart a board change reached nobody until then.\n *\n * Placed directly after the runtime dependencies (the repositories are up; the record exists from\n * the application's own initialisation), so it also precedes the startup reconciliations, the HTTP\n * server and the freshness plane: no reconciliation, request or publication runs ahead of it.\n *\n * BEST-EFFORT, unlike the engine's fatal step. There the id stamps rows, and a backend that cannot\n * name its application must not write; here the synchronous readers already refuse on their own,\n * and a companion that will not boot cannot be used to repair the cause (Rule 3 of\n * `continuity-drift-and-cas-basis.md`). The warning is what makes the degraded state visible.\n */\n private async primeApplicationIdentity(): Promise<void> {\n try {\n const identity = await this.applicationIdentity.prime();\n this.logDebug('Canonical application identity resolved', { applicationRecordId: identity._id });\n } catch (error) {\n this.logger.warn(\n 'The APPLICATION record identity could not be resolved at startup. Until it is, the workbench '\n + 'receives no pushed board changes and scope-derived file/PDF reads refuse. (non-fatal by design)',\n { error: describeCaughtError(error) },\n );\n }\n }\n\n /**\n * Report every stretch in which this process's event loop stopped keeping time, with what was running\n * (#2394). Started before anything that can block, beside the readiness heartbeat, so a stall during\n * boot is reported too.\n *\n * On app-creation-test-005 the companion stopped answering for minutes during build waves while its\n * `/health` handler awaited nothing, so the thread was held, and nothing in the log said so. These\n * lines are what tells the next measurement when to take a CPU profile and whether a fix removed the\n * stalls.\n */\n private startEventLoopStallMonitor(): void {\n // `initialize()` may run again after a failed boot; a second monitor would double every report.\n if (this.eventLoopStallMonitor) return;\n const readUtilization = createEventLoopUtilizationReader();\n this.eventLoopStallMonitor = new EventLoopStallMonitor(\n (report) => {\n this.logger.warn('Companion event loop stalled', { ...report, eventLoopUtilization: readUtilization() });\n },\n () => {\n const memory = process.memoryUsage();\n return {\n ...this.introspectionSourceWatcher.describeActivity(),\n heapUsedMb: Math.round(memory.heapUsed / 1_048_576),\n rssMb: Math.round(memory.rss / 1_048_576),\n };\n },\n );\n this.eventLoopStallMonitor.start();\n }\n\n /**\n * Restart this companion at a boundary before its heap reaches its limit (#3205), see\n * {@link HeapPressureMonitor}. Under the app-creator supervisor the restart is a graceful shutdown with the\n * exit code that supervisor named; under the framework's dev supervisor it is a signal-file request, which\n * that supervisor also holds while a run beats its heartbeat.\n */\n private startHeapPressureMonitor(): void {\n if (this.heapPressureMonitor) return;\n const saasRoot = this.companionContext.saasRoot;\n this.heapPressureMonitor = new HeapPressureMonitor({\n saasRoot,\n restart: (detail) => {\n const exitCode = readCompanionRestartExitCode(process.env);\n if (exitCode !== null) {\n void this.workerShutdownManager.initiateShutdown({ gracePeriodMs: 25_000, checkIntervalMs: 500, exitCode });\n return true;\n }\n return requestCompanionRestart(saasRoot, { reasonKey: 'heap-pressure', detail });\n },\n warn: (message, context) => this.logger.warn(message, context),\n });\n this.heapPressureMonitor.start();\n }\n\n /**\n * Start the plane that keeps introspection derivations current WITHOUT a reader asking.\n *\n * Ordered after the WebSocket server on purpose: the notifier's whole output is a socket emit, and\n * starting it before the server exists would give it a window in which a recompilation is computed\n * and then silently dropped.\n *\n * Failure here is NON-FATAL, and that is the important part. Everything this plane does is a\n * latency and freshness improvement over a path that still works without it: with no watcher the\n * derivation state stays in per-read observation, which is exactly the behaviour issue #159\n * shipped. A companion that refuses to boot because a directory could not be watched would trade a\n * slow workbench for no workbench — and the remedy for that would need the companion this failure\n * just prevented from starting (`continuity-drift-and-cas-basis.md` Rule 3).\n */\n private async startIntrospectionFreshnessPlane(): Promise<void> {\n try {\n this.introspectionResourceNotifier.start();\n // Before the watcher, not after it: with no watcher the sweep walks on every tick (no change feed vouches\n // for anything), so a watcher that fails to start must not also keep the sweep from starting.\n this.creationPlaneProjection.start();\n await this.introspectionSourceWatcher.start();\n this.logDebug('[StartCompanionApplication] Introspection freshness plane started');\n\n /*\n * Warming is started and NOT awaited. It spawns one subprocess per declared behavior, each\n * importing the whole target application, so awaiting it would add the very 8.8 s to boot that\n * it exists to remove from the first read. Boot completing while warming runs is the correct\n * shape: a read arriving mid-warm joins the in-flight compilation rather than starting a\n * second one.\n */\n void this.introspectionResourceSource.warmDeclaredDerivations()\n .then(({ attempted, failed }) => {\n if (attempted === 0) return;\n this.logger.info('Introspection derivations warmed', { attempted, failed });\n })\n .catch((error: unknown) => {\n this.logger.warn('Introspection derivation warming failed', {\n error: describeCaughtError(error),\n });\n });\n\n /*\n * The schema-plan sync state is warmed on the same terms, and for the same reason: it is the\n * other derivation a reader waits on. Resolving whether the migration step has landed spawns\n * `wildo db diff --check`, which boots the CLI and imports the application's compiled modules\n * registry — 8-14 s measured on `examples/wonder-todos`, of which ~5.5 s is the import. The\n * answer is cached against a signature of its inputs, so the cost falls entirely on the FIRST\n * read of each companion lifetime; warming moves that read off the board and onto boot, where\n * nobody is waiting. Under `wildo local dev` the companion respawns often, so that first read\n * is not a rare event.\n *\n * Called as a FUNCTION, not through the build-generation-step service, deliberately: reaching\n * it through the service would pull the labelling, email and brand service graph into the boot\n * graph to answer a question about two files.\n */\n void resolveSchemaPlanSyncState(this.companionContext.saasRoot)\n .then((state) => this.logDebug('[StartCompanionApplication] Schema-plan sync state warmed', { state }))\n .catch((error: unknown) => {\n this.logger.warn('Schema-plan sync state warming failed; the first build-plan read pays for it instead', {\n error: describeCaughtError(error),\n });\n });\n\n /*\n * Warming at boot fixes the first read of a companion lifetime. It does NOT fix the EDIT loop:\n * every `dist` rebuild moves the model's signature, so without this the next board read pays the\n * full 15s again. The loop re-derives in the background once the model has SETTLED, so the board\n * meets a fresh answer instead of waiting for one.\n */\n this.stopSchemaPlanFreshnessLoop = startSchemaPlanFreshnessLoop({\n saasRoot: this.companionContext.saasRoot,\n onRefreshFailed: (error: unknown) => {\n this.logger.warn('Background schema-plan refresh failed; the next build-plan read re-derives instead', {\n error: describeCaughtError(error),\n });\n },\n });\n } catch (error) {\n this.logger.warn(\n 'Introspection freshness plane failed to start; derivations fall back to per-read source observation',\n { error: describeCaughtError(error) },\n );\n }\n }\n\n /**\n * Generated CRUD routes for the WORKBENCH resources — and for nothing else.\n *\n * ## The whitelist is mandatory, not a tidy-up\n *\n * `ControllersRegistryHandlerBackendService.initialize()` creates an HTTP controller for EVERY\n * resource in the registry when no whitelist is passed. The companion's registry is the union of\n * the application's own vocabulary, platform-core's and the engine's — on wonder-crm that is ~80\n * resources — so an unwhitelisted call would expose generated CRUD over the observed\n * application's data on a dev daemon that, today, authenticates nothing. The parameter is opt-IN,\n * which makes omitting it fail OPEN.\n *\n * The whitelist is derived from `WorkbenchShared_ResourceType`, never hand-listed: a workbench\n * resource added tomorrow is exposed automatically, and — more importantly — a resource that is\n * NOT a workbench resource can never appear here by an editing slip.\n *\n * ## Why this is safe to call unconditionally\n *\n * Every workbench resource is INTROSPECTION-backed and declares only READ and LIST; the adapter\n * refuses all twelve write members. So the surface this opens is read-only by construction, not by\n * policy.\n */\n /**\n * Resource SERVICES the mounted frontend-support controllers need, beyond the workbench's own.\n *\n * `users` is what `AuthenticationController` resolves to identify and authenticate the operator —\n * the application's seeded administrator, in the database this companion and the application\n * backend share.\n *\n * Deliberately a short explicit list rather than \"everything\": a service the companion cannot\n * build aborts the whole registry initialization (`createService` THROWS), so widening blindly\n * turns one unbuildable resource into a failed boot. Each entry is here because a mounted\n * controller demonstrably asks for it.\n */\n private static readonly FRONTEND_SUPPORT_SERVICE_RESOURCE_TYPES: readonly string[] = [\n CoreResourceType.USERS,\n ...ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES,\n /*\n * The CONVERSATION plane (#1454, Step 4). `FlowsActorsController`'s history route lists the\n * caller's `userFlowActorExecutions`, and `ConversationalExecutionBackendService` persists every\n * thread through `SystemAccess` on the owner variant — user here, since the WebSocket surface is\n * user-scoped — and the other two variants exist for the A2A and machine surfaces the same\n * runtime serves. Measured 2026-09-22 with only the two entries above: `/flows-actors/history`\n * answered `service_not_found`, and a turn would have failed at its first write.\n */\n CoreResourceType.USER_FLOW_ACTOR_EXECUTIONS,\n CoreResourceType.ORGANIZATION_FLOW_ACTOR_EXECUTIONS,\n CoreResourceType.APPLICATION_FLOW_ACTOR_EXECUTIONS,\n ];\n\n /**\n * The engine manual controllers the companion mounts because it SERVES A FRONTEND.\n *\n * ## Why through the controllers registry rather than `registerCustomController`\n *\n * The registry's master router is mounted at `MAIN_API_BASE_PATH` (`/api/v1`) — the single source\n * of truth every Wildo frontend derives its URLs from. A controller registered as a CUSTOM\n * controller instead lands at `/api/custom/<controller-name>`, which is what an application's\n * OWN controllers want and is useless for an engine route a frontend already knows the path of.\n * Measured: the i18n controller registered that way answered correctly at\n * `/api/custom/i18n-controller/i18n/labels` while the workbench asked for `/api/v1/i18n/labels`\n * and got a 404, leaving every framework layout mounted and empty.\n *\n * This is exactly what `StartApplicationBackendService` does for an application — it merges\n * `getManualControllersBackend(...)` into the list it passes here — so the companion is using the\n * engine's own mounting path rather than a parallel one.\n *\n * ## Why a SUBSET, resolved by token\n *\n * `getManualControllersBackend()` returns the whole manual surface: authentication, OAuth, MCP,\n * A2A, files, features, charts, webhooks. Most of it has no business on a companion — an OAuth\n * provider, an MCP transport and a file surface answer to an application's clients, not to an\n * operator looking at one. Resolving the FOUR the workbench needs, by DI token, keeps the exposed\n * surface exactly what the frontend requires and nothing else, and needs no new engine export.\n *\n * Both are already bound in the engine container and injected above, so they receive the same\n * logger, error builder and services as everything else in this process.\n */\n private resolveFrontendSupportControllers(): AbstractControllerBackendService[] {\n return [\n // Labels for every framework component the workbench renders.\n this.i18nController,\n // The frontend bootstrap `ApplicationMainProvider` fetches before it mounts any provider.\n this.applicationConfigController,\n /*\n * Authentication, because the workbench renders the engine's own application shell and that\n * shell routes an unauthenticated visitor to `/login`.\n *\n * The operator signs in with `ADMIN_EMAIL` / `ADMIN_PASSWORD` (`PlatformAdminEnvKey`), which\n * apps-manager provisions in INIT mode, so this mounts an authentication surface over an\n * EXISTING user store rather than inventing a second identity for the workbench.\n *\n * That store is the PLATFORM's, NOT the application's. The two are different databases and\n * both hold a row for that email with different roles, so the operator authenticated here is\n * the platform identity, never the application administrator. `buildWorkbenchFrontendServiceEntry`\n * in `companion-platform-config.companion.ts` records the consequence in detail: `usersManagement`\n * is authored EMPTY because the platform identity carries no `userTypes`, and declaring the\n * application's type fails every workbench login with `authentication_user_type_mismatch`.\n *\n * The surface this opens is real and deliberately bounded: the companion asserts a loopback\n * bind at startup and fails closed otherwise, so these routes are reachable only from the\n * developer's own machine. If the companion is ever exposed beyond loopback that is a genuine\n * authentication problem for the whole daemon, not a property of this line.\n */\n this.authenticationController,\n /*\n * Feature resolution, which the application shell performs immediately AFTER a successful\n * login. Unmounted it answers 404 and the shell LOGS THE OPERATOR STRAIGHT BACK OUT —\n * measured as `200 /auth/authenticate` followed by `404 /features/resolved` and\n * `204 /auth/logout`, which presents as \"the password did not work\" and is nothing of the\n * kind.\n */\n this.featuresController,\n /*\n * The conversational plane's HTTP half (#1454, Step 4): `/flows-actors/frontend-info`, which is\n * how the workbench learns the creation assistant exists, and `/flows-actors/history`, which\n * is how it lists a creator's threads. The WebSocket half (`setupFlowsActorsHandlers`) was\n * already attached to every signed-in socket by the engine's own server; only the discovery\n * and history routes were missing, so the browser saw `systems = []` and rendered nothing.\n */\n this.flowsActorsController,\n ];\n }\n\n /**\n * The creation-plane CONTROL resources the workbench consumes AS resources.\n *\n * These are the platform's own control-plane rows — the actor tasks and executions the companion\n * itself writes (repository-direct) during playbook runs and coding dispatches. Their configs are\n * shared platform vocabulary (`wildo-application-tasks` / `wildo-application-executions` in\n * `@wildo-ai/platform-core-shared`), whose READ/LIST became ORG_MEMBER-gated API variants on\n * 2026-09-01 precisely for this consumption (the decision is recorded on\n * `createOrgMemberReadApiVariant` in those files). Every type in this list is mounted READ-ONLY\n * (`ResourceControllerMountMode.READ_ONLY`, #3357): only read-shaped operations get a route, and no upload or\n * field-validation route. The companion owns none of these writes over HTTP (its own writes are repository-direct),\n * and it runs none of the engine's custom implementations, so a write served here would skip what the application\n * backend adds to it. `organizations` needed this most: an engine resource whose write variants the application\n * backend must keep, so the configuration could not drop them as #3319 did for `wildoApplication`. The mode is a\n * property of the mount, so a write variant any of these configurations gains later is not mounted here either.\n *\n * A hand list rather than a derivation, deliberately: consuming a control-plane type is a\n * per-type DECISION (each one widens an HTTP surface), not a population to sweep.\n */\n private static readonly CREATION_CONTROL_PLANE_RESOURCE_TYPES: readonly string[] = [\n /*\n * The parent anchor first: every control-plane URL nests under\n * `…/wildo-application/{wildoApplicationId}/…`, and the workbench bootstraps that id by LISTing\n * this resource (one row per companion). Its config already carried API read variants; mounting is\n * all it needed.\n */\n CustomShared_ResourceType.WILDO_APPLICATION,\n /*\n * ORGANIZATIONS rides with the plane: it is the PRIMARY SCOPE of all three control-plane types,\n * so the workbench frontend registers it — and a registered organizations resource makes the\n * engine shell READ the org rows it scopes by. Unmounted, those reads 404 on every session\n * (measured); the rows exist in this application's own database, and the engine's standard\n * controller serves them behind ordinary auth.\n */\n CoreResourceType.ORGANIZATIONS,\n CustomShared_ResourceType.WILDO_APPLICATION_ACTOR_TASKS,\n CustomShared_ResourceType.WILDO_APPLICATION_ACTOR_SYSTEM_EXECUTIONS,\n CustomShared_ResourceType.WILDO_APPLICATION_FLOW_SYSTEM_EXECUTIONS,\n ];\n\n private async initializeWorkbenchResourceControllers(): Promise<void> {\n const workbenchResourceTypes = [\n ...(Object.values(WorkbenchShared_ResourceType) as string[]),\n ...StartCompanionApplicationService.CREATION_CONTROL_PLANE_RESOURCE_TYPES,\n ];\n\n /*\n * SERVICES before CONTROLLERS, and both whitelisted to the same set.\n *\n * A controller resolves its service by resource type at request time; without the service the\n * route mounts and answers `service_not_found`, which reads like a routing bug rather than a\n * missing registration. The whitelist matters more here than on the controllers side:\n * `createService` THROWS on failure and aborts the whole initialization, so building services\n * for all ~99 registry entries would let one resource the companion cannot service fail its\n * boot outright.\n */\n /*\n * SERVICES and CONTROLLERS get DIFFERENT whitelists, and the asymmetry is the point.\n *\n * A service is reachable only from code inside this process; a controller is an HTTP surface.\n * So the services list may widen to whatever the mounted controllers need, while the controllers\n * list stays exactly the workbench's own resources — no generated CRUD over the observed\n * application's data appears because authentication happens to need a user service.\n *\n * `AuthenticationController` resolves the `users` service to identify and authenticate an\n * operator. Without it every auth route mounts and answers `service_not_found`, which reads like\n * a routing bug and is really a missing registration.\n */\n /*\n * Labels BEFORE the controllers that serve them.\n *\n * `I18nBackendService` answers `{}` until it is initialized, and the companion never initialized\n * it — so `/i18n/labels` returned a correctly shaped empty map and every framework layout in the\n * workbench rendered its label KEYS. Initializing here, in the same step that mounts the route,\n * keeps the two facts adjacent: the surface and the content it serves.\n */\n await this.i18nService.initialize(companionCustomLabels);\n\n await this.servicesRegistryService.initializeServices([\n ...workbenchResourceTypes,\n ...StartCompanionApplicationService.FRONTEND_SUPPORT_SERVICE_RESOURCE_TYPES,\n ]);\n /*\n * The creation board's DISPATCH operations:\n * OVERRIDE_ALL custom implementations delegating to the companion's own services. Initialized\n * AFTER the services registry, because registrations validate against the CONFIGURED operation\n * paths at init — a drifting identifier fails the boot here instead of becoming unreachable\n * code (the exact silence the registry's own doc records). This list is the companion's WHOLE\n * custom-impl registry, deliberately: the engine's `CoreBackend_ServiceImplementationsFactories`\n * have never run in this process, and activating them here would change the behavior of every\n * engine resource the companion mounts as a side effect of a board feature.\n */\n this.customImplRegistry.initialize(createCreationPlaneDispatchFactories());\n /*\n * The engine's OWN runtime floor is mounted beside the workbench's resources, and it is the one\n * exception to \"controllers stay exactly the workbench's own resources\".\n *\n * It is not a widening of the observed application's surface. `ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES`\n * is the set the engine reads to restore an authenticated session, and it is CONTEXT-ADDRESSED:\n * `user_self` resolves to the CALLER's own record, so mounting it exposes an authenticated\n * operator to themselves and to nobody else.\n *\n * Mounting it is not optional. The frontend registry keeps these registered no matter what an\n * application excludes (the same constant enforces it there), so the browser WILL call\n * `/api/v1/user-self/:id/context` after every login. Serving a 404 makes session restoration\n * return false, and the shell logs out \"to avoid a half-restored state\" — login succeeds, the\n * token is valid, and the user lands back on the login form. Measured on the workbench: fixing\n * the registry alone moved the failure from a missing registry entry to this 404, one layer down.\n */\n const mountedResourceTypes = [...workbenchResourceTypes, ...ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES];\n /*\n * The collection-export PDF templates, BEFORE the controllers that serve their exports (#1645). The\n * companion never runs `StartApplicationBackendService.initialize()`, where an application binds its\n * templates, so the workbench binds its one here — with completeness asserted, so a workbench export\n * naming a template nobody provides fails this boot rather than its first download.\n *\n * Checked against the MOUNTED types only. The registry also holds the observed application's\n * resources, and an application declaring its own PDF export must not stop the companion booting\n * over a template only the application's backend renders.\n */\n this.pdfCollectionExportTemplates.initialize([\n createWorkbenchGovernedDocumentsPdfTemplate({\n dossier: this.dossierService,\n labelsFor: (locale) => this.i18nService.getLabels(locale as AvailableLanguage),\n }),\n ], { assertCompleteness: true, servedResourceTypes: mountedResourceTypes });\n await this.controllersRegistryService.initialize(\n this.resolveFrontendSupportControllers(),\n mountedResourceTypes,\n StartCompanionApplicationService.CREATION_CONTROL_PLANE_RESOURCE_TYPES,\n );\n this.logDebug('Workbench resource controllers initialized', { resourceTypes: mountedResourceTypes });\n }\n\n private async registerCustomControllers(customControllers: AbstractControllerBackendService[]): Promise<void> {\n for (const controller of customControllers) {\n this.httpServerService.registerCustomController(controller);\n }\n }\n\n /** Transport liveness only; semantic readiness is exposed separately below. */\n public isHttpServerRunning(): boolean {\n return this.httpServerService.isRunning();\n }\n\n /**\n * The continuity-readiness apparatus is gone (git is the accepted state; there is nothing to recover at\n * startup), so a companion whose HTTP server is up IS semantically ready. The literal keeps the\n * `companion-readiness.json` wire protocol the local-dev diagnostics collector already reads.\n */\n public getContinuityReadinessStatus(): 'READY' {\n return 'READY';\n }\n\n public getServerInfo(): string | null {\n return this.httpServerService.getServerInfo();\n }\n\n /**\n * Publish a sanitized process-local posture for the bootstrap-safe developer\n * diagnostic collector. This is not continuity authority and contains no\n * failure object, stack, environment value, token, or mutable semantic state.\n * Publication is best-effort so observability can never change startup.\n *\n * The discriminator mirrors the dependency-free root protocol as a thin\n * native gateway because the distributed companion cannot depend on files\n * from the framework checkout that is diagnosing it.\n */\n private publishLocalReadinessObservation(): void {\n const observationPath = join(\n this.companionContext.saasRoot,\n '.wildo-saas',\n 'runtime-signals',\n 'diagnostics',\n 'companion-readiness.json',\n );\n const directory = dirname(observationPath);\n const temporaryPath = `${observationPath}.tmp-${process.pid}-${Date.now()}`;\n try {\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n chmodSync(directory, 0o700);\n writeFileSync(temporaryPath, `${JSON.stringify({\n kind: 'wildo.local-dev.companion-readiness-observation',\n schemaVersion: 1,\n producerKind: 'dev-companion',\n producerInstanceId: this.readinessObservationProducerInstanceId,\n producerPid: process.pid,\n appRoot: this.companionContext.saasRoot,\n status: 'READY',\n /*\n * A READY companion that never drained its terminalization outbox. Non-fatal by design, and\n * therefore invisible until it is published here — the drain's only previous surface was a\n * `console.warn` on a boot that then succeeded.\n */\n /*\n * What the ordered startup actually COST, and which stages missed their soft budget.\n *\n * A stage deadline used to report the stage and the budget it missed and nothing else, which made a stuck\n * companion undiagnosable: nobody could see whether one stage was pathological or every stage was near\n * its limit. `stagesOverSoftBudgetMs` is normally empty, so its presence alone is the warning.\n */\n httpRunning: this.httpServerService.isRunning(),\n updatedAt: new Date().toISOString(),\n }, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n renameSync(temporaryPath, observationPath);\n chmodSync(observationPath, 0o600);\n } catch (error) {\n try {\n unlinkSync(temporaryPath);\n } catch {\n // The temporary file may not exist or may already have been renamed.\n }\n this.logger.warn('Could not publish the local companion readiness observation', {\n error: describeCaughtError(error),\n });\n }\n }\n\n private startLocalReadinessObservation(): void {\n this.publishLocalReadinessObservation();\n if (this.readinessObservationHeartbeat) {\n return;\n }\n this.readinessObservationHeartbeat = setInterval(() => {\n this.publishLocalReadinessObservation();\n }, 5_000);\n this.readinessObservationHeartbeat.unref();\n }\n\n /**\n * Bind every companion-owned long-lived resource to the engine's canonical\n * shutdown coordinator. HTTP closes in the stop phase so no new work enters;\n * Redis, Mongo, and observability then drain through the coordinator's LIFO\n * cleanup phase. Registration is idempotent because initialize can be called\n * more than once by defensive bootstraps.\n */\n private registerCompanionShutdownLifecycle(): void {\n if (this.shutdownLifecycleRegistered) {\n return;\n }\n this.shutdownLifecycleRegistered = true;\n\n this.workerShutdownManager.registerStopHandler(async () => {\n try {\n await this.runBoundedShutdownStep('http-server', () => this.httpServerService.shutdown());\n } finally {\n // Hygiene rather than a latch: the loop's timer is unref'd, so it can never be the reason the\n // process stays alive. Stopping it keeps a shutting-down companion from spawning a `db diff`.\n this.stopSchemaPlanFreshnessLoop?.();\n this.stopSchemaPlanFreshnessLoop = null;\n this.stopOwedActorReviewRecordRepairTick?.();\n this.stopOwedActorReviewRecordRepairTick = null;\n this.stopActorQuestionDeadlineSweep?.();\n this.stopActorQuestionDeadlineSweep = null;\n this.eventLoopStallMonitor?.stop();\n this.eventLoopStallMonitor = null;\n this.heapPressureMonitor?.stop();\n this.heapPressureMonitor = null;\n // The coding agent's background connectivity probe (#3236): unref'd too, and a stopping companion starts none.\n this.codingAgentDispatchService.stopBackgroundConnectivityProbe();\n this.publishLocalReadinessObservation();\n if (this.readinessObservationHeartbeat) {\n clearInterval(this.readinessObservationHeartbeat);\n this.readinessObservationHeartbeat = null;\n }\n }\n });\n this.workerShutdownManager.onShutdown(async () => this.runBoundedShutdownStep('mongodb', () => this.mongoDBService.disconnect()));\n this.workerShutdownManager.onShutdown(async () => this.runBoundedShutdownStep('redis', () => this.redisService.disconnect()));\n this.workerShutdownManager.registerSignalHandlers();\n }\n\n /** Keep one stuck dependency from consuming the supervisor's whole SIGTERM grace period. */\n private async runBoundedShutdownStep(component: string, operation: () => Promise<void>): Promise<void> {\n let timeout: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () => reject(new Error(`Companion ${component} shutdown exceeded ${COMPANION_SHUTDOWN_STEP_TIMEOUT_MS}ms.`)),\n COMPANION_SHUTDOWN_STEP_TIMEOUT_MS,\n );\n timeout.unref();\n });\n try {\n await Promise.race([Promise.resolve().then(operation), timeoutPromise]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"start-companion-application.service.js","sourceRoot":"","sources":["../../../../../src/core/runtime/services/start-companion-application.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,wCAAwC,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,uCAAuC,EAAE,kCAAkC,EAAE,MAAM,mCAAmC,CAAC;AAEhI,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,EACL,kBAAkB,EAGlB,kBAAkB,EAClB,wBAAwB,EACxB,cAAc,EACd,gCAAgC,EAChC,YAAY,EACZ,+BAA+B,EAC/B,uCAAuC,EACvC,2BAA2B,EAC3B,mCAAmC,EACnC,0BAA0B,EAC1B,wCAAwC,EACxC,+BAA+B,EAC/B,qCAAqC,EACrC,yCAAyC,EACzC,2DAA2D,EAC3D,yBAAyB,EACzB,2BAA2B,EAC3B,mCAAmC,EACnC,8BAA8B,EAQ9B,mBAAmB,GACpB,MAAM,4BAA4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B,CAAC,CAAA;IAGrD,YAAA,MAAM,CAAC,kBAAkB,CAAC,4BAA4B,CAAC,CAAA;IAEvD,YAAA,MAAM,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAA;IAG9C,YAAA,MAAM,CAAC,kBAAkB,CAAC,0BAA0B,CAAC,CAAA;IAGrD,YAAA,MAAM,CAAC,uBAAuB,CAAC,mBAAmB,CAAC,CAAA;IAGnD,YAAA,MAAM,CAAC,uBAAuB,CAAC,+BAA+B,CAAC,CAAA;IAE/D,YAAA,MAAM,CAAC,kBAAkB,CAAC,oBAAoB,CAAC,CAAA;IAG/C,YAAA,MAAM,CAAC,uBAAuB,CAAC,iCAAiC,CAAC,CAAA;IAAE,YAAA,QAAQ,EAAE,CAAA;+CArFI,wBAAwB;QAC9B,cAAc;QACQ,gCAAgC;QAC1D,YAAY;QACF,+BAA+B,UAM9D,uCAAuC;QAE5C,2BAA2B;QAEjC,mCAAmC;QAE9B,0BAA0B;QAE5B,+BAA+B;QAE7B,wCAAwC,8DAmBvD,kBAAkB;QAEN,qCAAqC;QAE1C,2DAA2D;QAElD,yCAAyC,oBAMpD,kCAAkC;QAExB,mCAAmC;QAE3C,0CAA0C;QAElC,0CAA0C;QAEvC,6CAA6C;QAE/C,2CAA2C;QAG/C,uCAAuC;GAlFxE,gCAAgC,CAg6C5C","sourcesContent":["import { chmodSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { COMPANION_MODEL_APPLICABILITY_PREFERENCE } from '../companion-model-preference';\nimport { createLanguageModelRunHeartbeatReporter, resolveCompanionLanguageModelRoute } from '../companion-language-model-route';\n\nimport { injectable, inject, optional } from 'inversify';\nimport type { AvailableLanguage } from '@wildo-ai/presets-components-models';\nimport {\n I18nBackendService,\n type AgentsBackendService,\n type ConversationalExecutionBackendService,\n SAAS_SERVICE_TYPES,\n HttpServerBackendService,\n MongoDBService,\n PostgreSQLDatabaseBackendService,\n RedisService,\n FileStorageRouterBackendService,\n ExternalProvidersRegistryBackendService,\n ObservabilityBackendService,\n WorkerShutdownManagerBackendService,\n FlowsActorsRegistryService,\n ControllersRegistryHandlerBackendService,\n ResourcesRegistryBackendService,\n ServicesRegistryHandlerBackendService,\n RepositoriesRegistryHandlerBackendService,\n ResourceOperationCustomImplementationRegistryBackendService,\n mergeBackendDomainModules,\n projectCaughtErrorLogFields,\n projectRetriedAttemptErrorLogFields,\n resolveBackendProviderRegistry,\n type AbstractControllerBackendService,\n type ActorsSystemBackendService,\n type ApplicationInitializationConfig,\n type AppConfiguration_BackendAuthored,\n type ApplicationIdentityBackendService,\n type LoggerService,\n type PdfCollectionExportTemplateBackendService,\n describeCaughtError,\n} from '@wildo-ai/saas-backend-lib';\nimport {\n CoreResourceType, buildSharedSaaSModulesRegistry,\n ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES,\n MODEL_SPEND_GATE_RESOURCE_TYPES,\n} from '@wildo-ai/saas-models';\nimport type {\n ResourceConfiguration,\n ResourceConfiguration_InitializationFactoryMap,\n ResourceConfiguration_InitializationFactory,\n ResourceRelationship,\n ResourceType,\n} from '@wildo-ai/saas-models';\nimport {\n registerFeatureSpecifications,\n registerRoleSpecifications,\n type FeatureSpecification,\n type RoleSpecification,\n} from '@wildo-ai/saas-specifications';\nimport {\n PLATFORM_SHARED_SERVICE_TYPES,\n type PlatformAppConfigInitializerService,\n} from '@wildo-ai/platform-shared-lib';\nimport type { SaasRuntimeProvidersArtifact } from '@wildo-ai/platform-config-lib';\nimport { WILDO_PLATFORM_ORGANIZATION_TYPES } from '@wildo-ai/platform-config-lib';\n\nimport { COMPANION_SERVICE_TYPES } from '../../../core/inject/models/service-types';\nimport type { CompanionTraceabilityService } from '../../traceability/companion-traceability.service';\nimport { resolveSchemaPlanSyncState } from '../../../meta-workflows/services/application-build-generation-step.companion.service';\nimport { startSchemaPlanFreshnessLoop } from '../../../meta-workflows/services/schema-plan-freshness-loop.companion';\nimport type { DossierCompanionService } from '../../../meta-workflows/services/dossier.companion.service';\nimport { createWorkbenchGovernedDocumentsPdfTemplate } from '../../../meta-workflows/services/governed-documents-pdf.companion';\nimport { IntrospectionSourceWatcherCompanionService } from '../../introspection/services/introspection-source-watcher.companion.service';\nimport { EventLoopStallMonitor, createEventLoopUtilizationReader } from '../event-loop-stall-monitor.companion';\nimport { HeapPressureMonitor, readCompanionRestartExitCode } from '../heap-pressure-restart.companion';\nimport { startOwedActorReviewRecordRepairTick } from '../owed-actor-review-record-repair-tick.companion';\nimport type { CompanionActorQuestionDeadlineSweepService } from '../../../meta-workflows/services/companion-actor-question-deadline-sweep.companion.service';\nimport { requestCompanionRestart } from '../companion-self-restart.companion';\nimport { IntrospectionResourceNotifierCompanionService } from '../../introspection/resources/introspection-resource-notifier.companion.service';\nimport { IntrospectionResourceSourceCompanionService } from '../../introspection/resources/introspection-resource-source.companion.service';\nimport { CreationPlaneProjectionCompanionService } from '../../introspection/resources/creation-plane-projection.companion.service';\nimport type { ApplicationBuildDispatchCompanionService } from '../../../meta-workflows/services/application-build-dispatch.companion.service';\nimport { createCreationPlaneDispatchFactories } from '../../introspection/resources/creation-plane-dispatch.custom-impl.companion.service';\nimport { CompanionAuthFloorCompanionService } from '../../auth/companion-auth-floor.companion.service';\nimport type { CompanionContext } from '../../context/companion-context';\nimport { META_WORKFLOWS_SYSTEM_REF } from '../../../meta-workflows/models/meta-workflows-lane.models';\nimport { APPLICATION_BUILD_SYSTEM_REF } from '../../../meta-workflows/models/application-build.actors-system.definitions';\nimport {\n buildCompanionResolvedAppConfig,\n parseCompanionPlatformEnv,\n planCompanionPlatformStoreConnections,\n} from '../utils/companion-platform-config.companion';\nimport { CustomShared_ResourceType, WORKBENCH_CREATION_CONVERSATION_SYSTEM_REF, WorkbenchShared_ResourceType } from '@wildo-ai/platform-core-shared';\nimport {\n companionPlatformCoreBackendModule,\n companionPlatformCoreSharedModule,\n companionWorkbenchSharedModule,\n} from '../utils/platform-core-domain-modules.companion';\nimport {\n loadBackendCompanionExports,\n loadSharedLibraryCompanionExports,\n loadSpecificationsCompanionData,\n} from '../../context/companion-package-loaders.companion';\n\n/**\n * Where the companion's resource-registry vocabulary came from at startup.\n * Logged as `registrySource` — the load-bearing diagnostic for the recurring\n * \"companion didn't see the app's resources\" bug class.\n */\nenum ResourceRegistryInitSource {\n /**\n * The application's companion-export surface loaded successfully; the\n * registry mirrors the backend API's vocabulary, unioned with the\n * platform-core persistence vocabulary.\n */\n APP_COMPANION_EXPORTS = 'app-companion-exports',\n /**\n * The app companion-exports could not be loaded (e.g. a not-yet-built\n * `dist`); only the statically-imported platform-core engine vocabulary is\n * registered. App-resource labelling is degraded but startup is never\n * blocked.\n */\n PLATFORM_CORE_FALLBACK = 'platform-core-fallback',\n}\nimport { CodingAgentDispatchCompanionService, type InterruptedRun } from '../../../claude-cli/services/coding-agent-dispatch.companion.service';\nimport { CreationInterventionLedgerCompanionService } from '../../../meta-workflows/services/creation-intervention-ledger.companion.service';\nimport { companionCustomLabels } from '../../../i18n';\nimport { initializeFileStorageWithRetry } from './file-storage-initialization.companion';\n\nexport interface CompanionStartupConfig {\n customControllers: AbstractControllerBackendService[];\n backendConfig?: AppConfiguration_BackendAuthored;\n backendProviderRegistry?: unknown;\n providerRuntime?: SaasRuntimeProvidersArtifact;\n flowsActorsRegistry?: ApplicationInitializationConfig['flowsActorsRegistry'];\n}\n\nconst COMPANION_SHUTDOWN_STEP_TIMEOUT_MS = 5_000;\n\n/**\n * Start Companion Application Service\n *\n * Minimal startup orchestrator for the Dev Companion.\n * The companion API lane now consumes a platform-style env contract, but it\n * still needs local app semantics for label/email/tooling services. The startup\n * path therefore hydrates `AppConfigurationService` itself before handing off to\n * the standard backend runtime bootstrap.\n */\n/**\n * `CompanionStartupConfig.backendProviderRegistry` is typed `unknown` — deliberately, so the companion\n * does not take a type dependency on the private connectors package — so it is CHECKED here rather\n * than cast. A value that is not a fragment is dropped, and the companion then runs on exactly what\n * its own artifact declares, which is the honest outcome: a malformed hand-off should not silently\n * become an unfiltered catalogue.\n */\nfunction asBackendProviderFragment(\n candidate: unknown,\n): Parameters<typeof resolveBackendProviderRegistry>[0]['applicationFragment'] {\n if (typeof candidate !== 'object' || candidate === null) {\n return undefined;\n }\n const modules = (candidate as { modules?: unknown }).modules;\n return modules instanceof Map\n ? (candidate as Parameters<typeof resolveBackendProviderRegistry>[0]['applicationFragment'])\n : undefined;\n}\n\n@injectable()\nexport class StartCompanionApplicationService {\n private readonly logDebug: (message: string, context?: Record<string, unknown>) => void;\n private readonly readinessObservationProducerInstanceId = `${process.pid}-${Date.now()}`;\n private readinessObservationHeartbeat: NodeJS.Timeout | null = null;\n private initialized = false;\n private shutdownLifecycleRegistered = false;\n /** See {@link startEventLoopStallMonitor}. */\n private eventLoopStallMonitor: EventLoopStallMonitor | null = null;\n private heapPressureMonitor: HeapPressureMonitor | null = null;\n /** Stops the background schema-plan refresher; the timer is unref'd, so this is hygiene rather than a latch. */\n private stopSchemaPlanFreshnessLoop: (() => void) | null = null;\n /** Stops the periodic owed-actor-review-record repair (#2189); the timer is unref'd, so this is hygiene. */\n private stopOwedActorReviewRecordRepairTick: (() => void) | null = null;\n /** Stops the periodic actor question deadline sweep (#2807); the timer is unref'd, so this is hygiene. */\n private stopActorQuestionDeadlineSweep: (() => void) | null = null;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.HttpServerService) private readonly httpServerService: HttpServerBackendService,\n @inject(SAAS_SERVICE_TYPES.MongoDBService) private readonly mongoDBService: MongoDBService,\n @inject(SAAS_SERVICE_TYPES.PostgreSQLDatabaseService) private readonly postgresqlDatabaseService: PostgreSQLDatabaseBackendService,\n @inject(SAAS_SERVICE_TYPES.RedisService) private readonly redisService: RedisService,\n @inject(SAAS_SERVICE_TYPES.FileStorageRouter) private readonly fileStorageRouter: FileStorageRouterBackendService,\n @inject(SAAS_SERVICE_TYPES.BackendProviderRegistryService)\n private readonly backendProviderRegistryService: {\n initialize(registry: unknown, providerRuntime?: unknown, unresolvedReasons?: ReadonlyMap<string, string>): void;\n },\n @inject(SAAS_SERVICE_TYPES.ExternalProvidersRegistryService)\n private readonly externalProvidersRegistryService: ExternalProvidersRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ObservabilityBackendService)\n private readonly observabilityBackendService: ObservabilityBackendService,\n @inject(SAAS_SERVICE_TYPES.WorkerShutdownManagerService)\n private readonly workerShutdownManager: WorkerShutdownManagerBackendService,\n @inject(SAAS_SERVICE_TYPES.FlowsActorsRegistryService)\n private readonly flowsActorsRegistryService: FlowsActorsRegistryService,\n @inject(SAAS_SERVICE_TYPES.ResourceRegistryService)\n private readonly resourcesRegistryService: ResourcesRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ControllersRegistryHandlerService)\n private readonly controllersRegistryService: ControllersRegistryHandlerBackendService,\n /*\n * The two engine manual controllers the companion mounts for its FRONTEND — injected by token\n * rather than resolved from a container reference, so the dependency is declared where every\n * other one is and a missing binding fails at construction instead of mid-startup.\n */\n @inject(SAAS_SERVICE_TYPES.I18nController)\n private readonly i18nController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.ApplicationConfigController)\n private readonly applicationConfigController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.AuthenticationController)\n private readonly authenticationController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.FeaturesController)\n private readonly featuresController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.FlowsActorsController)\n private readonly flowsActorsController: AbstractControllerBackendService,\n @inject(SAAS_SERVICE_TYPES.ConversationalExecutionBackendService)\n private readonly conversationalExecution: ConversationalExecutionBackendService,\n @inject(SAAS_SERVICE_TYPES.I18nService)\n private readonly i18nService: I18nBackendService,\n @inject(SAAS_SERVICE_TYPES.ServicesRegistryHandlerService)\n private readonly servicesRegistryService: ServicesRegistryHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceOperationCustomImplementationRegistryService)\n private readonly customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService)\n private readonly repositoriesRegistryService: RepositoriesRegistryHandlerBackendService,\n @inject(PLATFORM_SHARED_SERVICE_TYPES.PlatformAppConfigInitializerService)\n private readonly appConfigInitializer: PlatformAppConfigInitializerService,\n @inject(COMPANION_SERVICE_TYPES.CompanionContext)\n private readonly companionContext: CompanionContext,\n @inject(COMPANION_SERVICE_TYPES.AuthFloorService)\n private readonly authFloorService: CompanionAuthFloorCompanionService,\n @inject(COMPANION_SERVICE_TYPES.CodingAgentDispatchService)\n private readonly codingAgentDispatchService: CodingAgentDispatchCompanionService,\n @inject(COMPANION_SERVICE_TYPES.CreationInterventionLedgerService)\n private readonly interventionLedger: CreationInterventionLedgerCompanionService,\n @inject(COMPANION_SERVICE_TYPES.IntrospectionSourceWatcherService)\n private readonly introspectionSourceWatcher: IntrospectionSourceWatcherCompanionService,\n @inject(COMPANION_SERVICE_TYPES.IntrospectionResourceNotifierService)\n private readonly introspectionResourceNotifier: IntrospectionResourceNotifierCompanionService,\n @inject(SAAS_SERVICE_TYPES.IntrospectionResourceSource)\n private readonly introspectionResourceSource: IntrospectionResourceSourceCompanionService,\n /* The creation-plane boards' input signature (#1310): started beside the watcher it listens to. */\n @inject(COMPANION_SERVICE_TYPES.CreationPlaneProjectionService)\n private readonly creationPlaneProjection: CreationPlaneProjectionCompanionService,\n /** The engine's execution driver — settles the playbook runs a previous process left PROCESSING (#1360). */\n @inject(SAAS_SERVICE_TYPES.ActorsSystemBackendService)\n private readonly actorsSystemService: ActorsSystemBackendService,\n /* The collection-export PDF templates (#1645) and the dossier the governed-documents one reads its texts from. */\n @inject(SAAS_SERVICE_TYPES.PdfCollectionExportTemplates)\n private readonly pdfCollectionExportTemplates: PdfCollectionExportTemplateBackendService,\n @inject(COMPANION_SERVICE_TYPES.DossierService)\n private readonly dossierService: DossierCompanionService,\n /* The APPLICATION record's identity, primed at startup because this class replaces the engine's startup (#1767). */\n @inject(SAAS_SERVICE_TYPES.ApplicationIdentityService)\n private readonly applicationIdentity: ApplicationIdentityBackendService,\n /* Trace-session retention, started at boot so a companion that serves few requests still sheds its expired sessions. */\n @inject(COMPANION_SERVICE_TYPES.TraceabilityService)\n private readonly traceabilityService: CompanionTraceabilityService,\n /* The website-copy review sweep (#2593), started once the companion serves: a review a restart lost is redone here. */\n @inject(COMPANION_SERVICE_TYPES.ApplicationBuildDispatchService)\n private readonly buildDispatchService: ApplicationBuildDispatchCompanionService,\n @inject(SAAS_SERVICE_TYPES.AgentsBackendService)\n private readonly agentsService: AgentsBackendService,\n /** #2807: lapses and reminds the companion's own actor questions. Optional and last, so a harness may omit it. */\n @inject(COMPANION_SERVICE_TYPES.ActorQuestionDeadlineSweepService) @optional()\n private readonly actorQuestionDeadlineSweep?: CompanionActorQuestionDeadlineSweepService,\n ) {\n this.logDebug = this.logger.debugByType('StartCompanionApplication');\n this.logger.setDebugTypeLogging('StartCompanionApplication', true);\n }\n\n /**\n * Initialize the companion application using the typed config object.\n */\n public async initialize(config: CompanionStartupConfig): Promise<void> {\n if (this.initialized) {\n this.logDebug('Companion runtime already initialized, skipping');\n return;\n }\n\n this.registerCompanionShutdownLifecycle();\n\n // Start the best-effort heartbeat before the first external dependency can\n // block. A hung Mongo/config/bootstrap phase is then distinguishable from\n // an old companion that never implemented the observation protocol.\n this.startLocalReadinessObservation();\n this.startEventLoopStallMonitor();\n this.startHeapPressureMonitor();\n\n const runtimeEnv = parseCompanionPlatformEnv();\n\n /*\n * Connect whichever platform store this environment actually declares.\n *\n * Unconditional MongoDB until 2026-08-28 (issue #94). On a PostgreSQL-engined platform\n * that made the companion read platform rows — `wildoapplication`, actor tasks, execution\n * rows — from a database the platform had stopped using. Nothing failed: it connected\n * successfully to an EMPTY store, so `resolveOwnership` reported the application as\n * unregistered and every companion execution refused, while the row sat in PostgreSQL.\n * A wrong connection presenting as missing data is why it was misdiagnosed as an\n * uninitialized platform.\n *\n * The env schema has already refused an environment declaring neither store, and refused a\n * selected store without its URL (`DATABASE_DEFAULT_ADAPTER=postgresql` without PG_CONNECT_URL, and\n * since #1117 a MongoDB selection without MONGO_CONNECT_URL), so both branches here are\n * genuinely optional rather than silently permissive.\n */\n const storeConnections = planCompanionPlatformStoreConnections(runtimeEnv);\n if (storeConnections.mongoConnectUrl) {\n this.logDebug('Connecting companion platform MongoDB from env');\n await this.mongoDBService.connectWithUri(storeConnections.mongoConnectUrl);\n }\n if (storeConnections.postgresConnectUrl) {\n // Lazy pool — zero I/O here. The connection must exist before any repository is\n // constructed, because the repositories bind to it at construction time.\n this.logDebug('Connecting companion platform PostgreSQL from env');\n this.postgresqlDatabaseService.connectWithUrl(storeConnections.postgresConnectUrl);\n }\n\n const resolvedAppConfig = await buildCompanionResolvedAppConfig({\n companionContext: this.companionContext,\n env: runtimeEnv,\n backendConfig: config.backendConfig,\n providerRuntime: config.providerRuntime,\n });\n\n this.appConfigInitializer.initializeWithFullConfig({\n serviceName: runtimeEnv.SERVICE_NAME,\n applicationId: runtimeEnv.APPLICATION_ID,\n appSlug: this.companionContext.saasConfig.slug,\n appName: this.companionContext.saasConfig.displayName,\n port: runtimeEnv.PORT,\n fullAppConfig: resolvedAppConfig,\n // The companion hydrates the application's configuration but serves none of its end-user logins.\n servesAuthentication: false,\n });\n\n await this.initializePlatformExecutionPersistence();\n /*\n * The workbench runtimes were initialised here: a domain-plan inbox, an evolution overview and the SPA\n * host, each bound to a durable journal generation and an evolution verification port.\n *\n * All three projected an accepted-state ledger that no longer exists, so they were deleted rather than\n * repointed. When the operator surface returns it initialises at exactly this point — after continuity\n * is ready and before any semantic route is mounted — reading what it shows from git and the run\n * journal.\n */\n\n await this.registerApplicationDefinitionSpecifications();\n await this.initializeCompanionProviderDependencies(config.backendProviderRegistry, config.providerRuntime);\n // Observability reconcile + graceful-flush wiring. The companion does NOT\n // run `StartApplicationBackendService.initialize()` (custom startup), so\n // without this explicit call the LLM-observability sink flush would never\n // be registered with the shutdown coordinator and a supervisor SIGTERM\n // would drop the last buffered `$ai_generation` batch. Must run AFTER\n // `initializeCompanionProviderDependencies` (the provider registry must be\n // initialized for the LLM_OBSERVABILITY / OBSERVABILITY_TELEMETRY selection\n // lookups); never throws.\n this.observabilityBackendService.initialize();\n await this.initializeCompanionFlowsActors(config.flowsActorsRegistry);\n await this.initializePlatformRuntimeDependencies();\n await this.primeApplicationIdentity();\n /*\n * Restart reconciliation of interrupted coding runs — wired 2026-08-24 at exactly the point the\n * 2026-08-23 note reserved (after the runtime dependencies, BEFORE any semantic route is mounted,\n * so no admission can race a stale PROCESSING row). A fresh process cannot prove a previous\n * process's Claude Code subprocess is gone, so each such row terminalizes as ABORTED /\n * INTERRUPTED_REQUIRES_REVIEW with a captured worktree snapshot — evidence for the human, never a\n * revert. BEST-EFFORT: a boot path must not fail closed on something whose remedy needs the very\n * companion it would stop (`continuity-drift-and-cas-basis.md`, Rule 3).\n */\n /*\n * Every run this restart interrupted, coding runs and generation steps alike: their writes are\n * recovered in ONE pass after both sweeps (#1805). They shared one tree, so recovering each kind in\n * its own sweep committed the other kind's files under the first run's name. Collected as each sweep\n * FINDS them, not from what it returns: a sweep can still throw after settling a run ABORTED, and a\n * run lost here is found by no later boot.\n */\n const interruptedRuns: InterruptedRun[] = [];\n const collectInterrupted = (run: InterruptedRun): void => { interruptedRuns.push(run); };\n /*\n * What this boot found in flight, for the intervention ledger (#2231): a boot with runs in flight IS a\n * restart, and this is the only moment that is known — the rows only say each run was interrupted.\n */\n const bootAt = new Date().toISOString();\n const restart = { codingTaskIds: [] as string[], playbookExecutionIds: [] as string[], generationExecutionIds: [] as string[] };\n try {\n const { reconciledTaskIds } = await this.codingAgentDispatchService.reconcileInterruptedApplicationCodingTasks(undefined, { onInterrupted: collectInterrupted });\n restart.codingTaskIds.push(...reconciledTaskIds);\n // Always logged, so \"the reconciliation ran and found nothing\" is distinguishable from \"it never\n // ran\" — a silent best-effort step is unverifiable (negative-results rule).\n this.logDebug('Startup coding-task reconciliation completed', { interrupted: reconciledTaskIds.length });\n if (reconciledTaskIds.length > 0) {\n this.logger.warn(\n 'Startup reconciliation terminalized interrupted application-coding task(s) as '\n + 'INTERRUPTED_REQUIRES_REVIEW — a previous companion process left them PROCESSING. '\n + 'Review their captured change sets before retrying.',\n { reconciledTaskIds },\n );\n }\n } catch (error) {\n this.logger.warn('Startup coding-task reconciliation failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n /*\n * Restart reconciliation of ORPHANED playbook runs (#1360). Since #1358 a playbook run is an actor\n * execution the engine's driver opens and settles — and the only thing that settles it is the\n * driver in the process that opened it. A companion taken away mid-run (ordinary here: parallel\n * sessions land engine code and the supervisor respawns it) left that execution and its task at\n * PROCESSING forever, a run that reads as \"running\" with nothing running it. A companion that has\n * just started is running nothing, and there is one per application, so every PROCESSING\n * execution of its system is an orphan by construction: settled ABORTED, its progress checkpoint\n * left in place so re-running the composite continues it.\n *\n * Same place and same posture as the coding reconciliation above: before any semantic route is\n * mounted, and BEST-EFFORT — a boot path must not fail closed on something whose remedy needs the\n * very companion it would stop.\n */\n try {\n const { aborted, restored } = await this.actorsSystemService.reconcileOrphanedActorExecutions(META_WORKFLOWS_SYSTEM_REF);\n restart.playbookExecutionIds.push(...aborted, ...restored);\n this.logDebug('Startup playbook-run reconciliation completed', { aborted: aborted.length, restored: restored.length });\n if (restored.length > 0) {\n this.logger.warn(\n 'Startup reconciliation put playbook run(s) back to waiting on their question — a previous companion process '\n + 'stopped while continuing an answer. Answer again to continue.',\n { restored },\n );\n }\n if (aborted.length > 0) {\n this.logger.warn(\n 'Startup reconciliation settled orphaned playbook run(s) ABORTED — a previous companion process left them '\n + 'PROCESSING. A composite among them keeps its progress checkpoint: re-run it to continue.',\n { aborted },\n );\n }\n } catch (error) {\n this.logger.warn('Startup playbook-run reconciliation failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n /*\n * The agent-work records a previous process OWED (#1599 I3, #1922): a review of an actor's work whose settle won\n * and whose process died before its record. The settling swap left the whole record on the row; this writes it\n * (`ROW_REPAIR`, metadata only). No grace: a companion that has just started holds no settle in flight, and it is\n * the only writer of its application's actor rows. Best-effort, like the reconciliations above — a repair that\n * fails leaves its marker for the next start.\n */\n try {\n const repair = await this.actorsSystemService.repairOwedActorCorrectionRecords(undefined, { graceMs: 0 });\n if (repair.failed > 0) {\n this.logger.warn('Startup could not write every owed actor review record; their markers stay for the next repair tick.', { ...repair });\n }\n } catch (error) {\n this.logger.warn('Startup actor review record repair failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n // And on a clock (#2189): a record write that failed without a crash is repaired within a minute, not at the next start.\n this.stopOwedActorReviewRecordRepairTick ??= startOwedActorReviewRecordRepairTick({\n repair: () => this.actorsSystemService.repairOwedActorCorrectionRecords(),\n logger: this.logger,\n describeError: describeCaughtError,\n });\n /*\n * And the clocks of the companion's own actor questions (#2807): a question whose system declares deadlines lapses\n * LAPSED and fires each reminder stage once, every minute. The engine's sweep reads only an application's actor plane\n * and is inert here. Nothing to read until a companion system declares deadlines.\n */\n this.stopActorQuestionDeadlineSweep ??= this.actorQuestionDeadlineSweep?.startPeriodicSweep() ?? null;\n /*\n * And the build system's (#1359): a companion GENERATION STEP is an execution too, since the day\n * it stopped living in an in-memory list of the last five dispatches. A restart in the middle of a\n * forty-minute label pass used to leave nothing anywhere saying it had been running; it now leaves\n * an orphan, settled ABORTED here. Its product is files on disk and the pipelines skip fresh\n * units, so re-dispatching the step continues rather than repeats. A coding dispatch that was\n * SELECTED and never admitted is swept by the coding reconciliation above — the engine reads\n * PENDING as well as PROCESSING.\n */\n try {\n const { aborted } = await this.codingAgentDispatchService.reconcileInterruptedBuildGenerationSteps(APPLICATION_BUILD_SYSTEM_REF, undefined, { onInterrupted: collectInterrupted });\n restart.generationExecutionIds.push(...aborted);\n this.logDebug('Startup build-dispatch reconciliation completed', { aborted: aborted.length });\n if (aborted.length > 0) {\n this.logger.warn(\n 'Startup reconciliation settled orphaned build generation step(s) ABORTED — a previous companion process '\n + 'left them running. What they had written is recovered next, under the autonomy posture; re-dispatch the step '\n + 'and its pipelines skip the units that are already fresh.',\n { aborted },\n );\n }\n } catch (error) {\n this.logger.warn('Startup build-dispatch reconciliation failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n try {\n await this.codingAgentDispatchService.recoverWritesOfInterruptedRuns(interruptedRuns);\n } catch (error) {\n this.logger.warn('Startup recovery of interrupted runs\\' writes failed; they stay for review (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n // Never throws: a report must not stop a boot. Writes nothing when nothing was in flight.\n await this.interventionLedger.recordRestart({ bootAt, ...restart });\n await this.initializePlatformHttpServer(config.customControllers);\n\n this.initialized = true;\n /*\n * Shed expired read-request trace sessions now, not only when the first request arrives: the sweep was\n * request-triggered, so an application whose companion is started and barely used kept its backlog\n * indefinitely (5.9 GB measured on scratch-journey). Fire-and-forget and best-effort inside the service.\n */\n this.traceabilityService.startReadRequestSessionRetention();\n this.startLocalReadinessObservation();\n this.logDebug('Dev Companion Application started');\n }\n\n private async initializePlatformExecutionPersistence(): Promise<void> {\n const registryInit = await this.resolveResourceRegistryInitInputs();\n\n // The companion signs people in against the PLATFORM database, whose organizations are of the platform's own type, so\n // the role rule must know that type (#3202). The configuration keeps the application's types: it describes the\n // application, and the configuration boundary refuses any other `organizationTypes`.\n this.resourcesRegistryService.useIdentityStoreOrganizationTypes(WILDO_PLATFORM_ORGANIZATION_TYPES);\n\n /*\n * The two `as never` crossings that stood here are gone: `ResourceConfiguration_InitializationFactoryMap`\n * used without a type argument resolved to `undefined`, so the engine signature literally accepted\n * `undefined` and these real maps had to be forced through it. The bare form now resolves to the\n * open map, so the maps assembled above are assignable on their own terms (#44).\n */\n await this.resourcesRegistryService.initialize(\n registryInit.sharedConfigurations,\n registryInit.sharedFieldIdentifiers,\n registryInit.sharedRelationships,\n registryInit.backendConfigurations,\n registryInit.backendFieldIdentifiers,\n registryInit.backendRelationships,\n );\n\n const resourcesRegistry = this.resourcesRegistryService.getResourcesRegistry();\n const resourceConfigurations = new Map(\n Object.entries(resourcesRegistry.resourceConfigurations) as [\n ResourceType,\n ResourceConfiguration<any, any, any>,\n ][],\n );\n\n await this.repositoriesRegistryService.initializeRepositories(\n resourceConfigurations,\n this.mongoDBService.getConnection() || undefined,\n );\n\n // Keep the registry-mirror signal (source + count) but NOT the full\n // resourceTypes list: dumping all ~78 keys floods the dev console on every\n // startup. `registrySource` (a `ResourceRegistryInitSource` value)\n // and `resourceCount` are enough to confirm the companion mirrored the\n // backend registry — the load-bearing diagnostic for the recurring\n // \"companion didn't see the app's resources\" bug class.\n this.logDebug('Companion platform execution persistence initialized', {\n registrySource: registryInit.source,\n resourceCount: resourceConfigurations.size,\n });\n }\n\n /**\n * Register the application's app-level definition specifications (roles +\n * features) into the `@wildo-ai/saas-specifications` cross-registry — the\n * missing app half of a documented two-step registration chain.\n *\n * `getAllRegisteredRoleSpecifications()` (and the feature twin) is the source\n * of truth the companion i18n labelling collector reads (`collectRoleKeys()`\n * in `i18n-labelling/utils/role-lifecycle-keys.utils.ts` derives\n * `roles.<ref>.{label,description}` from it) AND the source the cross-registry\n * assertions resolve `roleRefs` / `requiredFeatures` against. The engine\n * registers its 12 core roles + baseline features as an import side-effect of\n * `@wildo-ai/saas-specifications` (`engine/_bootstrap.ts`), but an\n * application's OWN roles/features — the extendable-enum arm\n * (`RolesSchema = … | z.string().min(1)`, for example application-defined\n * `CUSTOM_APP_MANAGER` / `CUSTOM_ORG_SUPERVISOR`) — were only ever handed to\n * the companion as companion-export DATA for the context factory; nothing ever\n * registered them. Consequence (the bug this fixes): `collectRoleKeys()` saw\n * only the engine baseline, so every app-defined role got NO label key and\n * fell back to a humanized token at runtime.\n *\n * Safe by construction: the app's `roleSpecifications` / `featureSpecifications`\n * companion-exports already spread the engine baseline in FIRST (see the app's\n * `buildRoleSpecificationMap(...engineRoleSpecifications, …customRoles)`), and\n * `register*Specifications` is idempotent with a shape-equality guard — so\n * re-registering the engine entries is a no-op and only the app's own entries\n * are actually added.\n *\n * Scope — roles + features ONLY. Both are already in populated / fail-closed\n * mode from the engine bootstrap, so adding app entries cannot flip validation\n * semantics. Milestone/product are engine-EMPTY (fail-soft pass-through);\n * registering them would flip fail-soft → fail-closed and could surface a\n * previously-tolerated dangling ref, so they are deliberately out of scope and\n * belong in a dedicated pass.\n *\n * Best-effort: a specifications package whose authored source cannot be\n * evaluated yet (mid-edit, or importing a sibling package that is not built)\n * must not block companion startup (mirrors\n * {@link resolveResourceRegistryInitInputs}). On failure the\n * companion still starts; app-defined role/feature labels simply stay\n * un-generated until the package resolves.\n */\n private async registerApplicationDefinitionSpecifications(): Promise<void> {\n try {\n const specExports = await loadSpecificationsCompanionData(this.companionContext);\n\n const roleSpecifications = specExports.roleSpecifications as RoleSpecification | undefined;\n const featureSpecifications = specExports.featureSpecifications as\n | FeatureSpecification\n | undefined;\n\n if (roleSpecifications) registerRoleSpecifications(roleSpecifications);\n if (featureSpecifications) registerFeatureSpecifications(featureSpecifications);\n\n this.logDebug('Companion registered application definition specifications', {\n roleSpecCount: roleSpecifications ? Object.keys(roleSpecifications).length : 0,\n featureSpecCount: featureSpecifications ? Object.keys(featureSpecifications).length : 0,\n });\n } catch (error: unknown) {\n this.logger.warn(\n 'Companion could not register application role/feature specifications into the '\n + 'specifications cross-registry; app-defined roles/features will be ABSENT from i18n '\n + 'label-key collection and cross-registry assertions until this resolves.',\n { error: describeCaughtError(error) },\n );\n }\n }\n\n /**\n * Resolve the inputs for the companion's `ResourcesRegistry` initialization.\n *\n * The companion must see the SAME resource vocabulary the backend API runtime\n * sees — engine resources AND the application's own domain resources — so that\n * every registry-driven companion lane materializes the full surface. The most\n * load-bearing consumer today is the i18n labelling planner: `planResourceUnits`\n * enumerates `resourcesRegistryService.getResourcesRegistry().resourceConfigurations`\n * and emits one `resource:<type>` unit per entry. If the app's resources are\n * absent here, they are labellized by NOBODY (the frontend-derived lane\n * deliberately drops `resources.*`, deferring to `planResourceUnits`), and the\n * app's own resources fall back at runtime to humanized field names.\n *\n * The application exposes its full module set through the standard\n * companion-export surface — `loadSharedModules()` returns\n * `[engineSharedModule, ...appSharedModules]` and `loadBackendModules()` the\n * matching backend owners — the SAME set the backend API builds its registry\n * from (`buildSharedSaaSModulesRegistry` + `mergeBackendDomainModules`). We\n * mirror that assembly here — and then UNION the platform-core persistence\n * vocabulary on top (see the inline comment in the success branch): the\n * companion is also the local platform microservice for execution rows, so\n * its registry = backend-API vocabulary ∪ platform-core persistence\n * vocabulary, with app/engine registrations winning on key collisions.\n *\n * Best-effort with a hard fallback: if the app companion-exports cannot be\n * loaded (e.g. a not-yet-built `dist`), fall back to the statically-imported\n * platform-core engine vocabulary so the companion still starts. The fallback\n * degrades app-resource labelling but never blocks startup — strictly no worse\n * than the prior platform-core-only behavior.\n */\n private async resolveResourceRegistryInitInputs(): Promise<{\n source: ResourceRegistryInitSource;\n sharedConfigurations: Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>;\n sharedFieldIdentifiers: { [key: string]: string } | undefined;\n sharedRelationships: ResourceRelationship[];\n backendConfigurations: Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>;\n backendFieldIdentifiers: { [key: string]: string } | undefined;\n backendRelationships: ResourceRelationship[];\n }> {\n try {\n /*\n * IN-PROCESS, deliberately (#3268): the companion's own resource registry is built from these modules, whose\n * resource configurations are FACTORIES this process calls, so they cannot arrive as data. This runs once, at\n * boot, in the same module generation as the assembly's backend read; no reader of a build wave re-imports either\n * package for it.\n */\n const [sharedExports, backendExports] = await Promise.all([\n loadSharedLibraryCompanionExports(this.companionContext),\n loadBackendCompanionExports(this.companionContext),\n ]);\n const [sharedModules, backendOwnedModules] = await Promise.all([\n sharedExports.loadSharedModules(),\n backendExports.loadBackendModules(),\n ]);\n\n const sharedRegistry = buildSharedSaaSModulesRegistry(...sharedModules);\n const mergedBackend = mergeBackendDomainModules(\n ...backendOwnedModules.flatMap((ownedModule) =>\n ownedModule.backendModule ? [ownedModule.backendModule] : [],\n ),\n );\n\n // UNION, not either/or: the app companion-exports mirror carries the\n // backend-API vocabulary (engine + app modules — what labelling and\n // spec lanes need), but the companion is ALSO the local platform\n // microservice that persists execution rows (`wildoApplication`,\n // `wildoApplicationActorSystemExecutions`, `wildoApplicationActorTasks`,\n // …) — a PLATFORM-plane vocabulary the backend-API registry does NOT\n // contain. The 2026-06-17 mirror fix made this branch app-exports-only,\n // silently evicting those platform resources: every live\n // `CompanionExecutionsCompanionService` call then failed ownership\n // resolution with `repositories_registry_not_found` (it reads the\n // `wildoApplication` repo first). Unit tests mock the repositories, so\n // the first live coding-agent dispatch (meta-workflows Step 4,\n // 2026-07-03) is what surfaced it. Spread order pins app/engine\n // registrations to WIN over a same-keyed platform-core entry.\n return {\n source: ResourceRegistryInitSource.APP_COMPANION_EXPORTS,\n // These spreads carried a `Record<string, unknown>` cast each, plus an extra `unknown` hop on\n // the app registry, and an outer assertion to put the factory type back. All of it existed\n // because `ResourceConfiguration_InitializationFactoryMap` used without a type argument\n // resolved to `undefined`, so every field carrying that alias was statically `undefined`\n // while holding a real map. The alias now resolves to the open map, so the spreads type\n // themselves (#44).\n /*\n * The workbench module is spread FIRST so the existing precedence is untouched: an app or\n * engine registration of the same key still wins, exactly as it wins over platform-core.\n * Its keys are workbench-specific (`workbench*`), so a collision would itself be a defect.\n */\n sharedConfigurations: {\n ...companionWorkbenchSharedModule.resourceConfigurations,\n ...companionPlatformCoreSharedModule.resourceConfigurations,\n ...sharedRegistry.resourceConfigurations,\n },\n sharedFieldIdentifiers: {\n ...(companionWorkbenchSharedModule.resourceFieldIdentifiers ?? {}),\n ...(companionPlatformCoreSharedModule.resourceFieldIdentifiers ?? {}),\n ...(sharedRegistry.resourceFieldIdentifiers ?? {}),\n },\n sharedRelationships: [\n ...(companionWorkbenchSharedModule.resourceRelationships ?? []),\n ...(companionPlatformCoreSharedModule.resourceRelationships ?? []),\n ...(sharedRegistry.resourceRelationships ?? []),\n ],\n backendConfigurations: {\n ...(companionPlatformCoreBackendModule.resourceConfigurations ?? {}),\n ...(mergedBackend.resourceConfigurations ?? {}),\n },\n backendFieldIdentifiers: {\n ...(companionPlatformCoreBackendModule.resourceFieldIdentifiers ?? {}),\n ...(mergedBackend.resourceFieldIdentifiers ?? {}),\n },\n backendRelationships: [\n ...(companionPlatformCoreBackendModule.resourceRelationships ?? []),\n ...(mergedBackend.resourceRelationships ?? []),\n ],\n };\n } catch (error: unknown) {\n this.logger.warn(\n 'Companion could not load application companion-exports for the resources registry; falling back to platform-core engine vocabulary only. Application-owned resources will be ABSENT from the companion registry — their i18n labels will not be generated until this resolves.',\n { error: describeCaughtError(error) },\n );\n /*\n * The workbench vocabulary is unioned HERE TOO, and that is the point of this block existing\n * separately: its resources are INTROSPECTION-backed projections served by this companion, so\n * they are exactly the ones that must survive an application whose companion-exports failed to\n * load. Registering them only on the success path would make the operator surface disappear\n * precisely when someone needs it to see WHY the application will not load.\n */\n return {\n source: ResourceRegistryInitSource.PLATFORM_CORE_FALLBACK,\n sharedConfigurations: {\n ...(companionWorkbenchSharedModule.resourceConfigurations as Record<string, unknown>),\n ...(companionPlatformCoreSharedModule.resourceConfigurations as Record<string, unknown>),\n } as Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>,\n sharedFieldIdentifiers: {\n ...(companionWorkbenchSharedModule.resourceFieldIdentifiers ?? {}),\n ...(companionPlatformCoreSharedModule.resourceFieldIdentifiers ?? {}),\n },\n sharedRelationships: [\n ...(companionWorkbenchSharedModule.resourceRelationships ?? []),\n ...(companionPlatformCoreSharedModule.resourceRelationships ?? []),\n ],\n backendConfigurations:\n (companionPlatformCoreBackendModule.resourceConfigurations ?? {}) as Record<string, ResourceConfiguration_InitializationFactory<any, any, any>>,\n backendFieldIdentifiers: companionPlatformCoreBackendModule.resourceFieldIdentifiers,\n backendRelationships: companionPlatformCoreBackendModule.resourceRelationships ?? [],\n };\n }\n }\n\n /**\n * The companion is the FOURTH host of the on-demand provider loader (#330), and the only one that\n * used to pass no topology at all.\n *\n * It already loaded its own `companion.runtime-providers.generated.json` — `loadProviderRuntime` in\n * `companion-startup-assembly.ts` reads it and hands it over as `config.providerRuntime` — and then\n * initialised the registry without it, which meant the companion process received the ENGINE'S\n * WHOLE CATALOGUE: twenty-two provider modules, six pulling a model SDK, for a scope that names a\n * handful. So closing this seam needed no new request shape and no new file, only the wiring of a\n * value that was already in hand.\n *\n * The artifact reaches `initialize` too, so the companion gets the same fail-loud refusal every\n * other host gets when its scope names a provider nothing can supply.\n */\n private async initializeCompanionProviderDependencies(\n backendProviderRegistry: unknown,\n providerRuntime: CompanionStartupConfig['providerRuntime'],\n ): Promise<void> {\n const resolved = await resolveBackendProviderRegistry({\n // The companion artifact is single-scope (`artifactKind: 'companion'`, `scope` already projected\n // by the CLI). It satisfies the loader's `DeclaredProviderTopology` structurally, which is why\n // that contract is stated as a shape rather than as the backend's nominal artifact type.\n providerRuntime,\n applicationFragment: asBackendProviderFragment(backendProviderRegistry),\n });\n this.backendProviderRegistryService.initialize(resolved.registry, providerRuntime, resolved.unresolved);\n this.logDebug('Companion backend provider registry initialized', {\n providerRuntimeApplied: Boolean(providerRuntime),\n providerCount: resolved.registry.modules.size,\n });\n\n await this.externalProvidersRegistryService.refreshFromConfig();\n // #3002: a configuration pointing a provider at a secret its module does not declare is refused here as in the\n // application backend, so the companion does not start reading it as \"not enabled\". The remedy is a file edit.\n this.externalProvidersRegistryService.assertAuthoredSecretRefsDeclared();\n }\n\n private async initializeCompanionFlowsActors(flowsActorsRegistry: CompanionStartupConfig['flowsActorsRegistry']): Promise<void> {\n // The companion's judgment work runs on Opus 5.5, not the framework default (2026-11-06): set before any agent resolves.\n this.flowsActorsRegistryService.useModelApplicabilityPreference(COMPANION_MODEL_APPLICABILITY_PREFERENCE);\n await this.flowsActorsRegistryService.initialize(\n flowsActorsRegistry?.flowActorSystemsFactoryMap,\n flowsActorsRegistry?.agents,\n /*\n * The third collection the engine's own startup passes and this one never did: without it an\n * agent's declared function refs resolve to nothing. The creation assistant (#1454) is the\n * first companion agent whose work IS its function tools.\n */\n flowsActorsRegistry?.functionTools,\n );\n this.installLanguageModelRoute();\n }\n\n /**\n * Route the companion's language-model calls through Claude Code over ACP (#3472), unless\n * `WILDO_LANGUAGE_MODEL_TRANSPORT=api`.\n *\n * A route that cannot be installed — the ACP binding not enabled in this application's provider configuration — is\n * reported as an ERROR naming the consequence, and the calls stay on the API keys: refusing to start would take down\n * every surface of the companion for a cost concern, and the error is what makes the cost visible.\n */\n private installLanguageModelRoute(): void {\n // The heartbeat that holds a supervisor restart while a routed call's agent is running (#3472, 2026-11-15).\n const route = resolveCompanionLanguageModelRoute(\n process.env,\n createLanguageModelRunHeartbeatReporter(this.companionContext.saasRoot, (message, error) =>\n this.logger.warn(message, { reason: describeCaughtError(error) })),\n );\n if (route === undefined) {\n this.logger.info('Language-model calls stay on the API keys (WILDO_LANGUAGE_MODEL_TRANSPORT=api)');\n return;\n }\n try {\n this.agentsService.routeLanguageModelCallsOverAgentClientProtocol(route);\n } catch (error) {\n this.logger.error('Language-model calls could NOT be routed over ACP and will spend the API keys', {\n acpProviderRef: route.acpProviderRef,\n executionProfileRef: route.executionProfileRef,\n model: route.model,\n reason: describeCaughtError(error),\n });\n }\n }\n\n /**\n * Platform-mode startup in `StartApplicationBackendService` intentionally skips\n * provider, Redis, storage, and HTTP phases because platform owners usually\n * restore them explicitly once their config is hydrated. The companion uses the\n * same pattern so its API lane becomes a truthful local platform microservice\n * rather than a partially initialized app-backend bootstrap.\n */\n private async initializePlatformRuntimeDependencies(): Promise<void> {\n if (this.fileStorageRouter.isConfigured()) {\n /*\n * Retried rather than attempted once (#1195): these credentials come from apps-manager, which the\n * companion routinely starts alongside, and storage is fail-closed — so losing that race once left\n * file operations dead for the whole process lifetime while readiness kept answering 200.\n */\n await initializeFileStorageWithRetry({\n initialize: () => this.fileStorageRouter.initialize(),\n onReady: (attempt) => { this.logDebug('Companion file storage initialized', { attempt }); },\n onRetry: ({ attempt, error }) => {\n // Without the level floor: an attempt the loop repeats is not the fault — `onExhausted` is,\n // and it keeps the floor (#1637; `projectRetriedAttemptErrorLogFields`).\n this.logDebug('Companion file storage initialization failed; retrying', {\n attempt,\n ...projectRetriedAttemptErrorLogFields(error),\n });\n },\n onExhausted: ({ attempts, error }) => {\n this.logger.warn(\n 'Companion file storage initialization failed; file operations may fail at runtime',\n {\n // NOT `error instanceof Error ? … : String(error)`. `WildoError_Backend`\n // is a plain object, never an `Error`, so that ternary rendered the one\n // diagnostic this path produces as the literal '[object Object]' — which\n // is non-empty and carries exactly as much information as empty. Storage\n // is fail-closed with no fallback, so this message is all a reader gets.\n attempts,\n ...projectCaughtErrorLogFields(error),\n },\n );\n },\n });\n }\n\n await this.externalProvidersRegistryService.refreshFromConfig();\n // #3002: as after the provider registry's first refresh above.\n this.externalProvidersRegistryService.assertAuthoredSecretRefsDeclared();\n\n try {\n await this.redisService.connect();\n this.logDebug('Companion Redis connection established');\n } catch (error) {\n this.logger.warn(\n 'Companion Redis connection failed; runtime fallbacks may be used where supported',\n {\n error: describeCaughtError(error),\n },\n );\n }\n }\n\n /**\n * Settle the creation CONVERSATION's turns this companion was running when it stopped (#1601): such a\n * turn is left PROCESSING for ever, and the creator's message reads as unanswered with nothing saying\n * why. The companion is the only host of this system, which is what makes a startup settlement\n * correct (see `settleInterruptedTurns`). Best-effort, like the startup reconciliations.\n *\n * ORDER IS THE WHOLE CONTRACT, on both sides:\n * - AFTER `initializeWorkbenchResourceControllers`, which is where the three `*FlowActorExecutions`\n * services come into existence. Called earlier (as it first was, 150451c8), every listing answered\n * `service_not_found` and the settlement reported `settled: 0` on every boot — inert, and quiet\n * about it, measured 2026-09-25.\n * - BEFORE the HTTP and WebSocket server listens, so no turn started by THIS process can exist yet:\n * everything still PROCESSING belongs to a host that is gone.\n */\n private async settleInterruptedConversationTurns(): Promise<void> {\n try {\n await this.conversationalExecution.settleInterruptedTurns([WORKBENCH_CREATION_CONVERSATION_SYSTEM_REF]);\n } catch (error) {\n this.logger.warn('Startup conversation-turn settlement failed; continuing (non-fatal by design).', {\n error: describeCaughtError(error),\n });\n }\n }\n\n private async initializePlatformHttpServer(\n customControllers: AbstractControllerBackendService[],\n ): Promise<void> {\n // P-29 auth floor — BEFORE the server starts listening: fail-closed\n // loopback assertion (no override env) + companion.token (0600) for\n // the token middleware on mutating routes. Runs after app-config\n // hydration because host resolution reads `runtime.endPoints`.\n await this.authFloorService.enforceStartupInvariants();\n\n await this.registerCustomControllers(customControllers);\n await this.initializeWorkbenchResourceControllers();\n await this.settleInterruptedConversationTurns();\n /*\n * The WebSocket server is MOUNTED, because this companion serves a frontend.\n *\n * It was skipped when the companion answered only the CLI. The workbench changed that: an\n * authenticated Wildo frontend opens a socket unconditionally — `UserOrgsContext` calls\n * `connectWebSocket` the moment a session restores, and there is no configuration that says\n * \"this backend has no realtime\". So skipping it does not mean \"no realtime\", it means a socket\n * that retries forever against a port with nothing listening, which the operator sees as a\n * permanent \"Reconnecting\" and which no log explains.\n */\n await this.httpServerService.initialize({ skipWebSocket: false });\n\n await this.startIntrospectionFreshnessPlane();\n this.startWebsiteCopyReviewSweep();\n this.startWebsiteVisualReviewSweep();\n }\n\n /**\n * Review the website runs whose copy review is missing or out of date (#2593). A run's review is started when the run\n * completes and is lost when the companion restarts during the judge call, which every engine change can cause; this\n * is where it is redone, and where a review that failed before (NOT_REVIEWED) is retried. Started and not awaited:\n * each review is a model call, and none of it is something startup should wait for or fail on.\n */\n private startWebsiteCopyReviewSweep(): void {\n void this.buildDispatchService.requestWebsiteCopySweep({ retryNotReviewed: true }).catch((error: unknown) => {\n this.logger.warn('The website copy review sweep could not start', { error: describeCaughtError(error) });\n });\n }\n\n /**\n * Review the website runs whose drawing has no review (#2785), retrying one that could not be reviewed before (the\n * website was not running, the camera was missing). Started and not awaited, like the copy sweep: each review\n * photographs a page and calls a model, and startup neither waits for it nor fails on it.\n */\n private startWebsiteVisualReviewSweep(): void {\n void this.buildDispatchService.requestWebsiteVisualSweep({ retryNotReviewed: true }).catch((error: unknown) => {\n this.logger.warn('The website visual review sweep could not start', { error: describeCaughtError(error) });\n });\n }\n\n /**\n * Resolve and cache the APPLICATION record's identity, which the engine's own startup does at its\n * step 7.65 and this custom startup must do itself.\n *\n * Every SYNCHRONOUS reader of the canonical id throws until this has run: the introspection\n * notifier, which names the APPLICATION collection room by it (#1767), and the engine's file, PDF\n * and feature-resolution scope derivations. Nothing in the companion called it, so those readers\n * worked only after some ASYNC reader happened to settle the identity — in practice the first model\n * call — and after every restart a board change reached nobody until then.\n *\n * Placed directly after the runtime dependencies (the repositories are up; the record exists from\n * the application's own initialisation), so it also precedes the startup reconciliations, the HTTP\n * server and the freshness plane: no reconciliation, request or publication runs ahead of it.\n *\n * BEST-EFFORT, unlike the engine's fatal step. There the id stamps rows, and a backend that cannot\n * name its application must not write; here the synchronous readers already refuse on their own,\n * and a companion that will not boot cannot be used to repair the cause (Rule 3 of\n * `continuity-drift-and-cas-basis.md`). The warning is what makes the degraded state visible.\n */\n private async primeApplicationIdentity(): Promise<void> {\n try {\n const identity = await this.applicationIdentity.prime();\n this.logDebug('Canonical application identity resolved', { applicationRecordId: identity._id });\n } catch (error) {\n this.logger.warn(\n 'The APPLICATION record identity could not be resolved at startup. Until it is, the workbench '\n + 'receives no pushed board changes and scope-derived file/PDF reads refuse. (non-fatal by design)',\n { error: describeCaughtError(error) },\n );\n }\n }\n\n /**\n * Report every stretch in which this process's event loop stopped keeping time, with what was running\n * (#2394). Started before anything that can block, beside the readiness heartbeat, so a stall during\n * boot is reported too.\n *\n * On app-creation-test-005 the companion stopped answering for minutes during build waves while its\n * `/health` handler awaited nothing, so the thread was held, and nothing in the log said so. These\n * lines are what tells the next measurement when to take a CPU profile and whether a fix removed the\n * stalls.\n */\n private startEventLoopStallMonitor(): void {\n // `initialize()` may run again after a failed boot; a second monitor would double every report.\n if (this.eventLoopStallMonitor) return;\n const readUtilization = createEventLoopUtilizationReader();\n this.eventLoopStallMonitor = new EventLoopStallMonitor(\n (report) => {\n this.logger.warn('Companion event loop stalled', { ...report, eventLoopUtilization: readUtilization() });\n },\n () => {\n const memory = process.memoryUsage();\n return {\n ...this.introspectionSourceWatcher.describeActivity(),\n heapUsedMb: Math.round(memory.heapUsed / 1_048_576),\n rssMb: Math.round(memory.rss / 1_048_576),\n };\n },\n );\n this.eventLoopStallMonitor.start();\n }\n\n /**\n * Restart this companion at a boundary before its heap reaches its limit (#3205), see\n * {@link HeapPressureMonitor}. Under the app-creator supervisor the restart is a graceful shutdown with the\n * exit code that supervisor named; under the framework's dev supervisor it is a signal-file request, which\n * that supervisor also holds while a run beats its heartbeat.\n */\n private startHeapPressureMonitor(): void {\n if (this.heapPressureMonitor) return;\n const saasRoot = this.companionContext.saasRoot;\n this.heapPressureMonitor = new HeapPressureMonitor({\n saasRoot,\n restart: (detail) => {\n const exitCode = readCompanionRestartExitCode(process.env);\n if (exitCode !== null) {\n void this.workerShutdownManager.initiateShutdown({ gracePeriodMs: 25_000, checkIntervalMs: 500, exitCode });\n return true;\n }\n return requestCompanionRestart(saasRoot, { reasonKey: 'heap-pressure', detail });\n },\n warn: (message, context) => this.logger.warn(message, context),\n });\n this.heapPressureMonitor.start();\n }\n\n /**\n * Start the plane that keeps introspection derivations current WITHOUT a reader asking.\n *\n * Ordered after the WebSocket server on purpose: the notifier's whole output is a socket emit, and\n * starting it before the server exists would give it a window in which a recompilation is computed\n * and then silently dropped.\n *\n * Failure here is NON-FATAL, and that is the important part. Everything this plane does is a\n * latency and freshness improvement over a path that still works without it: with no watcher the\n * derivation state stays in per-read observation, which is exactly the behaviour issue #159\n * shipped. A companion that refuses to boot because a directory could not be watched would trade a\n * slow workbench for no workbench — and the remedy for that would need the companion this failure\n * just prevented from starting (`continuity-drift-and-cas-basis.md` Rule 3).\n */\n private async startIntrospectionFreshnessPlane(): Promise<void> {\n try {\n this.introspectionResourceNotifier.start();\n // Before the watcher, not after it: with no watcher the sweep walks on every tick (no change feed vouches\n // for anything), so a watcher that fails to start must not also keep the sweep from starting.\n this.creationPlaneProjection.start();\n await this.introspectionSourceWatcher.start();\n this.logDebug('[StartCompanionApplication] Introspection freshness plane started');\n\n /*\n * Warming is started and NOT awaited. It spawns one subprocess per declared behavior, each\n * importing the whole target application, so awaiting it would add the very 8.8 s to boot that\n * it exists to remove from the first read. Boot completing while warming runs is the correct\n * shape: a read arriving mid-warm joins the in-flight compilation rather than starting a\n * second one.\n */\n void this.introspectionResourceSource.warmDeclaredDerivations()\n .then(({ attempted, failed }) => {\n if (attempted === 0) return;\n this.logger.info('Introspection derivations warmed', { attempted, failed });\n })\n .catch((error: unknown) => {\n this.logger.warn('Introspection derivation warming failed', {\n error: describeCaughtError(error),\n });\n });\n\n /*\n * The schema-plan sync state is warmed on the same terms, and for the same reason: it is the\n * other derivation a reader waits on. Resolving whether the migration step has landed spawns\n * `wildo db diff --check`, which boots the CLI and imports the application's compiled modules\n * registry — 8-14 s measured on `examples/wonder-todos`, of which ~5.5 s is the import. The\n * answer is cached against a signature of its inputs, so the cost falls entirely on the FIRST\n * read of each companion lifetime; warming moves that read off the board and onto boot, where\n * nobody is waiting. Under `wildo local dev` the companion respawns often, so that first read\n * is not a rare event.\n *\n * Called as a FUNCTION, not through the build-generation-step service, deliberately: reaching\n * it through the service would pull the labelling, email and brand service graph into the boot\n * graph to answer a question about two files.\n */\n void resolveSchemaPlanSyncState(this.companionContext.saasRoot)\n .then((state) => this.logDebug('[StartCompanionApplication] Schema-plan sync state warmed', { state }))\n .catch((error: unknown) => {\n this.logger.warn('Schema-plan sync state warming failed; the first build-plan read pays for it instead', {\n error: describeCaughtError(error),\n });\n });\n\n /*\n * Warming at boot fixes the first read of a companion lifetime. It does NOT fix the EDIT loop:\n * every `dist` rebuild moves the model's signature, so without this the next board read pays the\n * full 15s again. The loop re-derives in the background once the model has SETTLED, so the board\n * meets a fresh answer instead of waiting for one.\n */\n this.stopSchemaPlanFreshnessLoop = startSchemaPlanFreshnessLoop({\n saasRoot: this.companionContext.saasRoot,\n onRefreshFailed: (error: unknown) => {\n this.logger.warn('Background schema-plan refresh failed; the next build-plan read re-derives instead', {\n error: describeCaughtError(error),\n });\n },\n });\n } catch (error) {\n this.logger.warn(\n 'Introspection freshness plane failed to start; derivations fall back to per-read source observation',\n { error: describeCaughtError(error) },\n );\n }\n }\n\n /**\n * Generated CRUD routes for the WORKBENCH resources — and for nothing else.\n *\n * ## The whitelist is mandatory, not a tidy-up\n *\n * `ControllersRegistryHandlerBackendService.initialize()` creates an HTTP controller for EVERY\n * resource in the registry when no whitelist is passed. The companion's registry is the union of\n * the application's own vocabulary, platform-core's and the engine's — on wonder-crm that is ~80\n * resources — so an unwhitelisted call would expose generated CRUD over the observed\n * application's data on a dev daemon that, today, authenticates nothing. The parameter is opt-IN,\n * which makes omitting it fail OPEN.\n *\n * The whitelist is derived from `WorkbenchShared_ResourceType`, never hand-listed: a workbench\n * resource added tomorrow is exposed automatically, and — more importantly — a resource that is\n * NOT a workbench resource can never appear here by an editing slip.\n *\n * ## Why this is safe to call unconditionally\n *\n * Every workbench resource is INTROSPECTION-backed and declares only READ and LIST; the adapter\n * refuses all twelve write members. So the surface this opens is read-only by construction, not by\n * policy.\n */\n /**\n * Resource SERVICES the mounted frontend-support controllers need, beyond the workbench's own.\n *\n * `users` is what `AuthenticationController` resolves to identify and authenticate the operator —\n * the application's seeded administrator, in the database this companion and the application\n * backend share.\n *\n * Deliberately a short explicit list rather than \"everything\": a service the companion cannot\n * build aborts the whole registry initialization (`createService` THROWS), so widening blindly\n * turns one unbuildable resource into a failed boot. Each entry is here because a mounted\n * controller demonstrably asks for it.\n */\n private static readonly FRONTEND_SUPPORT_SERVICE_RESOURCE_TYPES: readonly string[] = [\n CoreResourceType.USERS,\n ...ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES,\n /*\n * The CONVERSATION plane (#1454, Step 4). `FlowsActorsController`'s history route lists the\n * caller's `userFlowActorExecutions`, and `ConversationalExecutionBackendService` persists every\n * thread through `SystemAccess` on the owner variant — user here, since the WebSocket surface is\n * user-scoped — and the other two variants exist for the A2A and machine surfaces the same\n * runtime serves. Measured 2026-09-22 with only the two entries above: `/flows-actors/history`\n * answered `service_not_found`, and a turn would have failed at its first write.\n */\n CoreResourceType.USER_FLOW_ACTOR_EXECUTIONS,\n CoreResourceType.ORGANIZATION_FLOW_ACTOR_EXECUTIONS,\n CoreResourceType.APPLICATION_FLOW_ACTOR_EXECUTIONS,\n /*\n * The MODEL-SPEND GATE's inputs (#3902). Every model call this process makes for a signed-in\n * person (a workbench playbook run, a creation-assistant turn) is admitted by the engine's token\n * budget gate, which resolves the payer's allowance from a scope-features ledger and charges a\n * consumption counter, both through the services registry. Without these services the ledger\n * read answers `service_not_found`, the gate fails closed with `allowance_unverifiable`, and\n * every such run answers 503 before reaching the model. Measured on the workbench: a\n * `bottom_up__domain-plan` run started as an organization owner, refused on its `userFeatures`\n * read. The set is the engine's own, so a counter the gate gains later reaches this list with it.\n * Services only: none of these is mounted as a controller here.\n */\n ...MODEL_SPEND_GATE_RESOURCE_TYPES,\n ];\n\n /**\n * The engine manual controllers the companion mounts because it SERVES A FRONTEND.\n *\n * ## Why through the controllers registry rather than `registerCustomController`\n *\n * The registry's master router is mounted at `MAIN_API_BASE_PATH` (`/api/v1`) — the single source\n * of truth every Wildo frontend derives its URLs from. A controller registered as a CUSTOM\n * controller instead lands at `/api/custom/<controller-name>`, which is what an application's\n * OWN controllers want and is useless for an engine route a frontend already knows the path of.\n * Measured: the i18n controller registered that way answered correctly at\n * `/api/custom/i18n-controller/i18n/labels` while the workbench asked for `/api/v1/i18n/labels`\n * and got a 404, leaving every framework layout mounted and empty.\n *\n * This is exactly what `StartApplicationBackendService` does for an application — it merges\n * `getManualControllersBackend(...)` into the list it passes here — so the companion is using the\n * engine's own mounting path rather than a parallel one.\n *\n * ## Why a SUBSET, resolved by token\n *\n * `getManualControllersBackend()` returns the whole manual surface: authentication, OAuth, MCP,\n * A2A, files, features, charts, webhooks. Most of it has no business on a companion — an OAuth\n * provider, an MCP transport and a file surface answer to an application's clients, not to an\n * operator looking at one. Resolving the FOUR the workbench needs, by DI token, keeps the exposed\n * surface exactly what the frontend requires and nothing else, and needs no new engine export.\n *\n * Both are already bound in the engine container and injected above, so they receive the same\n * logger, error builder and services as everything else in this process.\n */\n private resolveFrontendSupportControllers(): AbstractControllerBackendService[] {\n return [\n // Labels for every framework component the workbench renders.\n this.i18nController,\n // The frontend bootstrap `ApplicationMainProvider` fetches before it mounts any provider.\n this.applicationConfigController,\n /*\n * Authentication, because the workbench renders the engine's own application shell and that\n * shell routes an unauthenticated visitor to `/login`.\n *\n * The operator signs in with `ADMIN_EMAIL` / `ADMIN_PASSWORD` (`PlatformAdminEnvKey`), which\n * apps-manager provisions in INIT mode, so this mounts an authentication surface over an\n * EXISTING user store rather than inventing a second identity for the workbench.\n *\n * That store is the PLATFORM's, NOT the application's. The two are different databases and\n * both hold a row for that email with different roles, so the operator authenticated here is\n * the platform identity, never the application administrator. `buildWorkbenchFrontendServiceEntry`\n * in `companion-platform-config.companion.ts` records the consequence in detail: `usersManagement`\n * is authored EMPTY because the platform identity carries no `userTypes`, and declaring the\n * application's type fails every workbench login with `authentication_user_type_mismatch`.\n *\n * The surface this opens is real and deliberately bounded: the companion asserts a loopback\n * bind at startup and fails closed otherwise, so these routes are reachable only from the\n * developer's own machine. If the companion is ever exposed beyond loopback that is a genuine\n * authentication problem for the whole daemon, not a property of this line.\n */\n this.authenticationController,\n /*\n * Feature resolution, which the application shell performs immediately AFTER a successful\n * login. Unmounted it answers 404 and the shell LOGS THE OPERATOR STRAIGHT BACK OUT —\n * measured as `200 /auth/authenticate` followed by `404 /features/resolved` and\n * `204 /auth/logout`, which presents as \"the password did not work\" and is nothing of the\n * kind.\n */\n this.featuresController,\n /*\n * The conversational plane's HTTP half (#1454, Step 4): `/flows-actors/frontend-info`, which is\n * how the workbench learns the creation assistant exists, and `/flows-actors/history`, which\n * is how it lists a creator's threads. The WebSocket half (`setupFlowsActorsHandlers`) was\n * already attached to every signed-in socket by the engine's own server; only the discovery\n * and history routes were missing, so the browser saw `systems = []` and rendered nothing.\n */\n this.flowsActorsController,\n ];\n }\n\n /**\n * The creation-plane CONTROL resources the workbench consumes AS resources.\n *\n * These are the platform's own control-plane rows — the actor tasks and executions the companion\n * itself writes (repository-direct) during playbook runs and coding dispatches. Their configs are\n * shared platform vocabulary (`wildo-application-tasks` / `wildo-application-executions` in\n * `@wildo-ai/platform-core-shared`), whose READ/LIST became ORG_MEMBER-gated API variants on\n * 2026-09-01 precisely for this consumption (the decision is recorded on\n * `createOrgMemberReadApiVariant` in those files). Every type in this list is mounted READ-ONLY\n * (`ResourceControllerMountMode.READ_ONLY`, #3357): only read-shaped operations get a route, and no upload or\n * field-validation route. The companion owns none of these writes over HTTP (its own writes are repository-direct),\n * and it runs none of the engine's custom implementations, so a write served here would skip what the application\n * backend adds to it. `organizations` needed this most: an engine resource whose write variants the application\n * backend must keep, so the configuration could not drop them as #3319 did for `wildoApplication`. The mode is a\n * property of the mount, so a write variant any of these configurations gains later is not mounted here either.\n *\n * A hand list rather than a derivation, deliberately: consuming a control-plane type is a\n * per-type DECISION (each one widens an HTTP surface), not a population to sweep.\n */\n private static readonly CREATION_CONTROL_PLANE_RESOURCE_TYPES: readonly string[] = [\n /*\n * The parent anchor first: every control-plane URL nests under\n * `…/wildo-application/{wildoApplicationId}/…`, and the workbench bootstraps that id by LISTing\n * this resource (one row per companion). Its config already carried API read variants; mounting is\n * all it needed.\n */\n CustomShared_ResourceType.WILDO_APPLICATION,\n /*\n * ORGANIZATIONS rides with the plane: it is the PRIMARY SCOPE of all three control-plane types,\n * so the workbench frontend registers it — and a registered organizations resource makes the\n * engine shell READ the org rows it scopes by. Unmounted, those reads 404 on every session\n * (measured); the rows exist in this application's own database, and the engine's standard\n * controller serves them behind ordinary auth.\n */\n CoreResourceType.ORGANIZATIONS,\n CustomShared_ResourceType.WILDO_APPLICATION_ACTOR_TASKS,\n CustomShared_ResourceType.WILDO_APPLICATION_ACTOR_SYSTEM_EXECUTIONS,\n CustomShared_ResourceType.WILDO_APPLICATION_FLOW_SYSTEM_EXECUTIONS,\n ];\n\n private async initializeWorkbenchResourceControllers(): Promise<void> {\n const workbenchResourceTypes = [\n ...(Object.values(WorkbenchShared_ResourceType) as string[]),\n ...StartCompanionApplicationService.CREATION_CONTROL_PLANE_RESOURCE_TYPES,\n ];\n\n /*\n * SERVICES before CONTROLLERS, and both whitelisted to the same set.\n *\n * A controller resolves its service by resource type at request time; without the service the\n * route mounts and answers `service_not_found`, which reads like a routing bug rather than a\n * missing registration. The whitelist matters more here than on the controllers side:\n * `createService` THROWS on failure and aborts the whole initialization, so building services\n * for all ~99 registry entries would let one resource the companion cannot service fail its\n * boot outright.\n */\n /*\n * SERVICES and CONTROLLERS get DIFFERENT whitelists, and the asymmetry is the point.\n *\n * A service is reachable only from code inside this process; a controller is an HTTP surface.\n * So the services list may widen to whatever the mounted controllers need, while the controllers\n * list stays exactly the workbench's own resources — no generated CRUD over the observed\n * application's data appears because authentication happens to need a user service.\n *\n * `AuthenticationController` resolves the `users` service to identify and authenticate an\n * operator. Without it every auth route mounts and answers `service_not_found`, which reads like\n * a routing bug and is really a missing registration.\n */\n /*\n * Labels BEFORE the controllers that serve them.\n *\n * `I18nBackendService` answers `{}` until it is initialized, and the companion never initialized\n * it — so `/i18n/labels` returned a correctly shaped empty map and every framework layout in the\n * workbench rendered its label KEYS. Initializing here, in the same step that mounts the route,\n * keeps the two facts adjacent: the surface and the content it serves.\n */\n await this.i18nService.initialize(companionCustomLabels);\n\n await this.servicesRegistryService.initializeServices([\n ...workbenchResourceTypes,\n ...StartCompanionApplicationService.FRONTEND_SUPPORT_SERVICE_RESOURCE_TYPES,\n ]);\n /*\n * The creation board's DISPATCH operations:\n * OVERRIDE_ALL custom implementations delegating to the companion's own services. Initialized\n * AFTER the services registry, because registrations validate against the CONFIGURED operation\n * paths at init — a drifting identifier fails the boot here instead of becoming unreachable\n * code (the exact silence the registry's own doc records). This list is the companion's WHOLE\n * custom-impl registry, deliberately: the engine's `CoreBackend_ServiceImplementationsFactories`\n * have never run in this process, and activating them here would change the behavior of every\n * engine resource the companion mounts as a side effect of a board feature.\n */\n this.customImplRegistry.initialize(createCreationPlaneDispatchFactories());\n /*\n * The engine's OWN runtime floor is mounted beside the workbench's resources, and it is the one\n * exception to \"controllers stay exactly the workbench's own resources\".\n *\n * It is not a widening of the observed application's surface. `ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES`\n * is the set the engine reads to restore an authenticated session, and it is CONTEXT-ADDRESSED:\n * `user_self` resolves to the CALLER's own record, so mounting it exposes an authenticated\n * operator to themselves and to nobody else.\n *\n * Mounting it is not optional. The frontend registry keeps these registered no matter what an\n * application excludes (the same constant enforces it there), so the browser WILL call\n * `/api/v1/user-self/:id/context` after every login. Serving a 404 makes session restoration\n * return false, and the shell logs out \"to avoid a half-restored state\" — login succeeds, the\n * token is valid, and the user lands back on the login form. Measured on the workbench: fixing\n * the registry alone moved the failure from a missing registry entry to this 404, one layer down.\n */\n const mountedResourceTypes = [...workbenchResourceTypes, ...ENGINE_RUNTIME_REQUIRED_RESOURCE_TYPES];\n /*\n * The collection-export PDF templates, BEFORE the controllers that serve their exports (#1645). The\n * companion never runs `StartApplicationBackendService.initialize()`, where an application binds its\n * templates, so the workbench binds its one here — with completeness asserted, so a workbench export\n * naming a template nobody provides fails this boot rather than its first download.\n *\n * Checked against the MOUNTED types only. The registry also holds the observed application's\n * resources, and an application declaring its own PDF export must not stop the companion booting\n * over a template only the application's backend renders.\n */\n this.pdfCollectionExportTemplates.initialize([\n createWorkbenchGovernedDocumentsPdfTemplate({\n dossier: this.dossierService,\n labelsFor: (locale) => this.i18nService.getLabels(locale as AvailableLanguage),\n }),\n ], { assertCompleteness: true, servedResourceTypes: mountedResourceTypes });\n await this.controllersRegistryService.initialize(\n this.resolveFrontendSupportControllers(),\n mountedResourceTypes,\n StartCompanionApplicationService.CREATION_CONTROL_PLANE_RESOURCE_TYPES,\n );\n this.logDebug('Workbench resource controllers initialized', { resourceTypes: mountedResourceTypes });\n }\n\n private async registerCustomControllers(customControllers: AbstractControllerBackendService[]): Promise<void> {\n for (const controller of customControllers) {\n this.httpServerService.registerCustomController(controller);\n }\n }\n\n /** Transport liveness only; semantic readiness is exposed separately below. */\n public isHttpServerRunning(): boolean {\n return this.httpServerService.isRunning();\n }\n\n /**\n * The continuity-readiness apparatus is gone (git is the accepted state; there is nothing to recover at\n * startup), so a companion whose HTTP server is up IS semantically ready. The literal keeps the\n * `companion-readiness.json` wire protocol the local-dev diagnostics collector already reads.\n */\n public getContinuityReadinessStatus(): 'READY' {\n return 'READY';\n }\n\n public getServerInfo(): string | null {\n return this.httpServerService.getServerInfo();\n }\n\n /**\n * Publish a sanitized process-local posture for the bootstrap-safe developer\n * diagnostic collector. This is not continuity authority and contains no\n * failure object, stack, environment value, token, or mutable semantic state.\n * Publication is best-effort so observability can never change startup.\n *\n * The discriminator mirrors the dependency-free root protocol as a thin\n * native gateway because the distributed companion cannot depend on files\n * from the framework checkout that is diagnosing it.\n */\n private publishLocalReadinessObservation(): void {\n const observationPath = join(\n this.companionContext.saasRoot,\n '.wildo-saas',\n 'runtime-signals',\n 'diagnostics',\n 'companion-readiness.json',\n );\n const directory = dirname(observationPath);\n const temporaryPath = `${observationPath}.tmp-${process.pid}-${Date.now()}`;\n try {\n mkdirSync(directory, { recursive: true, mode: 0o700 });\n chmodSync(directory, 0o700);\n writeFileSync(temporaryPath, `${JSON.stringify({\n kind: 'wildo.local-dev.companion-readiness-observation',\n schemaVersion: 1,\n producerKind: 'dev-companion',\n producerInstanceId: this.readinessObservationProducerInstanceId,\n producerPid: process.pid,\n appRoot: this.companionContext.saasRoot,\n status: 'READY',\n /*\n * A READY companion that never drained its terminalization outbox. Non-fatal by design, and\n * therefore invisible until it is published here — the drain's only previous surface was a\n * `console.warn` on a boot that then succeeded.\n */\n /*\n * What the ordered startup actually COST, and which stages missed their soft budget.\n *\n * A stage deadline used to report the stage and the budget it missed and nothing else, which made a stuck\n * companion undiagnosable: nobody could see whether one stage was pathological or every stage was near\n * its limit. `stagesOverSoftBudgetMs` is normally empty, so its presence alone is the warning.\n */\n httpRunning: this.httpServerService.isRunning(),\n updatedAt: new Date().toISOString(),\n }, null, 2)}\\n`, { encoding: 'utf8', mode: 0o600 });\n renameSync(temporaryPath, observationPath);\n chmodSync(observationPath, 0o600);\n } catch (error) {\n try {\n unlinkSync(temporaryPath);\n } catch {\n // The temporary file may not exist or may already have been renamed.\n }\n this.logger.warn('Could not publish the local companion readiness observation', {\n error: describeCaughtError(error),\n });\n }\n }\n\n private startLocalReadinessObservation(): void {\n this.publishLocalReadinessObservation();\n if (this.readinessObservationHeartbeat) {\n return;\n }\n this.readinessObservationHeartbeat = setInterval(() => {\n this.publishLocalReadinessObservation();\n }, 5_000);\n this.readinessObservationHeartbeat.unref();\n }\n\n /**\n * Bind every companion-owned long-lived resource to the engine's canonical\n * shutdown coordinator. HTTP closes in the stop phase so no new work enters;\n * Redis, Mongo, and observability then drain through the coordinator's LIFO\n * cleanup phase. Registration is idempotent because initialize can be called\n * more than once by defensive bootstraps.\n */\n private registerCompanionShutdownLifecycle(): void {\n if (this.shutdownLifecycleRegistered) {\n return;\n }\n this.shutdownLifecycleRegistered = true;\n\n this.workerShutdownManager.registerStopHandler(async () => {\n try {\n await this.runBoundedShutdownStep('http-server', () => this.httpServerService.shutdown());\n } finally {\n // Hygiene rather than a latch: the loop's timer is unref'd, so it can never be the reason the\n // process stays alive. Stopping it keeps a shutting-down companion from spawning a `db diff`.\n this.stopSchemaPlanFreshnessLoop?.();\n this.stopSchemaPlanFreshnessLoop = null;\n this.stopOwedActorReviewRecordRepairTick?.();\n this.stopOwedActorReviewRecordRepairTick = null;\n this.stopActorQuestionDeadlineSweep?.();\n this.stopActorQuestionDeadlineSweep = null;\n this.eventLoopStallMonitor?.stop();\n this.eventLoopStallMonitor = null;\n this.heapPressureMonitor?.stop();\n this.heapPressureMonitor = null;\n // The coding agent's background connectivity probe (#3236): unref'd too, and a stopping companion starts none.\n this.codingAgentDispatchService.stopBackgroundConnectivityProbe();\n this.publishLocalReadinessObservation();\n if (this.readinessObservationHeartbeat) {\n clearInterval(this.readinessObservationHeartbeat);\n this.readinessObservationHeartbeat = null;\n }\n }\n });\n this.workerShutdownManager.onShutdown(async () => this.runBoundedShutdownStep('mongodb', () => this.mongoDBService.disconnect()));\n this.workerShutdownManager.onShutdown(async () => this.runBoundedShutdownStep('redis', () => this.redisService.disconnect()));\n this.workerShutdownManager.registerSignalHandlers();\n }\n\n /** Keep one stuck dependency from consuming the supervisor's whole SIGTERM grace period. */\n private async runBoundedShutdownStep(component: string, operation: () => Promise<void>): Promise<void> {\n let timeout: NodeJS.Timeout | null = null;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(\n () => reject(new Error(`Companion ${component} shutdown exceeded ${COMPANION_SHUTDOWN_STEP_TIMEOUT_MS}ms.`)),\n COMPANION_SHUTDOWN_STEP_TIMEOUT_MS,\n );\n timeout.unref();\n });\n try {\n await Promise.race([Promise.resolve().then(operation), timeoutPromise]);\n } finally {\n if (timeout) {\n clearTimeout(timeout);\n }\n }\n }\n}\n"]}
|
|
@@ -20,8 +20,8 @@ declare const CompanionPlatformEnvSchema: z.ZodObject<{
|
|
|
20
20
|
REDIS_PORT: z.ZodCoercedNumber<unknown>;
|
|
21
21
|
REDIS_ADMIN_USER: z.ZodOptional<z.ZodString>;
|
|
22
22
|
REDIS_ADMIN_PASSWORD: z.ZodOptional<z.ZodString>;
|
|
23
|
-
RABBITMQ_HOST: z.ZodString
|
|
24
|
-
RABBITMQ_PORT: z.ZodCoercedNumber<unknown
|
|
23
|
+
RABBITMQ_HOST: z.ZodOptional<z.ZodString>;
|
|
24
|
+
RABBITMQ_PORT: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
|
|
25
25
|
RABBITMQ_ADMIN_USERNAME: z.ZodOptional<z.ZodString>;
|
|
26
26
|
RABBITMQ_ADMIN_PASSWORD: z.ZodOptional<z.ZodString>;
|
|
27
27
|
STORAGE_PROVIDER: z.ZodOptional<z.ZodString>;
|