@wildo-ai/wildo-cli 1.1.14 → 1.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/dist/src/commands/context/journey.command.d.ts.map +1 -1
  2. package/dist/src/commands/context/journey.command.js +12 -0
  3. package/dist/src/commands/context/journey.command.js.map +1 -1
  4. package/dist/src/commands/creation/drive.command.d.ts.map +1 -1
  5. package/dist/src/commands/creation/drive.command.js +2 -1
  6. package/dist/src/commands/creation/drive.command.js.map +1 -1
  7. package/dist/src/commands/generate/email-command.utils.d.ts +2 -0
  8. package/dist/src/commands/generate/email-command.utils.d.ts.map +1 -1
  9. package/dist/src/commands/generate/email-command.utils.js +5 -0
  10. package/dist/src/commands/generate/email-command.utils.js.map +1 -1
  11. package/dist/src/commands/init.command.d.ts.map +1 -1
  12. package/dist/src/commands/init.command.js +7 -2
  13. package/dist/src/commands/init.command.js.map +1 -1
  14. package/dist/src/commands/local/deregister.command.d.ts.map +1 -1
  15. package/dist/src/commands/local/deregister.command.js +4 -0
  16. package/dist/src/commands/local/deregister.command.js.map +1 -1
  17. package/dist/src/commands/local/dev.command.d.ts +50 -0
  18. package/dist/src/commands/local/dev.command.d.ts.map +1 -1
  19. package/dist/src/commands/local/dev.command.js +144 -1
  20. package/dist/src/commands/local/dev.command.js.map +1 -1
  21. package/dist/src/commands/local/jobs-command.utils.d.ts +24 -0
  22. package/dist/src/commands/local/jobs-command.utils.d.ts.map +1 -0
  23. package/dist/src/commands/local/jobs-command.utils.js +44 -0
  24. package/dist/src/commands/local/jobs-command.utils.js.map +1 -0
  25. package/dist/src/commands/local/jobs-run.command.d.ts +7 -0
  26. package/dist/src/commands/local/jobs-run.command.d.ts.map +1 -0
  27. package/dist/src/commands/local/jobs-run.command.js +92 -0
  28. package/dist/src/commands/local/jobs-run.command.js.map +1 -0
  29. package/dist/src/commands/local/jobs.command.d.ts +7 -0
  30. package/dist/src/commands/local/jobs.command.d.ts.map +1 -0
  31. package/dist/src/commands/local/jobs.command.js +59 -0
  32. package/dist/src/commands/local/jobs.command.js.map +1 -0
  33. package/dist/src/commands/local/tunnel.command.d.ts +84 -0
  34. package/dist/src/commands/local/tunnel.command.d.ts.map +1 -0
  35. package/dist/src/commands/local/tunnel.command.js +274 -0
  36. package/dist/src/commands/local/tunnel.command.js.map +1 -0
  37. package/dist/src/commands/providers/grant-export.command.d.ts +16 -0
  38. package/dist/src/commands/providers/grant-export.command.d.ts.map +1 -0
  39. package/dist/src/commands/providers/grant-export.command.js +78 -0
  40. package/dist/src/commands/providers/grant-export.command.js.map +1 -0
  41. package/dist/src/commands/providers/grant-import.command.d.ts +15 -0
  42. package/dist/src/commands/providers/grant-import.command.d.ts.map +1 -0
  43. package/dist/src/commands/providers/grant-import.command.js +78 -0
  44. package/dist/src/commands/providers/grant-import.command.js.map +1 -0
  45. package/dist/src/kernel/command-runner.d.ts.map +1 -1
  46. package/dist/src/kernel/command-runner.js +4 -6
  47. package/dist/src/kernel/command-runner.js.map +1 -1
  48. package/dist/src/kernel/hooks.d.ts.map +1 -1
  49. package/dist/src/kernel/hooks.js +2 -1
  50. package/dist/src/kernel/hooks.js.map +1 -1
  51. package/dist/src/kernel/json-document-output.d.ts +7 -0
  52. package/dist/src/kernel/json-document-output.d.ts.map +1 -1
  53. package/dist/src/kernel/json-document-output.js +8 -0
  54. package/dist/src/kernel/json-document-output.js.map +1 -1
  55. package/dist/src/kernel/types.d.ts +8 -0
  56. package/dist/src/kernel/types.d.ts.map +1 -1
  57. package/dist/src/kernel/types.js.map +1 -1
  58. package/dist/src/services/application/app-bootstrap.service.d.ts +65 -7
  59. package/dist/src/services/application/app-bootstrap.service.d.ts.map +1 -1
  60. package/dist/src/services/application/app-bootstrap.service.js +94 -15
  61. package/dist/src/services/application/app-bootstrap.service.js.map +1 -1
  62. package/dist/src/services/application/app-local-runtime-addresses.service.d.ts +1 -1
  63. package/dist/src/services/application/app-local-runtime-addresses.service.d.ts.map +1 -1
  64. package/dist/src/services/application/app-local-runtime-addresses.service.js.map +1 -1
  65. package/dist/src/services/application/app-runtime-targets.service.d.ts.map +1 -1
  66. package/dist/src/services/application/app-runtime-targets.service.js +16 -2
  67. package/dist/src/services/application/app-runtime-targets.service.js.map +1 -1
  68. package/dist/src/services/application/application-dependency-alignment.service.d.ts +20 -0
  69. package/dist/src/services/application/application-dependency-alignment.service.d.ts.map +1 -1
  70. package/dist/src/services/application/application-dependency-alignment.service.js +32 -2
  71. package/dist/src/services/application/application-dependency-alignment.service.js.map +1 -1
  72. package/dist/src/services/application/application-runtime-bootstrap.service.d.ts +13 -0
  73. package/dist/src/services/application/application-runtime-bootstrap.service.d.ts.map +1 -1
  74. package/dist/src/services/application/application-runtime-bootstrap.service.js +32 -0
  75. package/dist/src/services/application/application-runtime-bootstrap.service.js.map +1 -1
  76. package/dist/src/services/application/environment-provider-configurations.service.d.ts +7 -0
  77. package/dist/src/services/application/environment-provider-configurations.service.d.ts.map +1 -1
  78. package/dist/src/services/application/environment-provider-configurations.service.js +1 -1
  79. package/dist/src/services/application/environment-provider-configurations.service.js.map +1 -1
  80. package/dist/src/services/application/local-tunnel.service.d.ts +153 -0
  81. package/dist/src/services/application/local-tunnel.service.d.ts.map +1 -0
  82. package/dist/src/services/application/local-tunnel.service.js +295 -0
  83. package/dist/src/services/application/local-tunnel.service.js.map +1 -0
  84. package/dist/src/services/application/provider-runtime-sync.service.d.ts.map +1 -1
  85. package/dist/src/services/application/provider-runtime-sync.service.js +3 -0
  86. package/dist/src/services/application/provider-runtime-sync.service.js.map +1 -1
  87. package/dist/src/services/application/saas-skeleton.service.d.ts +7 -0
  88. package/dist/src/services/application/saas-skeleton.service.d.ts.map +1 -1
  89. package/dist/src/services/application/saas-skeleton.service.js +2 -0
  90. package/dist/src/services/application/saas-skeleton.service.js.map +1 -1
  91. package/dist/src/services/catalog/service-address-resolver.service.d.ts +7 -1
  92. package/dist/src/services/catalog/service-address-resolver.service.d.ts.map +1 -1
  93. package/dist/src/services/catalog/service-address-resolver.service.js +6 -3
  94. package/dist/src/services/catalog/service-address-resolver.service.js.map +1 -1
  95. package/dist/src/services/companion/companion-client.service.d.ts +17 -0
  96. package/dist/src/services/companion/companion-client.service.d.ts.map +1 -1
  97. package/dist/src/services/companion/companion-client.service.js +21 -0
  98. package/dist/src/services/companion/companion-client.service.js.map +1 -1
  99. package/dist/src/services/companion/creation-drive.service.d.ts +18 -0
  100. package/dist/src/services/companion/creation-drive.service.d.ts.map +1 -1
  101. package/dist/src/services/companion/creation-drive.service.js +70 -1
  102. package/dist/src/services/companion/creation-drive.service.js.map +1 -1
  103. package/dist/src/services/credentials/application-secrets.service.d.ts +6 -0
  104. package/dist/src/services/credentials/application-secrets.service.d.ts.map +1 -1
  105. package/dist/src/services/credentials/application-secrets.service.js +1 -1
  106. package/dist/src/services/credentials/application-secrets.service.js.map +1 -1
  107. package/dist/src/services/credentials/provider-env-vars.utils.d.ts.map +1 -1
  108. package/dist/src/services/credentials/provider-env-vars.utils.js +3 -1
  109. package/dist/src/services/credentials/provider-env-vars.utils.js.map +1 -1
  110. package/dist/src/services/credentials/secrets-writer.service.d.ts +11 -2
  111. package/dist/src/services/credentials/secrets-writer.service.d.ts.map +1 -1
  112. package/dist/src/services/credentials/secrets-writer.service.js +12 -3
  113. package/dist/src/services/credentials/secrets-writer.service.js.map +1 -1
  114. package/dist/src/services/deployment/ci-deploy-generator.service.d.ts.map +1 -1
  115. package/dist/src/services/deployment/ci-deploy-generator.service.js +3 -3
  116. package/dist/src/services/deployment/ci-deploy-generator.service.js.map +1 -1
  117. package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts +12 -3
  118. package/dist/src/services/deployment/docker/docker-compose-generator.service.d.ts.map +1 -1
  119. package/dist/src/services/deployment/docker/docker-compose-generator.service.js +40 -22
  120. package/dist/src/services/deployment/docker/docker-compose-generator.service.js.map +1 -1
  121. package/dist/src/services/deployment/framework-pod-network-membership.d.ts +6 -0
  122. package/dist/src/services/deployment/framework-pod-network-membership.d.ts.map +1 -1
  123. package/dist/src/services/deployment/framework-pod-network-membership.js +17 -3
  124. package/dist/src/services/deployment/framework-pod-network-membership.js.map +1 -1
  125. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.d.ts +4 -1
  126. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.d.ts.map +1 -1
  127. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.js +17 -7
  128. package/dist/src/services/deployment/k8s/k8s-manifest-generator.service.js.map +1 -1
  129. package/dist/src/services/deployment/k8s/k8s-manifest.schemas.d.ts +7 -0
  130. package/dist/src/services/deployment/k8s/k8s-manifest.schemas.d.ts.map +1 -1
  131. package/dist/src/services/deployment/k8s/k8s-manifest.schemas.js.map +1 -1
  132. package/dist/src/services/deployment/k8s/k8s-secrets-generator.service.d.ts.map +1 -1
  133. package/dist/src/services/deployment/k8s/k8s-secrets-generator.service.js +15 -9
  134. package/dist/src/services/deployment/k8s/k8s-secrets-generator.service.js.map +1 -1
  135. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.d.ts +43 -0
  136. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.d.ts.map +1 -0
  137. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.js +12 -0
  138. package/dist/src/services/deployment/k8s/kind-pod-host-gateway.js.map +1 -0
  139. package/dist/src/services/deployment/k8s/off-cluster-backing-services.d.ts +3 -1
  140. package/dist/src/services/deployment/k8s/off-cluster-backing-services.d.ts.map +1 -1
  141. package/dist/src/services/deployment/k8s/off-cluster-backing-services.js.map +1 -1
  142. package/dist/src/services/deployment/local-dev-late-workspace-members.service.d.ts +163 -0
  143. package/dist/src/services/deployment/local-dev-late-workspace-members.service.d.ts.map +1 -0
  144. package/dist/src/services/deployment/local-dev-late-workspace-members.service.js +356 -0
  145. package/dist/src/services/deployment/local-dev-late-workspace-members.service.js.map +1 -0
  146. package/dist/src/services/environment/authored-infra-config.utils.d.ts +13 -3
  147. package/dist/src/services/environment/authored-infra-config.utils.d.ts.map +1 -1
  148. package/dist/src/services/environment/authored-infra-config.utils.js +24 -4
  149. package/dist/src/services/environment/authored-infra-config.utils.js.map +1 -1
  150. package/dist/src/services/environment/container-host-gateway-listen-host.d.ts +6 -0
  151. package/dist/src/services/environment/container-host-gateway-listen-host.d.ts.map +1 -1
  152. package/dist/src/services/environment/container-host-gateway-listen-host.js +6 -0
  153. package/dist/src/services/environment/container-host-gateway-listen-host.js.map +1 -1
  154. package/dist/src/services/environment/env-configuration-generator.service.d.ts +12 -0
  155. package/dist/src/services/environment/env-configuration-generator.service.d.ts.map +1 -1
  156. package/dist/src/services/environment/env-configuration-generator.service.js +37 -5
  157. package/dist/src/services/environment/env-configuration-generator.service.js.map +1 -1
  158. package/dist/src/services/environment/env-vars-builder.service.d.ts +2 -1
  159. package/dist/src/services/environment/env-vars-builder.service.d.ts.map +1 -1
  160. package/dist/src/services/environment/env-vars-builder.service.js +47 -32
  161. package/dist/src/services/environment/env-vars-builder.service.js.map +1 -1
  162. package/dist/src/services/environment/environment-lifecycle.service.d.ts +7 -4
  163. package/dist/src/services/environment/environment-lifecycle.service.d.ts.map +1 -1
  164. package/dist/src/services/environment/environment-lifecycle.service.js +14 -18
  165. package/dist/src/services/environment/environment-lifecycle.service.js.map +1 -1
  166. package/dist/src/services/environment/environment-setup.service.d.ts.map +1 -1
  167. package/dist/src/services/environment/environment-setup.service.js +17 -6
  168. package/dist/src/services/environment/environment-setup.service.js.map +1 -1
  169. package/dist/src/services/environment/environment.service.d.ts +4 -3
  170. package/dist/src/services/environment/environment.service.d.ts.map +1 -1
  171. package/dist/src/services/environment/environment.service.js +0 -1
  172. package/dist/src/services/environment/environment.service.js.map +1 -1
  173. package/dist/src/services/framework/framework-docker-publish.service.d.ts +55 -15
  174. package/dist/src/services/framework/framework-docker-publish.service.d.ts.map +1 -1
  175. package/dist/src/services/framework/framework-docker-publish.service.js +115 -25
  176. package/dist/src/services/framework/framework-docker-publish.service.js.map +1 -1
  177. package/dist/src/services/framework/package-install.service.d.ts +7 -0
  178. package/dist/src/services/framework/package-install.service.d.ts.map +1 -1
  179. package/dist/src/services/framework/package-install.service.js +8 -1
  180. package/dist/src/services/framework/package-install.service.js.map +1 -1
  181. package/dist/src/services/registry/application-provider-connection.service.d.ts +16 -1
  182. package/dist/src/services/registry/application-provider-connection.service.d.ts.map +1 -1
  183. package/dist/src/services/registry/application-provider-connection.service.js +23 -0
  184. package/dist/src/services/registry/application-provider-connection.service.js.map +1 -1
  185. package/dist/src/services/registry/provider-grant-transfer.service.d.ts +48 -0
  186. package/dist/src/services/registry/provider-grant-transfer.service.d.ts.map +1 -0
  187. package/dist/src/services/registry/provider-grant-transfer.service.js +144 -0
  188. package/dist/src/services/registry/provider-grant-transfer.service.js.map +1 -0
  189. package/dist/src/services/registry/provider-module-scaffold.service.d.ts.map +1 -1
  190. package/dist/src/services/registry/provider-module-scaffold.service.js +10 -3
  191. package/dist/src/services/registry/provider-module-scaffold.service.js.map +1 -1
  192. package/dist/src/services/security/csp-sync.service.d.ts.map +1 -1
  193. package/dist/src/services/security/csp-sync.service.js +21 -2
  194. package/dist/src/services/security/csp-sync.service.js.map +1 -1
  195. package/dist/tsconfig.build.tsbuildinfo +1 -1
  196. package/package.json +19 -19
  197. package/templates/infra/docker-compose/docker-compose.wildo-platform.yml.hbs +16 -7
  198. package/templates/infra/k8s/platform/platform-crontabs-batches-manager/deployment.yaml.hbs +13 -0
  199. package/templates/saas/i18n/email/system/remote-agent-task-updated/labels.en.ts +11 -0
  200. package/templates/saas/i18n/email/system/remote-agent-task-updated/template.tsx +56 -0
  201. package/templates/saas/i18n/engine/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.en.ts +61 -0
  202. package/templates/saas/i18n/engine/components/APP_LAYOUTS_AGENT_ACTIVITY_SETTINGS.fr.ts +61 -0
  203. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/docusaurus.config.ts.hbs +5 -4
  204. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/package.json.hbs +1 -1
  205. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/scripts/substitute-api-origin.mjs +97 -32
  206. package/templates/saas/scenarios/add-technical-doc/files/technical-doc/src/plugins/api-reference-pages.ts +7 -6
  207. package/templates/saas/skeleton/.wildo-saas/wildo-dev-companion/scripts/dev-supervised.sh +18 -4
  208. package/templates/saas/skeleton/frontend/nginx-config/default.conf.hbs +1 -1
  209. package/templates/saas/skeleton/frontend/src/generated/csp.generated.json.hbs +4 -4
  210. package/templates/saas/skeleton/infrastructure/local/wildo.infra.local.config.ts.hbs +2 -0
  211. package/wildo-framework.info.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"app-bootstrap.service.js","sourceRoot":"","sources":["../../../../src/services/application/app-bootstrap.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,MAAM,0DAA0D,CAAC;AAC1G,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE3D,OAAO,EAAsB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC5E,OAAO,EACL,oCAAoC,EACpC,gCAAgC,EAChC,uBAAuB,EACvB,eAAe,EACf,gCAAgC,EAChC,qCAAqC,EAIrC,+BAA+B,EAE/B,gCAAgC,EAChC,uCAAuC,EACvC,wCAAwC,EACxC,0BAA0B,EAC1B,6BAA6B,EAC7B,2CAA2C,EAC3C,oCAAoC,EACpC,0CAA0C,EAC1C,wCAAwC,EACxC,yCAAyC,EACzC,uCAAuC,EAGvC,0CAA0C,EAC1C,2CAA2C,EAC3C,kCAAkC,EAIlC,0CAA0C,EAC1C,iDAAiD,EACjD,gDAAgD,EAChD,0CAA0C,EAC1C,gDAAgD,EAChD,mDAAmD,EACnD,wCAAwC,EAKxC,4BAA4B,EAC5B,6BAA6B,EAG7B,wBAAwB,EACx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-cli/services/environment/platform-runtime.schemas';\nimport { existsSync, readFileSync } from 'fs';\nimport { isAbsolute, join, relative, resolve } from 'path';\nimport type { AppConfiguration_BackendAuthored } from '@wildo-ai/saas-backend-lib';\nimport { RuntimeEnvironment, WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport {\n buildAppBootstrapCredentialsResponse,\n APPS_MANAGER_ADMIN_SECRET_HEADER,\n APPS_MANAGER_API_PREFIX,\n AppFrontendType,\n PlatformDocumentationSiteEnvKeys,\n ApplicationCreationVerificationEnvKey,\n type AdminAppManagedDeclaration,\n type AppBootstrapCredentials,\n type AppBootstrapFirstAdminSeed,\n AdminAppInitializeRequestSchema,\n type ApplicationBackingServiceAddressing,\n AdminAppInitializeResponseSchema,\n AdminAppReapplyDeclarationRequestSchema,\n AdminAppReapplyDeclarationResponseSchema,\n buildRegistryKeyRevokePath,\n buildAdminKeyringRotationPath,\n buildAdminApplicationSigningKeyRotationPath,\n buildAdminApplicationSigningKeysPath,\n buildAdminApplicationSigningKeyPromotePath,\n buildAdminApplicationSigningKeyStagePath,\n ApplicationSigningKeyPromoteRequestSchema,\n ApplicationSigningKeyStageRequestSchema,\n type ApplicationSigningKeyPromoteRequest,\n type ApplicationSigningKeyStageRequest,\n ApplicationSigningKeyRotationRequestSchema,\n ApplicationSigningKeyRotationResponseSchema,\n ApplicationSigningKeysStatusSchema,\n type ApplicationSigningKeyRotationRequest,\n type ApplicationSigningKeyRotationResponse,\n type ApplicationSigningKeysStatus,\n buildAdminApplicationLegacyEnvelopeKeyPath,\n buildAdminApplicationLegacyEnvelopeKeyRestorePath,\n buildAdminApplicationLegacyEnvelopeKeyRetirePath,\n ApplicationLegacyEnvelopeKeyResponseSchema,\n ApplicationLegacyEnvelopeKeyRestoreRequestSchema,\n ApplicationLegacyEnvelopeKeyRetirementRequestSchema,\n ApplicationLegacyEnvelopeKeyStatusSchema,\n type ApplicationLegacyEnvelopeKeyResponse,\n type ApplicationLegacyEnvelopeKeyRestoreRequest,\n type ApplicationLegacyEnvelopeKeyRetirementRequest,\n type ApplicationLegacyEnvelopeKeyStatus,\n KeyringRotationRequestSchema,\n KeyringRotationResponseSchema,\n type KeyringRotationRequest,\n type KeyringStatus,\n REGISTRY_KEYS_ADMIN_PATH,\n RegistryKeyListResponseSchema,\n RegistryKeyMintRequestSchema,\n RegistryKeyMintResponseSchema,\n RegistryKeyRevokeRequestSchema,\n type RegistryKeyMintRequest,\n type RegistryKeyListResponse,\n type RegistryKeyMintResponse,\n type AdminAppReapplyDeclarationResponse,\n AppBootstrapCredentialsResponseSchema,\n buildAdminInitializeApplicationPath,\n buildAdminReapplyDeclarationPath,\n buildAdminDeregisterApplicationPath,\n buildAdminApplicationResiduePath,\n buildAdminRestoreApplicationPath,\n buildAppBootstrapCredentialsPath,\n buildLocalhostApplicationRuntimeEndpoints,\n selectPrimaryBackendService,\n buildK8sApplicationRuntimeEndpoints,\n buildComposeApplicationRuntimeEndpoints,\n buildK8sApplicationIngressRoutes,\n buildK8sInternalUrl,\n APP_RUNTIME_SUBDIR_NAMES,\n type K8sIngressRoute,\n loadConfig,\n resolveAppLayout,\n WildoDeploymentRuntime,\n WildoLocationType,\n WORKSPACE_HOME_NAMES,\n WORKER_CONFIG_FILENAME,\n MINION_CONFIG_FILENAME,\n WildoWorkerConfigSchema,\n WildoMinionConfigSchema,\n ApplicationRuntimePrincipalKind,\n buildMinionRedisKeyPrefix,\n registerMinionLocalProviders,\n buildRuntimePrincipalKey,\n DEVELOPMENT_COMPANION_PRINCIPAL,\n enumerateRuntimePrincipalsWithBootstrapSecrets,\n runtimeEnvironmentHostsDevelopmentCompanion,\n type ApplicationRuntimePrincipal,\n DatabaseEngine,\n resolveApplicationDatabaseEngine,\n AppDatabaseSeedingPhase,\n AppDatabaseSeedingOutcome,\n type BackingServiceKind,\n} from '@wildo-ai/platform-config-lib';\nimport { buildWorkerInternalUrl, buildWorkerLocalUrl } from '@wildo-ai/platform-core-shared';\nimport type { PlatformEnvSecretsJson } from '~wildo-cli/services/credentials/credentials.schemas';\nimport type { PlatformEnvConfigJson } from '~wildo-cli/services/credentials/credentials.schemas';\nimport type { PlatformEnvironmentConfiguration } from '~wildo-cli/services/environment/environment.schemas';\nimport { resolveApplicationBackingServiceAddressing } from '~wildo-cli/services/environment/application-backing-service-addressing.utils';\nimport type {\n ApplicationBackendEnvTarget,\n CompanionPlatformEnvTarget,\n ApplicationFrontendEnvExampleTarget,\n ApplicationOperatorEnvTarget,\n ApplicationWorkerEnvTarget,\n ApplicationMinionEnvTarget,\n K8sPodPort,\n} from '~wildo-cli/services/environment/env-configuration-generator.service';\nimport { ApplicationOperatorEnvFileDisposition } from '~wildo-cli/services/environment/env-configuration-generator.service';\nimport { AddressPerspective, ServiceAddressResolver } from '~wildo-cli/services/catalog/service-address-resolver.service';\nimport { buildAppsManagerDiagnosticMessage } from '~wildo-cli/services/deployment/apps-manager-diagnostics.service';\nimport { ErrorUtils } from '~wildo-cli/infrastructure/errors/error.utils';\nimport { EnvironmentUtils } from '~wildo-cli/services/environment/environment.service';\nimport { AppRuntimeTargetsService, type ResolvedAppRuntimeTarget } from './app-runtime-targets.service';\nimport { applyAppSchemaMigrations, resolveAppMigrationsDirectory } from './app-schema-bootstrap.service';\n\n\n/**\n * Budget for a LIGHT apps-manager call — a read, or an idempotent config re-source.\n *\n * Short on purpose: for an operation that should answer in well under a second, a short budget is\n * what gives the timeout its diagnostic value. It says \"apps-manager is not answering\", and it says\n * it quickly.\n */\nconst APPS_MANAGER_TIMEOUT_MS = 15_000;\n\n/**\n * Budget for `POST /admin/apps/:appSlug/initialize` — a HEAVY, long-running provisioning call.\n *\n * ## Why this is not the same number as above\n *\n * Both budgets used to be one constant, and that conflated two unrelated questions: \"is apps-manager\n * unresponsive?\" and \"is apps-manager doing a long job it is supposed to be doing?\". Initialization\n * provisions the application database and its user, mints runtime-principal credentials, reconciles\n * ACLs, connects, and constructs the application's ENTIRE repository registry — ensuring every\n * declared index on every resource.\n *\n * Measured on Wonder Todos, 2026-08-19, on a machine where nothing was wrong: **12.2s** and **21.5s**\n * for the same call on two runs, against an application database holding 95 collections and 514\n * indexes. Both exceeded 15s, so `wildo local dev` aborted the whole session — and did so at the\n * point where the CLI kills the process tree, which made a healthy platform look like a failed one.\n *\n * Note the cost is NOT first-run index CREATION: those 514 indexes already existed. Ensuring them is\n * re-paid on every initialize, so the budget has to cover the steady state, not a cold start.\n *\n * ## Why raising the SHARED constant would have been the wrong fix\n *\n * It would have bought this call its headroom by taking detection value away from the two light\n * calls, which would then need the full budget to report an apps-manager that is simply dead.\n * A budget belongs to an operation, not to a client.\n *\n * The value is deliberately generous rather than tuned to the measurement: the work scales with the\n * application's resource count, and a larger app, a cold page cache or a loaded machine can be\n * several times slower without anything being wrong. It is still bounded, so a genuinely hung\n * apps-manager is reported well inside an interactive session.\n */\nconst APPS_MANAGER_INITIALIZE_TIMEOUT_MS = 180_000;\n\n/**\n * Per-OPERATION budget for withdrawing an application and restoring it (#1307).\n *\n * Both now act on every backing server once per runtime principal — delete or re-create a Redis ACL user, a\n * broker user, a MongoDB user and role (on Atlas, several Admin API round trips each) and a PostgreSQL role — so the\n * 15s liveness budget could expire while apps-manager was still revoking. The operator would then see a timeout\n * instead of the list of credentials still live, and the work would carry on unobserved. Same reasoning as\n * {@link APPS_MANAGER_INITIALIZE_TIMEOUT_MS}: a budget belongs to an operation, not to a client. Shorter than\n * initialization because nothing here builds a repository registry.\n */\nconst APPS_MANAGER_CREDENTIAL_LIFECYCLE_TIMEOUT_MS = 120_000;\n\n/**\n * `waitForPlatformServicesReady` gates entry into registered-app bootstrap on\n * apps-manager answering `/health/ready`, but that check and this request are\n * two separate round-trips: apps-manager can pass readiness and then crash\n * (observed 2026-08-06: an uncaught exception from an unrelated OTel\n * telemetry batch-flush timer killed apps-manager seconds after it reported\n * ready) before the registration POST lands, producing an immediate\n * connection-refused \"fetch failed\" that aborted the whole `wildo local dev`\n * session. `platform-lifecycle.service.ts`'s runtime supervisor auto-respawns\n * a crashed platform service within seconds, so a bounded reconnect-wait here\n * — NOT a soft-success, still fails hard on HTTP error responses and after\n * this budget is exhausted — turns a transient crash/respawn window into a\n * short, silent retry instead of a hard command failure.\n */\nconst APPS_MANAGER_RECONNECT_ATTEMPTS = 2;\nconst APPS_MANAGER_RECONNECT_WAIT_MS = 30_000;\nconst APPS_MANAGER_RECONNECT_POLL_INTERVAL_MS = 1_000;\n\n/**\n * Has apps-manager answered AT ALL during this process?\n *\n * The reconnect window above is for a crash/RESPAWN — its own contract says apps-manager \"can pass\n * readiness and then crash\". Riding that out presupposes it was up. When it was never up there is\n * nothing to respawn, and waiting only postpones a conclusion the first `ECONNREFUSED` already\n * reached.\n *\n * Measured 2026-08-28: `wildo config sync` against a deliberately stopped platform took ~3.5\n * minutes, of which ~120 seconds was this wait — `prepareApplicationEnvTargets` is reached by four\n * target builders, and each burned the full 30-second deadline before giving up. The command then\n * degraded to `reconstructBootstrapCredentialsOffline` exactly as designed, so the two minutes\n * bought nothing: the offline path was always going to be taken. Running `config sync` with the\n * platform down is not an error state — it is how an operator regenerates env files between\n * sessions.\n *\n * Process-scoped rather than per-call, because the point is whether THIS run ever established that\n * a platform is there. A stale value cannot outlive the command.\n */\nlet appsManagerAnsweredThisRun = false;\n\n/**\n * Record that apps-manager has been OBSERVED reachable in this process.\n *\n * Called by every successful fetch here and by `waitForServiceReady` in `platform-lifecycle.service.ts`\n * whenever the service it proved ready is apps-manager — so BOTH readiness barriers\n * (`waitForAppsManagerReady` and the `waitForPlatformServicesReady` that `wildo local dev` uses)\n * record it. The readiness barrier is the reason this is exported rather than private. The reconnect window exists for the\n * gap that barrier itself documents — apps-manager \"can pass readiness and then crash\" before the\n * registration POST lands — so the very case the retry is FOR is one where the only proof the\n * platform was up came from a probe that never went through `fetchWithReconnect`. Keying the skip\n * solely on this module's own successes would therefore have removed the retry from the one window\n * it was written for, and the pinned crash/respawn test caught exactly that.\n */\nexport function markAppsManagerObservedReachable(): void {\n appsManagerAnsweredThisRun = true;\n}\n\n/**\n * Why a deploy-artifact build could not reach a usable apps-manager (issue #279).\n *\n * A closed vocabulary with a named home, because the two REACHABLE-but-unusable cases mean\n * opposite things to a creator and the old code could tell neither: it reported both as\n * \"Failed to prepare application deploy artifacts: … Check PLATFORM_ADMIN_SECRET\", which is the\n * wrong remedy for both.\n */\nexport enum AppsManagerUnavailableReason {\n /** Nothing answered: no platform is running for this application yet — the fresh-creator case. */\n PLATFORM_NOT_RUNNING = 'PLATFORM_NOT_RUNNING',\n /**\n * Something answered and refused our credentials. On a shared development host this is very\n * rarely a wrong secret: it is ANOTHER application's platform occupying the port.\n */\n PLATFORM_NOT_OURS = 'PLATFORM_NOT_OURS',\n}\n\n/**\n * Classify a deploy-artifact failure, or `null` when it is neither of the known benign shapes.\n *\n * `null` is the important return: a genuine defect must keep failing the command. Only the two\n * cases a first-time creator legitimately hits are skippable, and they are skippable because the\n * artifacts that step produces are CI deploy inputs under `.wildo-saas/deploy/` — nothing\n * `wildo local up` needs, which is why the phase's other outputs (compose, env files, provider\n * runtime) are complete and correct without them.\n */\nexport function classifyAppsManagerUnavailable(error: unknown): AppsManagerUnavailableReason | null {\n const message = error instanceof Error ? error.message : String(error ?? '');\n // 401/403 — `requestJson` names this exactly, and it is the only place that phrasing is produced.\n if (message.includes('rejected bootstrap authentication')) return AppsManagerUnavailableReason.PLATFORM_NOT_OURS;\n\n // Connection-shaped failures. `fetch` wraps the cause, so the code can sit one or two levels down.\n const codes: string[] = [];\n let cursor: unknown = error;\n for (let depth = 0; depth < 4 && cursor instanceof Error; depth += 1) {\n const code = (cursor as NodeJS.ErrnoException).code;\n if (typeof code === 'string') codes.push(code);\n if ((cursor as Error).name) codes.push((cursor as Error).name);\n cursor = (cursor as { cause?: unknown }).cause;\n }\n const connectionShaped = ['ECONNREFUSED', 'ENOTFOUND', 'ECONNRESET', 'EHOSTUNREACH', 'ETIMEDOUT', 'AbortError', 'TimeoutError'];\n if (codes.some((code) => connectionShaped.includes(code))) return AppsManagerUnavailableReason.PLATFORM_NOT_RUNNING;\n if (/fetch failed|ECONNREFUSED|timed? out|was aborted/i.test(message)) return AppsManagerUnavailableReason.PLATFORM_NOT_RUNNING;\n\n return null;\n}\n\n/**\n * Progress for a wait a human is sitting through. stderr, not stdout: callers parse stdout, and a\n * silent multi-second stall is exactly what made this cost so long to explain.\n */\nfunction reportAppsManagerWait(message: string): void {\n process.stderr.write(` ${message}\\n`);\n}\n\n/**\n * Coerce a service key (e.g. `backendApi`) into a K8s-valid port name:\n * lowercase, only `[a-z0-9-]`, no leading/trailing `-`, ≤15 chars (the\n * IANA/K8s `IS_DNS1123_LABEL`-for-ports limit). `backendApi` → `backend-api`.\n * Empty/degenerate input falls back to `port`.\n */\nfunction toK8sPortName(raw: string): string {\n const kebab = raw\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n const trimmed = kebab.slice(0, 15).replace(/-+$/g, '');\n if (trimmed.length === 0) return 'port';\n // K8s port names are IANA_SVC_NAME — they MUST contain at least one letter.\n // An all-numeric service key (e.g. '123') would otherwise emit an invalid\n // port name that kubectl rejects; prefix it to guarantee an alpha char.\n if (!/[a-z]/.test(trimmed)) return `p-${trimmed}`.slice(0, 15);\n return trimmed;\n}\n\nfunction buildLocalRuntimeEndpoint(url: string): { publicUrl: string; internalUrl: string } {\n return {\n publicUrl: url,\n internalUrl: url,\n };\n}\n\nfunction resolveRuntimeEnvironment(\n env: PlatformEnvironmentConfiguration,\n config: PlatformEnvConfigJson | null,\n): RuntimeEnvironment {\n if (config?.runtimeEnvironment) {\n return config.runtimeEnvironment;\n }\n\n if (env.runtimeEnvironment) {\n return env.runtimeEnvironment;\n }\n\n throw new Error(\n `Environment '${env.name}' is missing explicit runtime semantics. Set runtimeEnvironment in config.json or in the environment registry before bootstrapping applications.`,\n );\n}\n\nasync function readErrorBody(response: Response): Promise<string> {\n try {\n const body = await response.text();\n return body.trim();\n } catch {\n return '';\n }\n}\n\nexport interface RegisteredApplicationEnvTargetInput {\n env: PlatformEnvironmentConfiguration;\n credentials: PlatformEnvSecretsJson;\n saasRoot: string;\n config?: PlatformEnvConfigJson | null;\n requestedAppSlug?: string | undefined;\n}\n\n/** One authoritative application-registration/credential snapshot used by every runtime projection. */\n/**\n * What one registration call (`POST /admin/apps/:slug/initialize`) reported.\n *\n * Both fields are `undefined` when apps-manager predates them — \"not reported\", never \"nothing\n * happened\" — which is why neither is defaulted here.\n */\nexport interface ApplicationRegistrationOutcome {\n /** What provisioning did about the application's own bootstrap rows. */\n appDatabaseSeeding: AppDatabaseSeedingOutcome | undefined;\n /** The declaration slices this registration applied to the stored config. */\n declarationConvergedFields: string[] | undefined;\n}\n\nexport interface PreparedApplicationEnvTargets {\n runtimeTarget: ResolvedAppRuntimeTarget;\n bootstrapCredentials: AppBootstrapCredentials;\n /**\n * The declaration slices THIS run's registration applied to the stored config (both provisioning\n * phases, de-duplicated). `undefined` when no registration reported it: a degraded run (which never\n * registered) or an apps-manager predating the field. Lets `wildo local dev` name the edit it applied.\n */\n declarationConvergedFields?: string[] | undefined;\n /**\n * True when apps-manager was UNREACHABLE and the credentials were reconstructed\n * from material already on disk (Step: degraded env generation).\n *\n * Callers MUST surface this. A `.env` that looks current but was written without\n * consulting the control plane is the same \"correct and believed otherwise\"\n * failure as a silent partial sync, pointing the other way — and the one thing a\n * degraded run cannot know is whether apps-manager holds material the runtime\n * does not yet have.\n */\n degraded?: boolean;\n /**\n * Principals that could NOT be regenerated offline, each naming itself and the\n * `.env` it expected. Non-empty only in degraded mode.\n *\n * These are OMITTED from `runtimePrincipalCredentials` rather than faked, so\n * `requireRuntimePrincipalCredentials` still refuses to substitute the\n * application backend's identity for them. The caller reports them; their\n * existing `.env` files are left untouched.\n */\n unresolvedPrincipals?: string[];\n runtimeEndpoints: Record<string, { publicUrl: string; internalUrl: string }>;\n /**\n * The environment resolved during preparation, carried so per-runtime\n * credential fetches reuse it instead of re-deriving.\n *\n * Re-deriving imposed a NEW requirement on callers that construct a target\n * without a fully-populated env — `resolveRuntimeEnvironment` throws rather\n * than defaulting — and a second derivation could in principle disagree with\n * the first, which would fetch a different environment's credentials.\n */\n runtimeEnvironment: RuntimeEnvironment;\n /**\n * Each declared minion's and worker's OWN bootstrap credentials, keyed by\n * `buildRuntimePrincipalKey` (Step 1 / F11).\n *\n * Populated HERE rather than fetched inside the target builders for two\n * reasons. It keeps preparation the single credential-fetch phase — the\n * builders stay pure and a caller that supplies `prepared` needs no network.\n * And it makes the field REQUIRED, so a hand-constructed `prepared` has to\n * state what each runtime holds; an optional map would invite a fallback to\n * the application backend's credentials, which is precisely the collapse this\n * step removes.\n *\n * The application backend is NOT in the map — its credentials are\n * `bootstrapCredentials`.\n */\n runtimePrincipalCredentials: Record<string, AppBootstrapCredentials>;\n}\n\nexport interface ApplicationEnvProjectionInput extends RegisteredApplicationEnvTargetInput {\n /** Supplied by the coordinator so every target family is derived from one logical bootstrap generation. */\n prepared?: PreparedApplicationEnvTargets;\n}\n\n/** The residue probe's wire shape (#1556). `null` everywhere means \"could not ask\", never \"none\". */\nexport interface ApplicationResidueResponse {\n success: boolean;\n appSlug: string;\n applicationId: string | null;\n status: string;\n deregisteredAt: string | null;\n schedule: {\n scheduledForApplication: number | null;\n platformScheduledTotal: number | null;\n schedulerRunning: boolean | null;\n unavailableReason: string | null;\n };\n broker: {\n vhost: string | null;\n vhostExists: boolean | null;\n queueCount: number | null;\n queuedMessages: number | null;\n unavailableReason: string | null;\n };\n notInspected: string[];\n}\n\n/**\n * One principal's credential on one backing service, as apps-manager reports it (#1307). `service` is absent\n * when the entry names a whole principal — a minion re-minted by the reconcile, or one it could not reach.\n */\nexport interface ApplicationCredentialReportEntry {\n principalKey: string;\n service?: BackingServiceKind;\n}\n\n/** `POST /admin/apps/:appSlug/deregister` — the withdrawal and every credential it revoked. */\nexport interface ApplicationDeregistrationResponse {\n success: boolean;\n appSlug: string;\n applicationId: string;\n alreadyDeregistered: boolean;\n withdrawnJobs: number;\n deletedExecutions: number;\n revokedCredentials: ApplicationCredentialReportEntry[];\n}\n\n/** `POST /admin/apps/:appSlug/restore` — the restore and every credential it re-minted. */\nexport interface ApplicationRestoreResponse {\n success: boolean;\n appSlug: string;\n alreadyActive: boolean;\n ensuredCredentials: ApplicationCredentialReportEntry[];\n}\n\nexport class AppBootstrapService {\n /**\n * Service keys (`config.services.<key>`) of the app's frontends that are\n * CDN-served in this environment — authored `cdn?[key].enabled === true` in\n * `wildo.infra.<env>.config.ts`.\n *\n * A CDN-served frontend is served OFF-CLUSTER (its public host resolves via\n * DNS to a CDN edge fronting an object-storage bucket), so it is dropped from\n * BOTH the per-frontend nginx Deployment/Service\n * ({@link buildApplicationFrontendDeployTargets}) AND the ingress / compose\n * route ({@link buildApplicationIngressRoutes}). It is deliberately KEPT in\n * {@link buildRuntimeEndpoints} so `runtime.endPoints.publicUrl` still\n * advertises `<serviceHost>.<publicDomain>` — the browser gets the same URL,\n * it just resolves to the CDN. This advertised-but-not-ingress-routed\n * asymmetry IS the CDN opt-in: the coherence invariant relaxes from \"every\n * advertised host is routed by the ingress\" to \"…routed by the ingress OR\n * served by a CDN\". Maintained by construction here (ingress/deploy frontends\n * = all frontends − these keys; endpoints = all frontends).\n *\n * Keys on `enabled === true`, NOT mere presence, so an authored-but-disabled\n * entry falls back to normal nginx-pod serving (never silently drops a route).\n */\n private static cdnFrontendKeys(env: PlatformEnvironmentConfiguration): ReadonlySet<string> {\n return new Set(\n Object.entries(env.cdn ?? {})\n .filter(([, cdnConfig]) => cdnConfig.enabled)\n .map(([serviceKey]) => serviceKey),\n );\n }\n\n private static buildRuntimeEndpoints(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): Record<string, { publicUrl: string; internalUrl: string }> {\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n const primaryBackendPort = primaryBackend?.defaultPort;\n // Public frontends with the endpoints map key (`serviceName`) DECOUPLED from\n // the serviceHosts resolution key (`.key` = `config.services.<key>`). Keying\n // hosts on `serviceName` silently ignores authored `serviceHosts` (the\n // serviceName `wonder-todos-app` misses the authored `app` entry) and\n // diverges from the apps-manager ingress. See the domain plan.\n const publicFrontends = runtimeTarget.frontendServices.flatMap((frontend) =>\n frontend.defaultPort\n ? [{ serviceName: frontend.serviceName, serviceKey: frontend.key, port: frontend.defaultPort }]\n : [],\n );\n const frontendApplicationPorts = Object.fromEntries(\n publicFrontends.map((frontend) => [frontend.serviceName, frontend.port]),\n );\n const websiteFrontend = runtimeTarget.frontendServices.find(\n (frontend) => frontend.frontendType === AppFrontendType.STATIC_WEBSITE,\n );\n const docsFrontend = runtimeTarget.frontendServices.find(\n (frontend) => frontend.frontendType === AppFrontendType.TECH_DOC,\n );\n\n // Remote Kubernetes: serviceHosts-driven public subdomains of the operator's\n // OWN publicDomain (greenfield — no `{svc}-{slug}-{env}` fan-out); internal\n // URLs are the app's cluster-DNS Service. Local dev + compose stay on\n // localhost.\n const namespace = env.kubernetes?.namespace;\n if (\n env.runtime === WildoDeploymentRuntime.KUBERNETES &&\n env.locationType === WildoLocationType.REMOTE &&\n namespace\n ) {\n const runtimeEndpoints = buildK8sApplicationRuntimeEndpoints({\n publicDomain: env.publicDomain,\n namespace,\n serviceHosts: env.serviceHosts,\n appServiceName: runtimeTarget.appSlug,\n frontends: publicFrontends,\n websiteServiceKey: websiteFrontend?.key,\n technicalDocumentationServiceKey: docsFrontend?.key,\n mainBackendApiServiceKey: primaryBackend?.key,\n mainBackendApiPort: primaryBackendPort,\n });\n // Secondary backends ride the same app Service on their own port; the\n // dev companion is a local-only concept (omitted remotely).\n for (const backendService of runtimeTarget.backendServices) {\n if (!backendService.defaultPort) {\n continue;\n }\n const url = buildK8sInternalUrl(runtimeTarget.appSlug, backendService.defaultPort, namespace);\n runtimeEndpoints[backendService.serviceName] = { publicUrl: url, internalUrl: url };\n }\n return runtimeEndpoints;\n }\n\n // Remote Docker Compose: SAME serviceHosts-driven public subdomains as k8s\n // (so the Traefik ingress routes and `runtime.endPoints.publicUrl` agree —\n // the CORS invariant holds for compose too); internal URLs are the app\n // container's own name on the shared compose network. Must NOT fall through\n // to the localhost branch below, which would advertise localhost topology\n // for a remotely-served app.\n if (env.runtime === WildoDeploymentRuntime.DOCKER_COMPOSE && env.locationType === WildoLocationType.REMOTE) {\n const runtimeEndpoints = buildComposeApplicationRuntimeEndpoints({\n publicDomain: env.publicDomain,\n serviceHosts: env.serviceHosts,\n appServiceName: runtimeTarget.appSlug,\n frontends: publicFrontends,\n websiteServiceKey: websiteFrontend?.key,\n technicalDocumentationServiceKey: docsFrontend?.key,\n mainBackendApiServiceKey: primaryBackend?.key,\n mainBackendApiPort: primaryBackendPort,\n });\n // Secondary backends reachable at their own port on the app container\n // (`http://<appSlug>:<port>` on the shared compose network). No dev\n // companion remotely.\n for (const backendService of runtimeTarget.backendServices) {\n if (!backendService.defaultPort) {\n continue;\n }\n const url = `http://${runtimeTarget.appSlug}:${backendService.defaultPort}`;\n runtimeEndpoints[backendService.serviceName] = { publicUrl: url, internalUrl: url };\n }\n return runtimeEndpoints;\n }\n\n const runtimeEndpoints = buildLocalhostApplicationRuntimeEndpoints({\n mainBackendApiPort: primaryBackendPort,\n frontendApplicationPorts,\n websitePort: websiteFrontend?.defaultPort,\n });\n for (const backendService of runtimeTarget.backendServices) {\n if (!backendService.defaultPort) {\n continue;\n }\n\n runtimeEndpoints[backendService.serviceName] = buildLocalRuntimeEndpoint(\n `http://localhost:${backendService.defaultPort}`,\n );\n }\n if (runtimeTarget.localServiceAddresses?.devCompanion?.url) {\n runtimeEndpoints[devCompanionRuntimeEndpointKey(runtimeTarget.appSlug)] = buildLocalRuntimeEndpoint(\n runtimeTarget.localServiceAddresses.devCompanion.url,\n );\n }\n\n return runtimeEndpoints;\n }\n\n /**\n * serviceHosts-driven ingress routes for the app's public services — the\n * per-app deploy context shared by the k8s ingress + the compose Traefik lane\n * (`buildK8sApplicationIngressRoutes`, runtime-agnostic host→port). Remote\n * only; local has no reverse proxy. Coherent with the runtime endpoints\n * (same resolver + topology).\n */\n private static buildApplicationIngressRoutes(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): K8sIngressRoute[] {\n if (env.locationType !== WildoLocationType.REMOTE) {\n return [];\n }\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n // Host resolution keys on `.key` (config.services key), NOT serviceName —\n // matches the runtime endpoints + the operator's authored serviceHosts.\n // CDN-served frontends are EXCLUDED: their public host is served off-cluster\n // by the CDN, so no ingress rule (k8s) / Traefik router (compose) is emitted\n // for them — while they stay in `buildRuntimeEndpoints` (advertised host\n // preserved). See {@link cdnFrontendKeys}.\n const cdnKeys = AppBootstrapService.cdnFrontendKeys(env);\n const publicFrontends = runtimeTarget.frontendServices.flatMap((frontend) =>\n frontend.defaultPort && !cdnKeys.has(frontend.key)\n ? [{ serviceName: frontend.serviceName, serviceKey: frontend.key, port: frontend.defaultPort }]\n : [],\n );\n return buildK8sApplicationIngressRoutes({\n publicDomain: env.publicDomain,\n serviceHosts: env.serviceHosts,\n frontends: publicFrontends,\n mainBackendApiServiceKey: primaryBackend?.key,\n // Per-service model: the api host routes to the backend's OWN k8s Service\n // (its serviceName), not a shared app Service.\n mainBackendApiServiceName: primaryBackend?.serviceName,\n mainBackendApiPort: primaryBackend?.defaultPort,\n });\n }\n\n /**\n * Derive the BACKEND pod's container/Service ports (per-service deploy model),\n * per-app from the authored `services.<backendKey>.defaultPort`:\n * - the primary backend on `mainBackendApiPort` — the ONE port its process binds.\n * Frontends are NOT here — each is its own nginx Deployment/Service (see\n * `buildApplicationFrontendDeployTargets`). `healthPort` is that same port, the\n * listener serving `/health` and `/health/ready`, and drives the k8s probes. It\n * was `mainBackendApiPort - 1`, a declared \"health sibling\" no backend process\n * binds, so every probe failed (#1760); the four siblings (API − 1..4) are no\n * longer declared at all (#1783). Remote only (local has no app k8s deploy).\n *\n * Ports are de-duplicated by number and carry K8s-valid names (see\n * {@link toK8sPortName}); a name collision after sanitisation is disambiguated\n * with a numeric suffix so the emitted Service is always valid.\n */\n private static buildBackendPodPorts(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): { podPorts: K8sPodPort[]; healthPort: number | undefined } {\n if (env.locationType !== WildoLocationType.REMOTE) {\n return { podPorts: [], healthPort: undefined };\n }\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n const backendPort = primaryBackend?.defaultPort;\n\n const seenPorts = new Set<number>();\n const usedNames = new Set<string>();\n const podPorts: K8sPodPort[] = [];\n const add = (rawName: string, containerPort: number | undefined): void => {\n if (containerPort === undefined || seenPorts.has(containerPort)) return;\n seenPorts.add(containerPort);\n let name = toK8sPortName(rawName);\n if (usedNames.has(name)) {\n // Disambiguate on a collision. Truncate the base to leave room for the\n // `-NN` suffix WITHIN the 15-char K8s port-name cap — appending the\n // suffix through `toK8sPortName` again would just re-truncate it back to\n // the colliding base and spin forever. Result stays ≤15 chars.\n const base = name.slice(0, 12).replace(/-+$/g, '');\n let suffix = 2;\n while (suffix < 100 && usedNames.has(`${base}-${suffix}`)) suffix += 1;\n name = `${base}-${suffix}`;\n }\n usedNames.add(name);\n podPorts.push({ name, containerPort });\n };\n\n // Per-service model: the BACKEND pod exposes ONLY the primary backend's\n // port. The engine's HTTP server binds exactly one, and serves health,\n // webhooks, the OAuth provider and MCP as routes on it — the four \"sibling\"\n // ports (API − 1..4) this used to expose were bound by nothing (#1783).\n // Frontends are SEPARATE nginx Deployments\n // (see `buildApplicationFrontendDeployTargets`), so their ports are NOT\n // folded into this pod. (Non-primary backend services, if any, would become\n // their own Deployments — a multi-backend follow-up; wonder-todos has one.)\n if (backendPort !== undefined) {\n add('backend', backendPort);\n }\n\n return { podPorts, healthPort: backendPort };\n }\n\n /**\n * The app's public frontends as per-service k8s deploy targets — each becomes\n * its OWN nginx Deployment + Service. `serviceName` is both the k8s object name\n * and the built image name (`{registry}/{serviceName}:{tag}`); `port` is the\n * authored `defaultPort` the frontend Service exposes (forwarded to nginx :80).\n * Frontends without a `defaultPort` are non-served (skipped). CDN-served\n * frontends are ALSO skipped — they get no nginx pod at all (served\n * off-cluster; see {@link cdnFrontendKeys}). Remote only.\n */\n private static buildApplicationFrontendDeployTargets(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): Array<{\n serviceKey: string;\n serviceName: string;\n port: number;\n isolation: { runAsUser: number; runAsGroup: number; writablePaths: string[] };\n }> {\n if (env.locationType !== WildoLocationType.REMOTE) {\n return [];\n }\n const cdnKeys = AppBootstrapService.cdnFrontendKeys(env);\n return runtimeTarget.frontendServices.flatMap((frontend) =>\n frontend.defaultPort && !cdnKeys.has(frontend.key)\n ? [{\n serviceKey: frontend.key,\n serviceName: frontend.serviceName,\n port: frontend.defaultPort,\n // Already resolved at the config boundary — passed through, never\n // re-derived, so the k8s and compose lanes cannot disagree.\n isolation: {\n runAsUser: frontend.isolation.runAsUser,\n runAsGroup: frontend.isolation.runAsGroup,\n writablePaths: [...frontend.isolation.writablePaths],\n },\n }]\n : [],\n );\n }\n\n /**\n * Read a runtime's ALREADY-GENERATED `.env` for the one value that cannot be\n * derived offline: its bootstrap secret.\n *\n * Returns `null` when the file does not exist or carries no secret — which is\n * exactly the FIRST-RUN case, and the case that must NOT be papered over: a\n * runtime apps-manager has never registered has no Redis ACL user, no RabbitMQ\n * user and no database role either, so inventing an env for it would produce a\n * runtime that boots and is refused by every backing service.\n */\n private static readPersistedBootstrapSecret(envFilePath: string): string | null {\n if (!existsSync(envFilePath)) return null;\n for (const line of readFileSync(envFilePath, 'utf8').split('\\n')) {\n const match = line.match(/^PLATFORM_APPLICATION_PRIMARY_SECRET=(.+)$/);\n if (match) {\n const value = match[1]!.trim().replace(/^[\"']|[\"']$/g, '');\n return value.length > 0 ? value : null;\n }\n }\n return null;\n }\n\n /**\n * Rebuild {@link AppBootstrapCredentials} WITHOUT contacting apps-manager.\n *\n * Only ONE of the four fields is a secret. `APPLICATION_ID` is already persisted\n * by `saveApplicationRuntimeIdentity` for exactly this reason (this rebuild is\n * its consumer), and the apps-manager URL and environment are\n * local configuration. So a degraded regeneration reuses the secret the runtime\n * already holds and derives the rest, which is precisely what apps-manager would\n * have returned: it PRESERVES an existing principal's secret rather than\n * re-minting, because rotating it would break a running runtime.\n *\n * `null` means the material is not on disk. The caller must then fail for THAT\n * runtime and say so, rather than degrade the whole sync.\n */\n private static reconstructBootstrapCredentialsOffline(input: {\n envName: string;\n appSlug: string;\n runtimeEnvironment: RuntimeEnvironment;\n appsManagerUrl: string;\n envFilePath: string;\n }): AppBootstrapCredentials | null {\n const primarySecret = AppBootstrapService.readPersistedBootstrapSecret(input.envFilePath);\n const applicationId = EnvironmentUtils.loadApplicationRuntimeIdentity(input.envName)?.[input.appSlug]?.applicationId;\n if (!primarySecret || !applicationId) return null;\n return buildAppBootstrapCredentialsResponse({\n appSlug: input.appSlug,\n applicationId,\n primarySecret,\n appsManagerUrl: input.appsManagerUrl,\n environment: input.runtimeEnvironment,\n }).credentials;\n }\n\n /**\n * True only for a CONNECTION-level failure — apps-manager not listening.\n *\n * Deliberately NOT true for an HTTP error response or a timeout. A 4xx/5xx means\n * apps-manager IS running and rejected the request (bad admin secret, invalid\n * declaration); degrading there would hide a real error behind a reassuring\n * warning. A timeout is ambiguous and is left fatal for the same reason.\n */\n private static isAppsManagerUnreachable(error: unknown): boolean {\n return /Unable to reach apps-manager/.test(ErrorUtils.extractErrorMessage(error));\n }\n\n /**\n * Rebuild EVERY declared principal's credentials offline (Step: degraded env).\n *\n * A minion's or worker's secret is its OWN — that is the entire point of Step 1,\n * which replaced one shared `PLATFORM_APPLICATION_PRIMARY_SECRET` per application\n * with one per runtime. So each principal's value is read from ITS OWN `.env`,\n * located through the same `saasConfig.{minions,workers}.<name>.path` the target\n * builders already use.\n *\n * ⚠️ There is deliberately NO fallback to the application-level secret. Reusing\n * it here would make every runtime present the same identity at the apps-manager\n * door — precisely the F11 collapse Step 1 exists to have removed — and it would\n * do so silently, in a code path whose whole purpose is to be reassuring. A\n * principal whose own secret is not on disk THROWS, naming itself.\n */\n private static async reconstructRuntimePrincipalCredentialsOffline(input: {\n envName: string;\n runtimeTarget: ResolvedAppRuntimeTarget;\n runtimeEnvironment: RuntimeEnvironment;\n appsManagerUrl: string;\n /**\n * The application backend's secret, as resolved for this run. A principal whose `.env` still holds THIS value was\n * last written before it had an identity of its own (the development companion before #2941), so it is reported\n * unresolved rather than handed the backend's identity again.\n */\n applicationBackendSecret: string;\n }): Promise<{ credentials: Record<string, AppBootstrapCredentials>; unresolved: string[] }> {\n const saasConfig = await loadConfig<{\n minions?: Record<string, { path: string }>;\n workers?: Record<string, { path: string }>;\n }>(input.runtimeTarget.saasConfigPath);\n\n const entries: Array<readonly [string, AppBootstrapCredentials]> = [];\n const unresolved: string[] = [];\n for (const principal of enumerateRuntimePrincipalsWithBootstrapSecrets(input.runtimeTarget.managedDeclaration, {\n hostsDevelopmentCompanion: AppBootstrapService.hostsDevelopmentCompanion(input.runtimeTarget, input.runtimeEnvironment),\n })) {\n const name = principal.name ?? '';\n const relativePath = AppBootstrapService.runtimePrincipalRelativeDir(principal, input.runtimeTarget, saasConfig);\n const reconstructed = relativePath\n ? AppBootstrapService.reconstructBootstrapCredentialsOffline({\n envName: input.envName,\n appSlug: input.runtimeTarget.appSlug,\n runtimeEnvironment: input.runtimeEnvironment,\n appsManagerUrl: input.appsManagerUrl,\n envFilePath: join(input.runtimeTarget.appRoot, relativePath, '.env'),\n })\n : null;\n const credentials = reconstructed && reconstructed.PLATFORM_APPLICATION_PRIMARY_SECRET !== input.applicationBackendSecret\n ? reconstructed\n : null;\n if (!credentials) {\n // Per-runtime granularity: this principal cannot be regenerated offline,\n // but the OTHERS can. Omitting it from the map (rather than throwing)\n // leaves its existing `.env` untouched and lets every other runtime be\n // written — and the omission is REPORTED, not silent, by the caller.\n //\n // Omission is the safe representation: `requireRuntimePrincipalCredentials`\n // refuses to substitute the application backend's identity for a missing\n // entry, so a skipped principal can never end up with the wrong secret.\n unresolved.push(\n `${buildRuntimePrincipalKey(principal)}`\n + `${relativePath ? ` (expected its own secret in ${join(relativePath, '.env')})` : ' (no declared path)'}`,\n );\n continue;\n }\n entries.push([buildRuntimePrincipalKey(principal), credentials] as const);\n }\n return { credentials: Object.fromEntries(entries), unresolved };\n }\n\n /**\n * Whether this run writes a development companion's environment, and so fetches its own secret (#2941): the\n * environment is a development one (the platform mints a companion secret there and nowhere else) and the\n * application has a companion to write it for.\n */\n private static hostsDevelopmentCompanion(runtimeTarget: ResolvedAppRuntimeTarget, runtimeEnvironment: RuntimeEnvironment): boolean {\n return runtimeEnvironmentHostsDevelopmentCompanion(runtimeEnvironment)\n && existsSync(resolveAppLayout(runtimeTarget.appRoot).companionHome);\n }\n\n /** Where a principal's `.env` lives, relative to the application root; `undefined` when nothing declares one. */\n private static runtimePrincipalRelativeDir(\n principal: ApplicationRuntimePrincipal,\n runtimeTarget: ResolvedAppRuntimeTarget,\n saasConfig: { minions?: Record<string, { path: string }>; workers?: Record<string, { path: string }> },\n ): string | undefined {\n switch (principal.kind) {\n case ApplicationRuntimePrincipalKind.MINION:\n return saasConfig.minions?.[principal.name ?? '']?.path;\n case ApplicationRuntimePrincipalKind.WORKER:\n return saasConfig.workers?.[principal.name ?? '']?.path;\n case ApplicationRuntimePrincipalKind.DEVELOPMENT_COMPANION:\n return AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, resolveAppLayout(runtimeTarget.appRoot).companionHome, `Application companion for '${runtimeTarget.appSlug}'`,\n );\n case ApplicationRuntimePrincipalKind.APPLICATION_BACKEND:\n // The backend's credentials are `bootstrapCredentials`, never a per-principal entry.\n return undefined;\n }\n }\n\n static async prepareApplicationEnvTargets(\n input: RegisteredApplicationEnvTargetInput,\n ): Promise<PreparedApplicationEnvTargets | null> {\n const runtimeTarget = await AppBootstrapService.resolveRuntimeTarget({ ...input, environmentName: input.env.name });\n if (!runtimeTarget) {\n return null;\n }\n\n await AppBootstrapService.validateFirstAdminSeedAgainstBackendConfig(runtimeTarget);\n\n if (runtimeTarget.backendServices.length === 0) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no backend services to prepare. Check wildo.saas.config.ts service definitions.`,\n );\n }\n\n const config = input.config ?? EnvironmentUtils.loadConfigJson(input.env.name);\n if (!config) {\n throw new Error(`No config for '${input.env.name}'. Run 'wildo config sync' to generate config.json.`);\n }\n\n const runtimeEnvironment = resolveRuntimeEnvironment(input.env, config);\n\n /**\n * Where this application's broker and storage live (#1107), from the SAME function that writes\n * `RABBITMQ_VHOST` / `STORAGE_BUCKET` into its backend env. Hoisted for the same reason as\n * `applicationDatabaseDeclaration` below: both provisioning phases must send one value.\n */\n const backingServiceAddressing = resolveApplicationBackingServiceAddressing(config);\n\n /**\n * ## Breaking the provisioning ↔ schema cycle\n *\n * An application whose own resources persist to PostgreSQL cannot be seeded before its schema\n * exists, and its schema is produced by migration artifacts that only the tooling can read. So\n * provisioning runs in TWO phases with the schema apply between them:\n *\n * 1. register with `DEFERRED` — infrastructure, credentials and platform records; no app rows;\n * 2. apply the application's migrations through the shared runner;\n * 3. register again (idempotent, `REQUIRED`) — now the bootstrap rows land.\n *\n * Phase 3 is a full re-invocation rather than a narrow seed call ON PURPOSE: provisioning also\n * issues the per-role GRANTs, and a grant can only be issued on a table that exists. Running the\n * whole provision after the migrations is what gives every confined role (minions, workers) its\n * grants on the tables the migrations just created — a seed-only endpoint would have left them\n * ungranted and moved the failure into the first minion boot.\n *\n * MongoDB is untouched: no migrations directory means one phase, exactly as before.\n */\n /**\n * From the ALREADY-LOADED config.json rather than the registry record: `applicationDatabase` is\n * deliberately not round-tripped through `environments.json`, because nothing reads it off that\n * cache — see the note in `hydrateEnvironmentFromConfig` about fields the registry does not own.\n *\n * Hoisted to a local so BOTH provisioning phases send the identical declaration. Recomputing it\n * for the second call would be two spellings of one value, and a divergence would land on the\n * provisioner as a database rename mid-provision.\n */\n const applicationDatabaseDeclaration = {\n /*\n * RESOLVED, never forwarded as absent (#1571). An environment that authors no\n * `applicationDatabase` is a PostgreSQL application, and sending the resolved engine means\n * apps-manager, the schema bootstrap below and `env-vars-builder` cannot answer silence\n * differently — which is exactly how the 2026-09-15 incident happened.\n */\n engine: resolveApplicationDatabaseEngine(config.applicationDatabase),\n // The SAME authored value `env-vars-builder` emits as `POSTGRESQL_DATABASE`, so the\n // database the backend connects to and the one the provisioner creates are one name\n // from one source.\n databaseName: config.backingServices?.postgresql?.database,\n };\n\n /**\n * Two-phase provisioning applies only when a PostgreSQL schema must exist before the application\n * can be seeded — see {@link resolveAppSchemaMigrationsDirectory} for why the ENGINE, and not\n * merely the presence of the migrations directory, is half of that question.\n */\n const usesTwoPhaseProvisioning = AppBootstrapService.resolveAppSchemaMigrationsDirectory(\n runtimeTarget,\n applicationDatabaseDeclaration,\n ) !== undefined;\n\n let bootstrapResponse: { credentials: AppBootstrapCredentials };\n let degraded = false;\n let declarationConvergedFields: string[] | undefined;\n try {\n const firstPhase = await AppBootstrapService.ensureApplicationRegistered(input.env, input.credentials, {\n appSlug: runtimeTarget.appSlug,\n appDisplayName: runtimeTarget.appDisplayName,\n appDatabaseName: runtimeTarget.appDatabaseName,\n managedDeclaration: runtimeTarget.managedDeclaration,\n applicationDatabase: applicationDatabaseDeclaration,\n backingServiceAddressing,\n firstAdminSeed: runtimeTarget.firstAdminSeed,\n appDatabaseSeeding: usesTwoPhaseProvisioning\n ? AppDatabaseSeedingPhase.DEFERRED\n : AppDatabaseSeedingPhase.REQUIRED,\n });\n\n declarationConvergedFields = firstPhase.declarationConvergedFields;\n if (usesTwoPhaseProvisioning) {\n const secondPhase = await AppBootstrapService.completeDeferredAppDatabaseSeeding({\n env: input.env,\n credentials: input.credentials,\n runtimeTarget,\n applicationDatabase: applicationDatabaseDeclaration,\n backingServiceAddressing,\n firstPhaseOutcome: firstPhase.appDatabaseSeeding,\n });\n // The first phase converges; the second normally reports nothing. Union them so neither is lost.\n if (secondPhase?.declarationConvergedFields !== undefined) {\n declarationConvergedFields = [...new Set([...(declarationConvergedFields ?? []), ...secondPhase.declarationConvergedFields])];\n }\n }\n\n bootstrapResponse = await AppBootstrapService.fetchBootstrapCredentials(\n input.env,\n input.credentials,\n {\n appSlug: runtimeTarget.appSlug,\n runtimeEnvironment,\n },\n );\n } catch (error) {\n // Degrade ONLY when apps-manager is not listening, and ONLY when the\n // material is already on disk. Every other failure — an HTTP rejection, a\n // timeout, a first run with no persisted secret — stays fatal, because\n // degrading there would either hide a real error or fabricate an identity\n // no backing service recognises.\n if (!AppBootstrapService.isAppsManagerUnreachable(error)) throw error;\n const authoritativeBackend = AppBootstrapService.resolveAuthoritativeBackendTarget(runtimeTarget);\n const offline = authoritativeBackend\n ? AppBootstrapService.reconstructBootstrapCredentialsOffline({\n envName: input.env.name,\n appSlug: runtimeTarget.appSlug,\n runtimeEnvironment,\n appsManagerUrl: AppBootstrapService.getAppsManagerBaseUrl(input.env),\n // `path` is app-root-relative; the runtime target carries the root.\n envFilePath: join(runtimeTarget.appRoot, authoritativeBackend.path, '.env'),\n })\n : null;\n if (!offline) throw error;\n /*\n * Say what was skipped, and why. The degrade used to be silent past the reconnect line, which\n * dropped the one fact the next failure depends on: registration is what converges the stored\n * declaration (`/initialize` reapplies `wildo.saas.config.ts` unconditionally), so a degraded\n * run serves the STORED declaration, not the authored one. On 2026-10-01 that surfaced two\n * steps later as an \"out of generation\" verification failure that named neither cause.\n */\n reportAppsManagerWait(\n `Registration of '${runtimeTarget.appSlug}' did not reach apps-manager `\n + `(${ErrorUtils.extractErrorMessage(error)}). Writing runtime env from the credentials already on disk; `\n + 'wildo.saas.config.ts was NOT applied to the stored application config in this run.',\n );\n degraded = true;\n bootstrapResponse = { credentials: offline };\n }\n\n // Persist the apps-manager-minted APPLICATION_ID (a Mongo `_id`, NOT\n // derivable offline from the slug) so a degraded regeneration can rebuild\n // bootstrap credentials without re-contacting apps-manager\n // (`reconstructBootstrapCredentialsOffline`). This method is the single\n // credential-fetch choke point (every app-target builder funnels through\n // it), so one write here keeps the persisted identity fresh.\n EnvironmentUtils.saveApplicationRuntimeIdentity(\n input.env.name,\n runtimeTarget.appSlug,\n bootstrapResponse.credentials.APPLICATION_ID,\n );\n\n // The THIRD apps-manager call site, and the one the first draft missed: it sat\n // inside the return expression, outside the try above. Degrading two of three\n // calls moved the failure one step later rather than removing it.\n let runtimePrincipalCredentials: Record<string, AppBootstrapCredentials>;\n let unresolvedPrincipals: string[] = [];\n try {\n runtimePrincipalCredentials = await AppBootstrapService.fetchDeclaredRuntimePrincipalCredentials(\n input,\n runtimeTarget,\n runtimeEnvironment,\n );\n } catch (error) {\n if (!AppBootstrapService.isAppsManagerUnreachable(error)) throw error;\n const offlinePrincipals = await AppBootstrapService.reconstructRuntimePrincipalCredentialsOffline({\n envName: input.env.name,\n runtimeTarget,\n runtimeEnvironment,\n appsManagerUrl: AppBootstrapService.getAppsManagerBaseUrl(input.env),\n applicationBackendSecret: bootstrapResponse.credentials.PLATFORM_APPLICATION_PRIMARY_SECRET,\n });\n runtimePrincipalCredentials = offlinePrincipals.credentials;\n unresolvedPrincipals = offlinePrincipals.unresolved;\n degraded = true;\n\n // Report ALL unresolved principals at once, then fail.\n //\n // Why fail rather than skip: a skipped runtime would be SILENT here — this\n // service has no logger, and the sync command does not hold `prepared`, so\n // nothing would tell the operator that one runtime's `.env` was left stale.\n // Shipping a silent skip would trade a loud failure for exactly the\n // \"correct and believed otherwise\" defect this whole change exists to\n // remove. Granular WRITING is worth having, but only once the skip can be\n // reported — see the note in the plan; the mechanism is the existing\n // `input.prepared` passthrough, which lets the sync command prepare once\n // and read `unresolvedPrincipals` itself.\n //\n // What IS improved: every unresolved principal is named in one message\n // instead of failing on the first, so one run tells the operator the whole\n // list rather than one name per re-run.\n if (unresolvedPrincipals.length > 0) {\n throw new Error(\n `Cannot regenerate env files without apps-manager. `\n + `${unresolvedPrincipals.length} runtime principal(s) have no existing secret on disk:\\n`\n + unresolvedPrincipals.map((entry) => ` - ${entry}`).join('\\n')\n + `\\nA runtime apps-manager has never registered also has no Redis ACL user, no broker `\n + `user and no database role, so its env cannot be produced offline. Every OTHER runtime `\n + `could be regenerated — start apps-manager and re-run to write them all.`,\n );\n }\n }\n\n return {\n runtimeTarget,\n degraded,\n declarationConvergedFields,\n bootstrapCredentials: bootstrapResponse.credentials,\n runtimeEndpoints: AppBootstrapService.buildRuntimeEndpoints(runtimeTarget, input.env),\n runtimeEnvironment,\n runtimePrincipalCredentials,\n unresolvedPrincipals,\n };\n }\n\n private static resolveAuthoritativeBackendTarget(\n runtimeTarget: Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>,\n ) {\n if (!runtimeTarget || runtimeTarget.backendServices.length === 0) {\n return null;\n }\n\n return selectPrimaryBackendService(runtimeTarget.backendServices) ?? null;\n }\n\n private static resolveAuthoritativeBackendConfigPath(\n runtimeTarget: Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>,\n ): string | null {\n const backendTarget = AppBootstrapService.resolveAuthoritativeBackendTarget(runtimeTarget);\n if (!backendTarget || !runtimeTarget) {\n return null;\n }\n\n const candidatePaths = [\n resolve(runtimeTarget.appRoot, backendTarget.path, 'src', 'saas-config.backend.ts'),\n resolve(runtimeTarget.appRoot, backendTarget.path, 'src', 'config', 'app-config.backend.ts'),\n ];\n\n return candidatePaths.find((candidatePath) => existsSync(candidatePath)) ?? candidatePaths[0]!;\n }\n\n private static async validateFirstAdminSeedAgainstBackendConfig(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n ): Promise<void> {\n const projectedUserTypes = runtimeTarget.firstAdminSeed?.userTypes;\n if (!projectedUserTypes || projectedUserTypes.length === 0) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' is missing bootstrap.firstAdmin.userTypes in '${runtimeTarget.saasConfigPath}'. `\n + 'Declare the first-admin bootstrap seed before running bootstrap, sync, reinit, or dev start.',\n );\n }\n\n const authoritativeBackend = AppBootstrapService.resolveAuthoritativeBackendTarget(runtimeTarget);\n if (!authoritativeBackend) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' declares bootstrap.firstAdmin.userTypes but has no backend service to validate against.`,\n );\n }\n\n const backendConfigPath = AppBootstrapService.resolveAuthoritativeBackendConfigPath(runtimeTarget);\n if (!backendConfigPath || !existsSync(backendConfigPath)) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' declares bootstrap.firstAdmin.userTypes, but the authoritative backend config was not found at '${backendConfigPath ?? 'unknown'}' for service '${authoritativeBackend.serviceName}'.`,\n );\n }\n\n const backendConfig = await loadConfig<AppConfiguration_BackendAuthored>(backendConfigPath);\n const declaredBackendUserTypes = new Set(Object.keys(backendConfig.userTypes ?? {}));\n const unknownUserTypes = projectedUserTypes.filter((userType) => !declaredBackendUserTypes.has(userType));\n\n if (unknownUserTypes.length > 0) {\n throw new Error(\n `Invalid bootstrap.firstAdmin.userTypes for application '${runtimeTarget.appSlug}': `\n + `[${unknownUserTypes.join(', ')}] not found in backend config '${backendConfigPath}'. `\n + `Declared backend userTypes: [${[...declaredBackendUserTypes].join(', ')}].`,\n );\n }\n }\n\n /**\n * A target's directory as a path relative to ITS application root — the anchor every env writer\n * joins it back onto (see `ApplicationRuntimeTargetAnchor`). Refuses a service path that escapes\n * the application: a `wildo.saas.config.ts` naming `../elsewhere` would otherwise have the CLI\n * write a `.env` into a directory the application does not own.\n */\n private static relativeToApplicationRoot(applicationRoot: string, targetDirectory: string, subject: string): string {\n const relativeDir = relative(resolve(applicationRoot), resolve(targetDirectory));\n if (relativeDir.startsWith('..') || isAbsolute(relativeDir)) {\n throw new Error(`${subject} is outside the application root and cannot receive generated .env files.`);\n }\n return relativeDir;\n }\n\n private static async resolveRuntimeTarget(input: {\n saasRoot: string;\n requestedAppSlug?: string | undefined;\n /** The environment the declaration is registered in; `null` when only the service topology is read. */\n environmentName: string | null;\n }) {\n return AppRuntimeTargetsService.resolve(input.saasRoot, {\n environmentName: input.environmentName,\n requestedAppSlug: input.requestedAppSlug,\n });\n }\n\n private static getAppsManagerBaseUrl(env: PlatformEnvironmentConfiguration): string {\n const addressContext = ServiceAddressResolver.fromEnvironment(env, AddressPerspective.HOST_FACING);\n const addresses = ServiceAddressResolver.resolve(addressContext);\n return `${addresses.platform.appsManager.url}${APPS_MANAGER_API_PREFIX}`;\n }\n\n private static getAdminSecret(credentials: PlatformEnvSecretsJson): string {\n return credentials.platform.adminSecret;\n }\n\n /**\n * Bounded, silent poll of apps-manager's own `/health/ready` (unversioned —\n * outside `APPS_MANAGER_API_PREFIX`, mirroring `waitForServiceReady` in\n * `platform-lifecycle.service.ts`). Used ONLY to ride out the crash/respawn\n * window documented on {@link APPS_MANAGER_RECONNECT_ATTEMPTS}; not a\n * general-purpose readiness wait — `wildo local dev`'s own platform-readiness\n * barrier already owns that responsibility before this service is entered.\n */\n /**\n * One reconnect PROBE, inside the poll loop.\n *\n * Short on purpose, and shorter than the loop's own budget: the caller already owns \"how long do\n * we wait for apps-manager\" through `APPS_MANAGER_RECONNECT_WAIT_MS`, so a probe that lingers\n * only eats that budget in one bite instead of polling with it. 5s is enough for a service on\n * this machine to answer a readiness route, and a probe that cannot is not ready.\n */\n private static readonly APPS_MANAGER_PROBE_TIMEOUT_MS = 5_000;\n\n private static async waitForAppsManagerReconnect(env: PlatformEnvironmentConfiguration): Promise<boolean> {\n const addressContext = ServiceAddressResolver.fromEnvironment(env, AddressPerspective.HOST_FACING);\n const addresses = ServiceAddressResolver.resolve(addressContext);\n const readyUrl = `${addresses.platform.appsManager.url.replace(/\\/$/, '')}/health/ready`;\n\n const deadline = Date.now() + APPS_MANAGER_RECONNECT_WAIT_MS;\n while (Date.now() < deadline) {\n try {\n const probe = await fetch(readyUrl, { signal: AbortSignal.timeout(AppBootstrapService.APPS_MANAGER_PROBE_TIMEOUT_MS), redirect: 'manual' });\n if (probe.ok) return true;\n } catch {\n // Connection still refused/reset — keep polling until the deadline.\n }\n await new Promise((resolve) => setTimeout(resolve, APPS_MANAGER_RECONNECT_POLL_INTERVAL_MS));\n }\n return false;\n }\n\n /**\n * Connects with a bounded reconnect-retry on connection-level failure only\n * (never on an HTTP error response, and never on a request timeout — both\n * are handled/thrown by the caller). See {@link APPS_MANAGER_RECONNECT_ATTEMPTS}.\n */\n private static async fetchWithReconnect(\n url: string,\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n init: RequestInit,\n /** Per-OPERATION budget. Defaults to the light-call budget; heavy calls pass their own. */\n timeoutMs: number = APPS_MANAGER_TIMEOUT_MS,\n ): Promise<Response> {\n for (let attempt = 0; ; attempt++) {\n try {\n const response = await fetch(url, {\n ...init,\n headers: {\n [APPS_MANAGER_ADMIN_SECRET_HEADER]: AppBootstrapService.getAdminSecret(credentials),\n ...(init.body ? { [WildoHeaderKeys.CONTENT_TYPE]: 'application/json' } : {}),\n ...(init.headers ?? {}),\n },\n signal: AbortSignal.timeout(timeoutMs),\n });\n // REACHABILITY, not success: an HTTP error response still proves a platform is listening,\n // which is the only question the reconnect decision asks.\n appsManagerAnsweredThisRun = true;\n return response;\n } catch (error) {\n if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n throw new Error(\n buildAppsManagerDiagnosticMessage({\n envName: env.name,\n summary: `Apps-manager request timed out after ${timeoutMs}ms at ${url}.`,\n }),\n );\n }\n\n /**\n * Never reached in this run ⇒ nothing to ride out. Fail now, and SAY so — the alternative\n * is a silent 30-second stall per call, four times over, ending in the same answer.\n */\n if (!appsManagerAnsweredThisRun) {\n reportAppsManagerWait(\n `apps-manager is not answering at ${AppBootstrapService.getAppsManagerBaseUrl(env)} and has not answered `\n + 'at any point in this run, so there is no crash/respawn to wait out. Continuing without it — a command '\n + 'that can use already-persisted material will; one that cannot will fail with its own diagnostic.',\n );\n throw new Error(\n buildAppsManagerDiagnosticMessage({\n envName: env.name,\n summary: `Unable to reach apps-manager at ${url}: ${ErrorUtils.extractErrorMessage(error)}.`,\n }),\n );\n }\n\n const canRetry = attempt < APPS_MANAGER_RECONNECT_ATTEMPTS;\n if (canRetry) {\n reportAppsManagerWait(\n `apps-manager stopped answering mid-run (attempt ${attempt + 1}/${APPS_MANAGER_RECONNECT_ATTEMPTS}) — `\n + `waiting up to ${APPS_MANAGER_RECONNECT_WAIT_MS / 1_000}s for the supervisor to respawn it...`,\n );\n if (await AppBootstrapService.waitForAppsManagerReconnect(env)) {\n reportAppsManagerWait('apps-manager is back; retrying.');\n continue;\n }\n reportAppsManagerWait('apps-manager did not come back within the window.');\n }\n\n throw new Error(\n buildAppsManagerDiagnosticMessage({\n envName: env.name,\n summary: `Unable to reach apps-manager at ${url}: ${ErrorUtils.extractErrorMessage(error)}.`,\n }),\n );\n }\n }\n }\n\n private static async requestJson(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n path: string,\n init: RequestInit = {},\n /** Per-OPERATION budget — see {@link APPS_MANAGER_INITIALIZE_TIMEOUT_MS}. */\n timeoutMs: number = APPS_MANAGER_TIMEOUT_MS,\n ): Promise<unknown> {\n const baseUrl = AppBootstrapService.getAppsManagerBaseUrl(env).replace(/\\/$/, '');\n const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n\n const response = await AppBootstrapService.fetchWithReconnect(url, env, credentials, init, timeoutMs);\n\n if (!response.ok) {\n if (response.status === 401 || response.status === 403) {\n throw new Error(\n 'Apps-manager rejected bootstrap authentication. Check PLATFORM_ADMIN_SECRET.',\n );\n }\n\n const errorBody = await readErrorBody(response);\n throw new Error(\n `Apps-manager request failed at ${url}: ${response.status} ${response.statusText}${errorBody ? ` - ${errorBody}` : ''}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * The application's migration artifacts, or `undefined` when no PostgreSQL schema has to be\n * applied before the application can be seeded.\n *\n * BOTH conditions are required, and the engine is the one that was missing.\n *\n * The first revision keyed solely on the directory, reasoning that \"an application that HAS\n * migrations needs them applied whatever its declared engine says, because the declaration and the\n * artifacts are two statements that can disagree while only the artifacts can create a table.\"\n * That is false for a MongoDB application: the artifacts describe a POSTGRESQL schema for a store\n * it does not use. The engine declaration is precisely what decides whether any PostgreSQL schema\n * is needed at all.\n *\n * Measured 2026-08-23, flipping this application back to MongoDB for the control run: the\n * `backend-api/migrations` directory survives the flip (it is committed), so two-phase provisioning\n * engaged, deferred the seed, and then tried to migrate a PostgreSQL database that a MongoDB\n * install never creates. `wildo local dev` aborted during application bootstrap with the\n * application left deliberately unseeded — worse than the deadlock the two-phase flow exists to\n * break, because it also affects the engine that never had the problem.\n */\n private static resolveAppSchemaMigrationsDirectory(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n applicationDatabase: { engine: DatabaseEngine; databaseName?: string } | undefined,\n ): string | undefined {\n if (applicationDatabase?.engine !== DatabaseEngine.POSTGRESQL) return undefined;\n // `appRoot` IS the saas root — `resolveRuntimeTarget` derives `saasConfigPath` by joining the\n // config filename onto it — so it is the same anchor `wildo db migrate` resolves from.\n return resolveAppMigrationsDirectory(runtimeTarget.appRoot);\n }\n\n /**\n * Phase 2 + 3: apply the application's schema, then re-invoke provisioning so the deferred\n * bootstrap rows land and every per-role GRANT is issued over the tables that now exist.\n *\n * Fails closed at both ends, because every degradation here produces an application that looks\n * provisioned and cannot boot:\n *\n * - an apps-manager that did not honour the phase (it is older than the contract, so it reported\n * nothing) is NOT assumed to have seeded — the migrations still run, and the idempotent second\n * call still completes the seed;\n * - an apps-manager that reports anything other than `SEEDED` after the schema exists is a defect,\n * not a state to retry past.\n */\n private static async completeDeferredAppDatabaseSeeding(input: {\n env: PlatformEnvironmentConfiguration;\n credentials: PlatformEnvSecretsJson;\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>;\n applicationDatabase: { engine: DatabaseEngine; databaseName?: string } | undefined;\n backingServiceAddressing: ApplicationBackingServiceAddressing;\n firstPhaseOutcome: AppDatabaseSeedingOutcome | undefined;\n }): Promise<ApplicationRegistrationOutcome | undefined> {\n if (input.firstPhaseOutcome === AppDatabaseSeedingOutcome.NO_PERSISTENCE_TARGET) {\n /**\n * Nothing the tooling does next can seed this application — the target itself is missing, and\n * apps-manager has already logged why. Applying migrations would fail on a database that was\n * never provisioned, with a message about connectivity rather than about the real cause.\n */\n return undefined;\n }\n\n await applyAppSchemaMigrations({\n envName: input.env.name,\n saasRoot: input.runtimeTarget.appRoot,\n appliedBy: `cli:bootstrap:${input.runtimeTarget.appSlug}`,\n reportMissing: (message) => { throw new Error(message); },\n });\n\n const secondPhase = await AppBootstrapService.ensureApplicationRegistered(input.env, input.credentials, {\n appSlug: input.runtimeTarget.appSlug,\n appDisplayName: input.runtimeTarget.appDisplayName,\n appDatabaseName: input.runtimeTarget.appDatabaseName,\n managedDeclaration: input.runtimeTarget.managedDeclaration,\n applicationDatabase: input.applicationDatabase,\n backingServiceAddressing: input.backingServiceAddressing,\n firstAdminSeed: input.runtimeTarget.firstAdminSeed,\n appDatabaseSeeding: AppDatabaseSeedingPhase.REQUIRED,\n });\n\n const secondPhaseOutcome = secondPhase.appDatabaseSeeding;\n if (secondPhaseOutcome !== undefined && secondPhaseOutcome !== AppDatabaseSeedingOutcome.SEEDED) {\n throw new Error(\n `Application '${input.runtimeTarget.appSlug}' was not seeded after its schema was applied `\n + `(apps-manager reported '${secondPhaseOutcome}'). Its backend requires exactly one APPLICATION `\n + 'row and cannot boot without it.',\n );\n }\n return secondPhase;\n }\n\n static async ensureApplicationRegistered(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: {\n appSlug: string;\n appDisplayName: string;\n appDatabaseName?: string | undefined;\n managedDeclaration: AdminAppManagedDeclaration;\n /**\n * The application's own persistence engine, from the authored `applicationDatabase`.\n *\n * This is the CLI half of the door that did not exist: apps-manager's per-application\n * PostgreSQL provisioning is gated on `usePostgreSQL`, which nothing in the repository set\n * until 2026-08-19. Omitted means MongoDB, so an environment that authors nothing is unchanged.\n */\n applicationDatabase?: { engine: DatabaseEngine; databaseName?: string } | undefined;\n /**\n * The application's authored broker vhost and storage bucket (#1107). REQUIRED rather than\n * optional: a registration that omits it makes apps-manager provision this application under\n * the platform owner's values, which is the defect the field exists to remove.\n */\n backingServiceAddressing: ApplicationBackingServiceAddressing;\n firstAdminSeed?: AppBootstrapFirstAdminSeed | undefined;\n /**\n * WHEN apps-manager should seed the application's own database. See\n * {@link AppDatabaseSeedingPhase} for the circularity `DEFERRED` breaks.\n */\n appDatabaseSeeding?: AppDatabaseSeedingPhase | undefined;\n },\n ): Promise<ApplicationRegistrationOutcome> {\n const body = AdminAppInitializeRequestSchema.parse({\n name: input.appDisplayName,\n appDatabaseName: input.appDatabaseName,\n userEmail: credentials.admin.email,\n userFirstName: credentials.admin.firstName,\n userLastName: credentials.admin.lastName,\n userPassword: credentials.admin.password,\n /*\n * The SECOND administrator (#575), and this site was enumerated as \"read only — no change\n * expected\" when the CLI half landed. That was WRONG, and it is the site that matters most:\n * `applicationAccessGrants` has zero mentions under `platform/` — it is an ENGINE resource, so\n * the two-person rule bites inside the GENERATED APPLICATION, not on the platform plane. This\n * request is what carries an identity into that application's own database, where\n * `_getDefault_App_FirstUser` is the only writer of `APP_ADMIN_SUPER_ADMIN` at provisioning\n * time.\n *\n * Spread, so a `secrets.json` predating the `approver` block sends nothing at all rather than\n * four `undefined`s that would read as a half-stated identity at the door.\n */\n ...(credentials.approver\n ? {\n approverEmail: credentials.approver.email,\n approverFirstName: credentials.approver.firstName,\n approverLastName: credentials.approver.lastName,\n approverPassword: credentials.approver.password,\n }\n : {}),\n managedDeclaration: input.managedDeclaration,\n applicationDatabase: input.applicationDatabase,\n backingServiceAddressing: input.backingServiceAddressing,\n firstAdminSeed: input.firstAdminSeed,\n appDatabaseSeeding: input.appDatabaseSeeding,\n /**\n * Forward the authored `serviceAuth` snapshot mirrored from\n * `wildo.infra.<env>.config.ts`. Apps-manager seeds platform-managed\n * JWT TTLs from this when present, including re-registration of an existing app.\n * An omitted block preserves an existing policy; first registration uses schema defaults.\n */\n serviceAuth: env.serviceAuth,\n });\n\n const response = await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminInitializeApplicationPath(input.appSlug),\n {\n method: 'POST',\n body: JSON.stringify(body),\n },\n APPS_MANAGER_INITIALIZE_TIMEOUT_MS,\n );\n\n /**\n * Returns the outcome rather than discarding it. An `undefined` field means an apps-manager that\n * predates it and therefore said nothing — which the caller must treat as UNKNOWN (not seeded, not\n * converged), never as the reassuring answer.\n */\n const parsed = AdminAppInitializeResponseSchema.parse(response);\n return {\n appDatabaseSeeding: parsed.appDatabaseSeeding,\n declarationConvergedFields: parsed.declarationConvergedFields,\n };\n }\n\n /**\n * POST /admin/apps/:appSlug/reapply-declaration\n *\n * Re-source the declaration-managed slices of the app's stored config\n * from the latest `wildo.saas.config.ts` projection. Idempotent.\n *\n * See `AdminAppReapplyDeclarationRequestSchema` (platform-config-lib)\n * for the contract scope: this does NOT touch K8s endpoints, infra, admin\n * user/role seeding, or any credential except the minions' runtime-principal\n * credentials, which apps-manager reconciles when the `minions` slice changes.\n */\n static async reapplyApplicationDeclaration(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: {\n appSlug: string;\n managedDeclaration: AdminAppManagedDeclaration;\n /**\n * Ask the server to report the diff and write nothing (issue #97).\n *\n * An empty `updatedFields` under a dry run is the coherence proof the init postcondition\n * and `wildo local doctor` rely on.\n */\n dryRun?: boolean;\n },\n ): Promise<AdminAppReapplyDeclarationResponse> {\n /*\n * The flag is omitted rather than sent as `false` when not requested, so the wire payload of an\n * ordinary reapply is byte-identical to what it was before `dryRun` existed. The request schema\n * is a `strictObject`, so this is also what keeps an older apps-manager from rejecting the call.\n */\n const body = AdminAppReapplyDeclarationRequestSchema.parse({\n managedDeclaration: input.managedDeclaration,\n ...(input.dryRun === true ? { dryRun: true } : {}),\n });\n\n const response = await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminReapplyDeclarationPath(input.appSlug),\n {\n method: 'POST',\n body: JSON.stringify(body),\n },\n );\n\n return AdminAppReapplyDeclarationResponseSchema.parse(response);\n }\n\n /**\n * POST /admin/registry/keys — mint a module-registry key for an organization (default: the platform\n * owner organization) (#1756). The response carries the secret exactly once.\n */\n static async mintRegistryKey(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n request: RegistryKeyMintRequest,\n ): Promise<RegistryKeyMintResponse> {\n const response = await AppBootstrapService.requestJson(env, credentials, REGISTRY_KEYS_ADMIN_PATH, {\n method: 'POST',\n body: JSON.stringify(RegistryKeyMintRequestSchema.parse(request)),\n });\n return RegistryKeyMintResponseSchema.parse(response);\n }\n\n /** GET /admin/registry/keys[?organizationSlug=] — an organization's registry keys, no secrets (#1756). */\n static async listRegistryKeys(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n organizationSlug?: string,\n ): Promise<RegistryKeyListResponse> {\n const query = organizationSlug ? `?organizationSlug=${encodeURIComponent(organizationSlug)}` : '';\n const response = await AppBootstrapService.requestJson(env, credentials, `${REGISTRY_KEYS_ADMIN_PATH}${query}`, { method: 'GET' });\n return RegistryKeyListResponseSchema.parse(response);\n }\n\n /** POST /admin/registry/keys/:apiKeyId/revoke — the registry refuses the key from then on (#1756). */\n static async revokeRegistryKey(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { apiKeyId: string; organizationSlug?: string },\n ): Promise<void> {\n await AppBootstrapService.requestJson(env, credentials, buildRegistryKeyRevokePath(input.apiKeyId), {\n method: 'POST',\n body: JSON.stringify(RegistryKeyRevokeRequestSchema.parse(input.organizationSlug ? { organizationSlug: input.organizationSlug } : {})),\n });\n }\n\n /**\n * POST /admin/apps/:appSlug/keys/rotate — rotate one of an application's keyrings: planned, emergency or root-lost (#2891).\n * Answers with the application's keyring status afterwards.\n */\n static async rotateKeyring(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n request: KeyringRotationRequest,\n ): Promise<KeyringStatus> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminKeyringRotationPath(appSlug), {\n method: 'POST',\n body: JSON.stringify(KeyringRotationRequestSchema.parse(request)),\n });\n return KeyringRotationResponseSchema.parse(response);\n }\n\n /** GET /admin/apps/:appSlug/signing-keys — an application's signing keys as `kid`s and dates, no material (#2895). */\n static async readApplicationSigningKeys(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n ): Promise<ApplicationSigningKeysStatus> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationSigningKeysPath(appSlug), { method: 'GET' });\n return ApplicationSigningKeysStatusSchema.parse(response);\n }\n\n /**\n * POST /admin/apps/:appSlug/signing-keys/rotate — rotate an application's signing keys, naming the keys it replaces\n * (#2895). A failed attempt is sent ONCE more, unchanged: the request is a compare-and-set on the keys it names, so a\n * re-send of a rotation that happened (its answer lost to a timeout or a dropped connection) is answered\n * `already_rotated` and rotates nothing, and a refused one is refused again.\n */\n static async rotateApplicationSigningKeys(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n request: ApplicationSigningKeyRotationRequest,\n ): Promise<ApplicationSigningKeyRotationResponse> {\n const send = async () => ApplicationSigningKeyRotationResponseSchema.parse(\n await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationSigningKeyRotationPath(appSlug), {\n method: 'POST',\n body: JSON.stringify(ApplicationSigningKeyRotationRequestSchema.parse(request)),\n }),\n );\n try {\n return await send();\n } catch {\n return await send();\n }\n }\n\n /**\n * POST /admin/apps/:appSlug/signing-keys/stage or /promote (#2895), the two halves of a planned rotation. A failed\n * attempt is sent ONCE more, unchanged: a re-sent staging is answered `already_staged`, a re-sent promotion (a\n * compare-and-set on the staged keys it names) `already_promoted`, and a refused one is refused again.\n */\n static async planApplicationSigningKeyRotation(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n step: { stage: ApplicationSigningKeyStageRequest } | { promote: ApplicationSigningKeyPromoteRequest },\n ): Promise<ApplicationSigningKeyRotationResponse> {\n const [path, body] = 'stage' in step\n ? [buildAdminApplicationSigningKeyStagePath(appSlug), ApplicationSigningKeyStageRequestSchema.parse(step.stage)]\n : [buildAdminApplicationSigningKeyPromotePath(appSlug), ApplicationSigningKeyPromoteRequestSchema.parse(step.promote)];\n const send = async () => ApplicationSigningKeyRotationResponseSchema.parse(\n await AppBootstrapService.requestJson(env, credentials, path, { method: 'POST', body: JSON.stringify(body) }),\n );\n try {\n return await send();\n } catch {\n return await send();\n }\n }\n\n /** GET /admin/apps/:appSlug/legacy-envelope-key — whether the legacy session encryption key is delivered (#3028). */\n static async readApplicationLegacyEnvelopeKey(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n ): Promise<ApplicationLegacyEnvelopeKeyStatus> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationLegacyEnvelopeKeyPath(appSlug), { method: 'GET' });\n return ApplicationLegacyEnvelopeKeyStatusSchema.parse(response);\n }\n\n /**\n * POST /admin/apps/:appSlug/legacy-envelope-key/retire or /restore (#3028). A failed attempt is sent ONCE more,\n * unchanged: both doors are idempotent (a re-sent retirement is answered `already_retired`, a re-sent restoration\n * `already_delivered`), and a refused one is refused again.\n */\n static async changeApplicationLegacyEnvelopeKeyDelivery(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n change: { retire: ApplicationLegacyEnvelopeKeyRetirementRequest } | { restore: ApplicationLegacyEnvelopeKeyRestoreRequest },\n ): Promise<ApplicationLegacyEnvelopeKeyResponse> {\n const [path, body] = 'retire' in change\n ? [buildAdminApplicationLegacyEnvelopeKeyRetirePath(appSlug), ApplicationLegacyEnvelopeKeyRetirementRequestSchema.parse(change.retire)]\n : [buildAdminApplicationLegacyEnvelopeKeyRestorePath(appSlug), ApplicationLegacyEnvelopeKeyRestoreRequestSchema.parse(change.restore)];\n const send = async () => ApplicationLegacyEnvelopeKeyResponseSchema.parse(\n await AppBootstrapService.requestJson(env, credentials, path, { method: 'POST', body: JSON.stringify(body) }),\n );\n try {\n return await send();\n } catch {\n return await send();\n }\n }\n\n /**\n * GET /admin/apps/:appSlug/residue\n *\n * What the platform still holds for this application (#1556) — read-only. Every count arrives\n * beside the means to tell absence from inability to ask, which is the whole reason the probe\n * exists: an empty answer that cannot prove it looked is indistinguishable from success.\n */\n static async inspectApplicationResidue(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { appSlug: string },\n ): Promise<ApplicationResidueResponse> {\n return await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminApplicationResiduePath(input.appSlug),\n { method: 'GET' },\n ) as ApplicationResidueResponse;\n }\n\n /**\n * POST /admin/apps/:appSlug/deregister\n *\n * Withdraw an application from the platform (#1556): its cron schedule is removed, its row is marked, and\n * every credential minted for it — the backend's and each minion's Redis, RabbitMQ, MongoDB and PostgreSQL\n * credentials — is REVOKED (#1307). **Destroys no data**: database, broker vhost, cache namespace and blobs\n * are kept, which is why this takes no confirmation and no environment gate, and why `restore` can bring the\n * application back. Destruction is a separate, parked concern (#1562).\n *\n * A withdrawal that could not revoke every credential answers 500 with the list of what still authenticates;\n * `requestJson` surfaces that body in the error it throws.\n *\n * Idempotent: an already-withdrawn application is withdrawn again, and a retry converges.\n */\n static async deregisterApplication(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { appSlug: string; reason?: string },\n ): Promise<ApplicationDeregistrationResponse> {\n return await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminDeregisterApplicationPath(input.appSlug),\n {\n method: 'POST',\n body: JSON.stringify(input.reason ? { reason: input.reason } : {}),\n },\n APPS_MANAGER_CREDENTIAL_LIFECYCLE_TIMEOUT_MS,\n ) as ApplicationDeregistrationResponse;\n }\n\n /**\n * POST /admin/apps/:appSlug/restore\n *\n * Return a withdrawn application to service and RE-MINT the credentials its withdrawal revoked, with the\n * recorded material (#1307), so it can boot. The schedule is re-established by the application's own next\n * boot, because only the application knows its jobs.\n */\n static async restoreApplication(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { appSlug: string },\n ): Promise<ApplicationRestoreResponse> {\n return await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminRestoreApplicationPath(input.appSlug),\n { method: 'POST', body: JSON.stringify({}) },\n APPS_MANAGER_CREDENTIAL_LIFECYCLE_TIMEOUT_MS,\n ) as ApplicationRestoreResponse;\n }\n\n static async fetchBootstrapCredentials(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: {\n appSlug: string;\n runtimeEnvironment: RuntimeEnvironment;\n /**\n * Which runtime principal to fetch for (Step 1 / F11). Omitted ⇒ the\n * application backend, which is what every caller wanted when one secret\n * per application was the only thing that existed.\n */\n principal?: ApplicationRuntimePrincipal;\n },\n ) {\n const response = await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAppBootstrapCredentialsPath(\n input.appSlug,\n input.runtimeEnvironment,\n input.principal ? buildRuntimePrincipalKey(input.principal) : undefined,\n ),\n { method: 'GET' },\n );\n\n return AppBootstrapCredentialsResponseSchema.parse(response);\n }\n\n /**\n * Fetch ONE runtime's own bootstrap credentials.\n *\n * The app-level `prepared.bootstrapCredentials` is the APPLICATION BACKEND's\n * identity. Minion and worker targets used to reuse it verbatim — which is\n * exactly what F11 measured when it compared `backend-api/.env` and\n * `marketing-scrapper/.env` and found the secret byte-identical.\n *\n * The `APPLICATION_ID` and apps-manager URL are per-application and come back\n * identical; only `PLATFORM_APPLICATION_PRIMARY_SECRET` differs. Keeping the\n * whole envelope (rather than splicing one field into the app's) means the\n * runtime's `.env` is built from a response that was authenticated and\n * validated as a unit.\n */\n /**\n * Fetch one bootstrap credential set PER declared minion and worker.\n *\n * The app-level `bootstrapCredentials` is the APPLICATION BACKEND's identity.\n * Minion and worker targets used to reuse it verbatim — which is exactly what\n * F11 measured when it compared `backend-api/.env` with\n * `marketing-scrapper/.env` and found the secret byte-identical.\n *\n * `APPLICATION_ID` and the apps-manager URL come back identical for every\n * principal; only `PLATFORM_APPLICATION_PRIMARY_SECRET` differs. The whole\n * envelope is kept rather than splicing one field into the app's, so each\n * runtime's `.env` is built from a response that was authenticated and\n * validated as a unit.\n */\n private static async fetchDeclaredRuntimePrincipalCredentials(\n input: ApplicationEnvProjectionInput,\n runtimeTarget: ResolvedAppRuntimeTarget,\n runtimeEnvironment: RuntimeEnvironment,\n ): Promise<Record<string, AppBootstrapCredentials>> {\n // Sourced from the MANAGED DECLARATION, not a re-read of the saas config.\n // That is the same input apps-manager mints from, so the set of principals\n // the CLI asks for and the set apps-manager stores cannot drift — and it\n // costs no extra filesystem access, since the declaration is already\n // resolved on the target.\n // The development companion joins on a development environment (#2941), from the same derivation apps-manager mints\n // from, so the CLI never asks for a companion secret the platform did not mint.\n const principals = enumerateRuntimePrincipalsWithBootstrapSecrets(runtimeTarget.managedDeclaration, {\n hostsDevelopmentCompanion: AppBootstrapService.hostsDevelopmentCompanion(runtimeTarget, runtimeEnvironment),\n });\n\n const entries = await Promise.all(\n principals.map(async (principal) => {\n const response = await AppBootstrapService.fetchBootstrapCredentials(\n input.env,\n input.credentials,\n { appSlug: runtimeTarget.appSlug, runtimeEnvironment, principal },\n );\n return [buildRuntimePrincipalKey(principal), response.credentials] as const;\n }),\n );\n return Object.fromEntries(entries);\n }\n\n /**\n * A declared runtime's own credentials, or a hard failure.\n *\n * Deliberately NO fallback to `prepared.bootstrapCredentials`. A fallback here\n * would hand the runtime the application backend's identity and the sync would\n * report success — reintroducing F11 silently, at the one seam built to close\n * it. A missing entry means preparation and the declaration disagree, which is\n * a bug to surface, not to paper over.\n */\n /**\n * Degraded-mode counterpart of {@link requireRuntimePrincipalCredentials}.\n *\n * Returns `null` for a principal the offline reconstruction could not resolve,\n * so the caller SKIPS that runtime and writes the others. Outside degraded mode\n * it delegates and still THROWS — a missing entry there means preparation and\n * the declaration disagree, which is a bug to surface rather than skip.\n *\n * The strictness that matters is untouched either way: nothing ever substitutes\n * the application backend's identity for a principal's.\n */\n private static resolveRuntimePrincipalCredentialsOrSkip(\n prepared: PreparedApplicationEnvTargets,\n principal: ApplicationRuntimePrincipal,\n ): AppBootstrapCredentials | null {\n if (prepared.degraded && !prepared.runtimePrincipalCredentials[buildRuntimePrincipalKey(principal)]) {\n return null;\n }\n return AppBootstrapService.requireRuntimePrincipalCredentials(prepared, principal);\n }\n\n private static requireRuntimePrincipalCredentials(\n prepared: PreparedApplicationEnvTargets,\n principal: ApplicationRuntimePrincipal,\n ): AppBootstrapCredentials {\n const principalKey = buildRuntimePrincipalKey(principal);\n const credentials = prepared.runtimePrincipalCredentials[principalKey];\n if (!credentials) {\n throw new Error(\n `No bootstrap credentials prepared for runtime principal '${principalKey}'. `\n + 'Every declared minion and worker, and the development companion, must have its own identity; refusing to fall back to the application backend\\'s.',\n );\n }\n return credentials;\n }\n\n static async buildApplicationBackendTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<ApplicationBackendEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n const { runtimeTarget, bootstrapCredentials, runtimeEndpoints } = prepared;\n\n // App-level deploy context (same value on every backend target, like\n // runtimeEndpoints) — the CI render path reads it to emit the serviceHosts\n // ingress (k8s) / Traefik routing (compose). Empty for local.\n const ingressRoutes = AppBootstrapService.buildApplicationIngressRoutes(runtimeTarget, input.env);\n const { podPorts, healthPort } = AppBootstrapService.buildBackendPodPorts(runtimeTarget, input.env);\n // Per-service model: the frontends deploy as their own nginx Deployments —\n // carried on the (primary-first) backend target's app-deploy context so the\n // CI render emits a backend Deployment + one frontend Deployment per entry.\n const frontends = AppBootstrapService.buildApplicationFrontendDeployTargets(runtimeTarget, input.env);\n // Backend→worker dispatch URLs (G-8 / MW4): every declared worker's per-app\n // k8s Service URL, keyed by bucket name. Emitted into the backend env as\n // `WILDO_WORKER_<NAME>_URL` so the backend's WorkerRemoteClientFactory can\n // call each worker. BOTH location types since #426 — a k8s Service URL for\n // REMOTE, a loopback address for LOCAL; same value on every backend target.\n const workerUrls = AppBootstrapService.buildApplicationWorkerDispatchUrls(runtimeTarget, input.env);\n\n\n // Emit the targets PRIMARY-FIRST. The shared `{appSlug}-secret`\n // (k8s-secrets-generator §5, deduped by appName, first-wins) must bake the\n // PRIMARY backend's identity env (SERVICE_NAME / OTEL_SERVICE_NAME) — the\n // single app pod + every minion mount it — not whichever backend happened to\n // be authored first. The same `selectPrimaryBackendService` rule the runtime endpoints and pod\n // ports use.\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n const orderedBackends = primaryBackend\n ? [primaryBackend, ...runtimeTarget.backendServices.filter((backend) => backend !== primaryBackend)]\n : runtimeTarget.backendServices;\n\n return orderedBackends.map((service) => {\n const serviceRoot = resolve(runtimeTarget.appRoot, service.path);\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, serviceRoot, `Application backend '${service.serviceName}'`,\n );\n return {\n bootstrapCredentials,\n serviceKey: service.key,\n serviceName: service.serviceName,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n applicationRuntimeSignalsHome: join(runtimeTarget.appRoot, WORKSPACE_HOME_NAMES.APP_RUNTIME_HOME, APP_RUNTIME_SUBDIR_NAMES.RUNTIME_SIGNALS),\n appDatabaseName: runtimeTarget.appDatabaseName,\n redisKeyPrefix: runtimeTarget.redisKeyPrefix,\n storageBucketPrefix: runtimeTarget.storageBucketPrefix,\n runtimeEndpoints,\n appName: runtimeTarget.appSlug,\n ingressRoutes: ingressRoutes.length > 0 ? ingressRoutes : undefined,\n podPorts: podPorts.length > 0 ? podPorts : undefined,\n healthPort,\n frontends: frontends.length > 0 ? frontends : undefined,\n // Per-service, not per-app: each backend row carries its own resolved\n // isolation. Passed through from the config boundary unchanged.\n isolation: {\n runAsUser: service.isolation.runAsUser,\n runAsGroup: service.isolation.runAsGroup,\n writablePaths: [...service.isolation.writablePaths],\n },\n workerUrls,\n // The backend's own declared provider scope. It legitimately declares\n // most providers, so this changes nothing for it today — but it must be\n // threaded explicitly, because the builder now fails CLOSED: an omitted\n // scope yields no provider secrets rather than all of them.\n scopedProviderRefs: runtimeTarget.backendScopedProviderRefs,\n };\n });\n }\n\n /**\n * Build the backend→worker dispatch URL map (G-8 / MW4): for every worker\n * declared in `wildo.saas.config.ts > workers`, its in-cluster base URL\n * `http://{appSlug}-worker-{bucketKey}:{http.port}`, keyed by bucket name.\n *\n * BOTH location types, by different addressing (#426).\n *\n * REMOTE resolves the per-app k8s Service, coherent-by-construction with\n * `renderWorkerForTarget` via the shared `buildWorkerInternalUrl` helper (same\n * `{appSlug}-worker-{key}` Service name). LOCAL has no Service to resolve, so it\n * addresses the supervised worker process on loopback at its authored port.\n *\n * This was `REMOTE only` until 2026-09-09, on the reasoning that \"local dev has no\n * k8s Services, and worker dispatch is a k8s-deploy concern\". The first half is\n * still true; the second stopped being true when `wildo local dev` began starting\n * workers. What local dev lacked was never a worker — it was an ADDRESS, and\n * without one `WorkerRemoteClientFactory.client()` fails closed on the absent\n * `WILDO_WORKER_<NAME>_URL`. That is why the backend-to-worker chain had never run\n * for anyone: it was unreachable in the only environment where anyone could try.\n *\n * The worker `http.port` comes from the resolved runtime target's managed\n * declaration, which `AppRuntimeTargetsService.resolve` built by parsing every\n * worker config through `WildoWorkerConfigSchema` — the same authoritative parse\n * `buildApplicationWorkerTargets` uses — so a wrong port can never drift from the\n * deployed Service or the local listener.\n *\n * It deliberately does NOT re-load `wildo.saas.config.ts` here. The runtime target\n * IS the parsed row; reading the file again would be a second parse of the same\n * truth, and it made this builder the one step of `buildApplicationBackendTargets`\n * that could not run against a resolved target alone (measured 2026-09-09: the\n * backend-targets pin, which stands in a resolved target for a config file that\n * does not exist, failed here and nowhere else once LOCAL joined REMOTE).\n */\n private static buildApplicationWorkerDispatchUrls(\n runtimeTarget: ResolvedAppRuntimeTarget,\n env: PlatformEnvironmentConfiguration,\n ): Record<string, string> | undefined {\n const workers = runtimeTarget.managedDeclaration.workers ?? {};\n const urls: Record<string, string> = {};\n for (const [workerName, worker] of Object.entries(workers)) {\n urls[workerName] = env.locationType === WildoLocationType.REMOTE\n ? buildWorkerInternalUrl(runtimeTarget.appSlug, workerName, worker.http.port)\n : buildWorkerLocalUrl(worker.http.port);\n }\n return Object.keys(urls).length > 0 ? urls : undefined;\n }\n\n static async buildApplicationCompanionTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<CompanionPlatformEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n\n const { runtimeTarget, runtimeEndpoints } = prepared;\n // A companion runs on a development environment only (#2941): no other platform mints it a secret.\n if (!AppBootstrapService.hostsDevelopmentCompanion(runtimeTarget, prepared.runtimeEnvironment)) {\n return [];\n }\n const companionRoot = resolveAppLayout(runtimeTarget.appRoot).companionHome;\n // The companion's OWN identity (#2941), never the backend's `bootstrapCredentials`: presenting the backend's secret\n // made it indistinguishable from the backend at apps-manager. Degraded mode skips it when its own secret is not on\n // disk; otherwise a missing entry throws, as for a minion.\n const companionCredentials = AppBootstrapService.resolveRuntimePrincipalCredentialsOrSkip(prepared, DEVELOPMENT_COMPANION_PRINCIPAL);\n if (!companionCredentials) {\n return [];\n }\n\n const companionRelativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, companionRoot, `Application companion for '${runtimeTarget.appSlug}'`,\n );\n\n const companionExtraEnv: Record<string, string> = {};\n\n if (runtimeTarget.localServiceAddresses?.devCompanion?.host) {\n companionExtraEnv.HOST = runtimeTarget.localServiceAddresses.devCompanion.host;\n }\n if (runtimeTarget.localServiceAddresses?.devCompanion?.port) {\n companionExtraEnv.PORT = String(runtimeTarget.localServiceAddresses.devCompanion.port);\n }\n\n return [{\n bootstrapCredentials: companionCredentials,\n serviceName: `${runtimeTarget.appSlug}-dev-companion`,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir: companionRelativeDir,\n runtimeEndpoints,\n extraEnv: companionExtraEnv,\n }];\n }\n\n static async buildApplicationWorkerTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<ApplicationWorkerEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n\n const { runtimeTarget, bootstrapCredentials, runtimeEndpoints } = prepared;\n const isRemote = input.env.locationType === WildoLocationType.REMOTE;\n const saasConfig = await loadConfig<{\n workers?: Record<string, { path: string }>;\n providers?: { scopes?: { workers?: Record<string, { providers?: Record<string, unknown> }> } };\n }>(runtimeTarget.saasConfigPath);\n const workers = saasConfig.workers ?? {};\n const targets: ApplicationWorkerEnvTarget[] = [];\n\n for (const [workerName, workerRef] of Object.entries(workers)) {\n const workerRoot = resolve(runtimeTarget.appRoot, workerRef.path);\n // Parse through the authoritative schema — validates the authored config\n // AND applies the canonical defaults (port 8080, /healthz, /readyz,\n // replicas 1) from `WorkerHttpSchema`/`WildoWorkerConfigSchema`. Deriving\n // from the spec (rather than re-defaulting `?? 8080` here) keeps the k8s\n // manifest in lockstep with the runtime contract — no drift, no second\n // source of the defaults, and a malformed config fails fast.\n const workerConfig = WildoWorkerConfigSchema.parse(\n await loadConfig(join(workerRoot, WORKER_CONFIG_FILENAME)),\n );\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, workerRoot, `Application worker '${workerName}'`,\n );\n\n const workerCredentials = AppBootstrapService.resolveRuntimePrincipalCredentialsOrSkip(\n prepared,\n { kind: ApplicationRuntimePrincipalKind.WORKER, name: workerName },\n );\n if (!workerCredentials) continue;\n\n targets.push({\n // Workers get their own identity too (D22). Leaving them on the shared\n // application secret would ship the containment with a worker-shaped\n // bypass: a worker could fetch every minion's credentials, so excluding\n // them would not have been the conservative choice.\n bootstrapCredentials: workerCredentials,\n workerName,\n serviceName: workerConfig.name,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n // Where the worker records how its start ended (#3288): the dev supervisor names a process holding its port\n // from that record, as it does for the backend. Written only for a LOCAL deployment (the env builder's guard).\n applicationRuntimeSignalsHome: join(runtimeTarget.appRoot, WORKSPACE_HOME_NAMES.APP_RUNTIME_HOME, APP_RUNTIME_SUBDIR_NAMES.RUNTIME_SIGNALS),\n runtimeEndpoints,\n // Declared provider scope — see the identical field on the minion target.\n // `myRustWorker` declares `providers: {}` and therefore receives no\n // provider secrets at all; it previously received every one of them.\n scopedProviderRefs: Object.keys(\n saasConfig.providers?.scopes?.workers?.[workerName]?.providers ?? {},\n ),\n // Authored worker HTTP (schema-defaulted): nested `http` populated for\n // every env (the `.env` projection is not remote-only), shared by the\n // worker env-gen and the REMOTE k8s render.\n http: {\n port: workerConfig.http.port,\n healthPath: workerConfig.http.healthPath,\n readyPath: workerConfig.http.readyPath,\n metricsPath: workerConfig.http.metricsPath,\n },\n // NOT inside the `isRemote` branch below — container isolation feeds\n // BOTH renderers (k8s securityContext + volumes, compose\n // `user`/`read_only`/`tmpfs`/`pids_limit`). Same placement and same\n // reason as the minion target below.\n isolation: workerConfig.isolation,\n // REMOTE k8s deploy context (appName + replicas).\n ...(isRemote\n ? { appName: runtimeTarget.appSlug, replicas: workerConfig.replicas }\n : {}),\n });\n }\n\n return targets;\n }\n\n static async buildApplicationMinionTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<ApplicationMinionEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n\n const { runtimeTarget, bootstrapCredentials, runtimeEndpoints } = prepared;\n const saasConfig = await loadConfig<{\n minions?: Record<string, {\n path: string;\n /**\n * The minion's authored application-data access. Read here so env\n * generation can withhold a backing service's TOPOLOGY from a minion that\n * never declared it (object storage) — the same declaration apps-manager\n * reads to decide which tables and storage prefixes beyond the engine floor\n * that minion's credentials cover (#1771).\n *\n * ABSENT and declared-but-empty are different statements and must stay\n * distinguishable all the way down; see `RuntimeAccessDeclaration`.\n */\n resourceAccess?: { read?: readonly string[]; write?: readonly string[] };\n /** Authored opt-in for a route off the host. Default false, never inferred. */\n requiresInternetEgress?: boolean;\n }>;\n // The scope's providers are a REF -> ENTRY map, not a bag of unknowns. Typed\n // that way so `registerMinionLocalProviders` can merge into it without the\n // call site loosening its contract to fit a placeholder type.\n providers?: { scopes?: { minions?: Record<string, { providers?: Record<string, Record<string, unknown>> }> } };\n }>(runtimeTarget.saasConfigPath);\n const minions = saasConfig.minions ?? {};\n const targets: ApplicationMinionEnvTarget[] = [];\n\n const isRemote = input.env.locationType === WildoLocationType.REMOTE;\n for (const [minionName, minionRef] of Object.entries(minions)) {\n const minionRoot = resolve(runtimeTarget.appRoot, minionRef.path);\n // Parse through the authoritative schema — validates AND applies the\n // canonical `MinionReinstantiationSchema`/`MinionLivenessSchema` defaults\n // (kill_previous, file liveness at /tmp/wildo-minion-alive, staleAfterSec\n // 90). Derived from the spec so the k8s manifest never drifts from the\n // runtime contract, and a malformed minion config fails fast.\n const minionConfig = WildoMinionConfigSchema.parse(\n await loadConfig(join(minionRoot, MINION_CONFIG_FILENAME)),\n );\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, minionRoot, `Application minion '${minionName}'`,\n );\n\n const minionCredentials = AppBootstrapService.resolveRuntimePrincipalCredentialsOrSkip(\n prepared,\n { kind: ApplicationRuntimePrincipalKind.MINION, name: minionName },\n );\n // Degraded mode only: a principal whose own secret is not on disk is SKIPPED\n // so every other runtime is still written. Outside degraded mode the resolver\n // throws, preserving the guard that refuses the backend's identity.\n if (!minionCredentials) continue;\n\n targets.push({\n // The minion's OWN identity, not the application backend's. This one\n // line is what F11 was about: every minion previously shipped with the\n // app's `PLATFORM_APPLICATION_PRIMARY_SECRET`, so at the apps-manager\n // door it could ask as the backend — making any narrowing elsewhere\n // bypassable rather than enforced.\n bootstrapCredentials: minionCredentials,\n minionName,\n serviceName: minionConfig.name,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n applicationRuntimeSignalsHome: join(runtimeTarget.appRoot, WORKSPACE_HOME_NAMES.APP_RUNTIME_HOME, APP_RUNTIME_SUBDIR_NAMES.RUNTIME_SIGNALS),\n appDatabaseName: runtimeTarget.appDatabaseName,\n // The minion's OWN Redis namespace (D20), NOT the application's.\n //\n // This is one half of a COUPLED PAIR: apps-manager grants this minion's\n // ACL user exactly `buildMinionRedisKeyPrefix(...)*`, and this is the\n // prefix the minion actually writes under. Derived from the SAME\n // function so the two cannot drift — if they disagree by a character,\n // every Redis operation the minion performs is DENIED and the error\n // names an ACL rather than the mismatch, so nothing in the minion's own\n // configuration explains it.\n //\n // A strict extension of the application prefix, which keeps\n // `RedisService`'s \"an authored prefix must start with `<appSlug>:`\"\n // rule true without changing that rule.\n redisKeyPrefix: buildMinionRedisKeyPrefix(runtimeTarget.appSlug, minionName),\n storageBucketPrefix: runtimeTarget.storageBucketPrefix,\n runtimeEndpoints,\n // NOT inside the `isRemote` branch below: container isolation applies to\n // BOTH renderers. k8s consumes it as securityContext + volumes, compose\n // as `user`/`read_only`/`tmpfs`/`pids_limit`. Gating it on REMOTE would\n // leave local dev running the pre-hardening posture while the manifest\n // claimed otherwise — exactly the k8s/compose asymmetry Step 5b warns\n // about.\n isolation: {\n runAsUser: minionConfig.isolation.runAsUser,\n runAsGroup: minionConfig.isolation.runAsGroup,\n writablePaths: minionConfig.isolation.writablePaths,\n pidsLimit: minionConfig.isolation.pidsLimit,\n },\n // The provider refs this minion DECLARED. Read from the authored scope\n // rather than inherited from the application: a minion scoped to `openai`\n // must not receive the app's Stripe key, and until now it did — the scope\n // was materialised into topology while the SECRETS ignored it entirely.\n // An undeclared scope yields `[]`, i.e. no provider secrets, matching the\n // fail-closed posture `resourceAccess` already takes (D11).\n // R7 — the minion's locally-AUTHORED providers are registered into its own\n // scope before the refs are derived, so a locally-authored provider is\n // visible to this minion exactly as an application-declared one is, and\n // through the SAME projection. Everything downstream — the secret\n // filtering, the generated runtime module — reads the merged scope and\n // cannot tell the two apart, which is what keeps ONE runtime source and\n // ONE secret mechanism.\n //\n // Registered HERE rather than at the catalog: this is the single place\n // that holds both the parsed minion config (which carries the fragment)\n // and the application scope it merges into.\n scopedProviderRefs: Object.keys(\n registerMinionLocalProviders(\n saasConfig.providers?.scopes?.minions?.[minionName],\n minionConfig.localProviders,\n minionName,\n ).providers,\n ),\n // Forwarded VERBATIM, including its absence. Defaulting to `{}` here\n // would turn \"declared nothing\" into \"declared empty\" and hand a\n // non-declaring minion the object-storage route it never asked for;\n // defaulting the other way would strip a declaring minion's object-storage\n // topology. Neither default is safe, so there is none. (The database\n // topology does not depend on the declaration: every minion gets it, #1771.)\n accessDeclaration: {\n resourceAccess: minionRef.resourceAccess,\n requiresInternetEgress: minionRef.requiresInternetEgress,\n },\n // REMOTE k8s deploy context (schema-defaulted fields, read directly).\n ...(isRemote\n ? {\n appName: runtimeTarget.appSlug,\n reinstantiationPolicy: minionConfig.reinstantiation.policy,\n gracePeriodSec: minionConfig.reinstantiation.gracePeriodSec,\n // Whole, so the probe cadence and the heartbeat env are derived from the same parsed value (#1859).\n liveness: minionConfig.liveness,\n }\n : {}),\n });\n }\n\n return targets;\n }\n\n static async buildApplicationFrontendTargets(input: {\n saasRoot: string;\n requestedAppSlug?: string | undefined;\n prepared?: PreparedApplicationEnvTargets;\n }): Promise<ApplicationFrontendEnvExampleTarget[]> {\n // Frontend `.env` targets read the service topology only, which no environment's provider configuration changes.\n const runtimeTarget = input.prepared?.runtimeTarget ?? await AppBootstrapService.resolveRuntimeTarget({ ...input, environmentName: null });\n if (!runtimeTarget) {\n return [];\n }\n\n // The PRIMARY backend's port, never a fallback to another backend's: when `backendApi` declares no\n // port, borrowing `backendServices[0]`'s made the app's API URL name a different backend than the\n // runtime endpoints and the website's local API origin, which all select through the same rule.\n const primaryBackendPort = selectPrimaryBackendService(runtimeTarget.backendServices)?.defaultPort;\n /**\n * Where the DEV SERVER forwards API traffic. This is an internal hop to a plain-http listener and\n * stays http under every edge scheme — the same public/internal split the runtime topology makes.\n */\n const apiProxyTarget = primaryBackendPort ? `http://localhost:${primaryBackendPort}` : undefined;\n\n return runtimeTarget.frontendServices.map((service) => {\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, resolve(runtimeTarget.appRoot, service.path), `Application frontend '${service.serviceName}'`,\n );\n\n /**\n * No `NODE_ENV` here, on purpose (#3097). Vite reads `NODE_ENV=development` from a `.env` file as\n * \"make a development build\", so every `vite build` run from the working tree bundled React's\n * DEVELOPMENT build: StrictMode active, every effect run, cleaned up and run again at mount. A\n * production bundle built that way never showed the sign-in form, and the same would ship to a\n * CDN through `wildo frontend publish`, which uploads a locally built `dist`. Each dev server (Vite,\n * `astro dev`, `docusaurus start`) sets `NODE_ENV` itself, and the SaaS frontend reads its mode\n * from Vite's `MODE`, so nothing needs the line.\n */\n const envExample: Record<string, string> = {\n VITE_APP_SLUG: runtimeTarget.appSlug,\n VITE_APP_NAME: runtimeTarget.appDisplayName,\n ...(service.defaultPort ? { VITE_PORT: String(service.defaultPort) } : {}),\n };\n\n if (service.defaultPort) {\n envExample.VITE_HMR_HOST = 'localhost';\n envExample.VITE_HMR_CLIENT_PORT = String(service.defaultPort);\n // The HMR socket rides the page's own origin, which is plain http locally.\n envExample.VITE_HMR_PROTOCOL = 'ws';\n }\n\n if (service.frontendType === AppFrontendType.SAAS_APP) {\n if (!apiProxyTarget) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no backend API port to bind frontend '${service.serviceName}' to VITE_API_BASE_URL.`,\n );\n }\n\n /**\n * The browser addresses the backend port DIRECTLY. This is the long-standing local behaviour,\n * and as of 2026-08-14 the only one: the dev API proxy was removed, so there is no dev-server\n * origin to address the API on and no proxy target to emit.\n *\n * ⚠️ Under a TLS edge this becomes a mixed-content problem — an https page cannot call the\n * backend's plain-http port. That is one of the reasons the local TLS edge was withdrawn; if\n * one is ever reintroduced, the API origin and the forwarding it implies have to come back\n * TOGETHER, not one before the other.\n */\n envExample.VITE_API_BASE_URL = apiProxyTarget;\n envExample.VITE_FRONTEND_SERVICE_NAME = service.serviceName;\n\n }\n\n if (service.frontendType === AppFrontendType.TECH_DOC) {\n /**\n * The documentation site needs the same three origins the SaaS app does, but under\n * its OWN env names: it is a Docusaurus build, not a Vite app, so it never reads\n * `VITE_*`. Its config refuses to complete a PRODUCTION build when these are unset,\n * because a docs bundle compiles its origins in — a wrong value points every reader\n * at the wrong host instead of failing.\n *\n * Local values are derived here, exactly as `VITE_API_BASE_URL` is, so a developer\n * building the docs locally needs no manual wiring. Remote environments author\n * `documentationSite` in `wildo.infra.<env>.config.ts`, which the documentation image's\n * build arguments and the CI workflow read under the same three names, straight from the\n * loaded descriptor (`ConfigSyncCommand`, `ci-workflow-generator.service.ts`). No runtime\n * environment carries them (#2310).\n */\n if (!apiProxyTarget) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no backend API port to bind documentation site '${service.serviceName}' to WILDO_DOCS_API_BASE_URL.`,\n );\n }\n const saasAppPort = runtimeTarget.frontendServices\n .find((frontend) => frontend.frontendType === AppFrontendType.SAAS_APP)?.defaultPort;\n if (!saasAppPort) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no SaaS application frontend port to bind documentation site '${service.serviceName}' to WILDO_DOCS_APP_URL. `\n + 'The documentation site deep-links anonymous readers to the SaaS app to sign in.',\n );\n }\n // The docs site is itself served plain http locally, so addressing the backend port directly\n // raises no mixed-content problem and needs no proxy of its own.\n envExample[PlatformDocumentationSiteEnvKeys.WILDO_DOCS_API_BASE_URL] = apiProxyTarget;\n // This one points at the SaaS APP, which IS the edge — so it carries the edge scheme. Left as\n // http it deep-links every anonymous reader at a port that no longer answers.\n envExample[PlatformDocumentationSiteEnvKeys.WILDO_DOCS_APP_URL] =\n `http://localhost:${saasAppPort}`;\n envExample[PlatformDocumentationSiteEnvKeys.WILDO_DOCS_FRONTEND_SERVICE_NAME] = service.serviceName;\n }\n\n return {\n serviceName: service.serviceName,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n envExample,\n };\n });\n }\n\n /**\n * Project local authored operator posture into the app-root `.env` target.\n *\n * The generated `config.json` snapshot is the input here. The `.env` file is\n * only a disposable process boundary and is regenerated by both config sync\n * and dev start. Run identity is intentionally absent: the verification\n * supervisor mints it per invocation rather than accepting authored state.\n */\n static buildApplicationOperatorEnvTargets(input: {\n env: PlatformEnvironmentConfiguration;\n config: PlatformEnvConfigJson;\n saasRoot: string;\n }): ApplicationOperatorEnvTarget[] {\n const verification = input.config.applicationCreationVerification;\n if (input.env.locationType !== WildoLocationType.LOCAL) {\n if (verification === undefined) return [];\n throw new Error('Application-creation verification operator environment is local-only.');\n }\n\n return [{\n applicationRoot: resolve(input.saasRoot),\n ...(verification === undefined\n ? { disposition: ApplicationOperatorEnvFileDisposition.REMOVE }\n : {\n disposition: ApplicationOperatorEnvFileDisposition.WRITE,\n env: {\n [ApplicationCreationVerificationEnvKey.EVIDENCE_DIRECTORY]: verification.evidenceDirectory,\n [ApplicationCreationVerificationEnvKey.SILENT]: String(verification.silent),\n },\n }),\n }];\n }\n}\n"]}
1
+ {"version":3,"file":"app-bootstrap.service.js","sourceRoot":"","sources":["../../../../src/services/application/app-bootstrap.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,8BAA8B,EAAE,MAAM,0DAA0D,CAAC;AAC1G,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,O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C;wBACA,WAAW,EAAE,qCAAqC,CAAC,KAAK;wBACxD,GAAG,EAAE;4BACH,CAAC,qCAAqC,CAAC,kBAAkB,CAAC,EAAE,YAAY,CAAC,iBAAiB;4BAC1F,CAAC,qCAAqC,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC;yBAC5E;qBACF,CAAC;aACL,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { devCompanionRuntimeEndpointKey } from '~wildo-cli/services/environment/platform-runtime.schemas';\nimport { existsSync, readFileSync } from 'fs';\nimport { isAbsolute, join, relative, resolve } from 'path';\nimport type { AppConfiguration_BackendAuthored } from '@wildo-ai/saas-backend-lib';\nimport { RuntimeEnvironment, WildoHeaderKeys } from '@wildo-ai/saas-models';\nimport {\n buildAppBootstrapCredentialsResponse,\n APPS_MANAGER_ADMIN_SECRET_HEADER,\n APPS_MANAGER_API_PREFIX,\n AppFrontendType,\n PlatformDocumentationSiteEnvKeys,\n ApplicationCreationVerificationEnvKey,\n type AdminAppManagedDeclaration,\n type AppBootstrapCredentials,\n type AppBootstrapFirstAdminSeed,\n AdminAppInitializeRequestSchema,\n type ApplicationBackingServiceAddressing,\n AdminAppInitializeResponseSchema,\n AdminAppReapplyDeclarationRequestSchema,\n AdminAppReapplyDeclarationResponseSchema,\n buildRegistryKeyRevokePath,\n buildAdminKeyringRotationPath,\n buildAdminApplicationSigningKeyRotationPath,\n buildAdminApplicationSigningKeysPath,\n buildAdminApplicationSigningKeyPromotePath,\n buildAdminApplicationSigningKeyStagePath,\n ApplicationSigningKeyPromoteRequestSchema,\n ApplicationSigningKeyStageRequestSchema,\n type ApplicationSigningKeyPromoteRequest,\n type ApplicationSigningKeyStageRequest,\n ApplicationSigningKeyRotationRequestSchema,\n ApplicationSigningKeyRotationResponseSchema,\n ApplicationSigningKeysStatusSchema,\n type ApplicationSigningKeyRotationRequest,\n type ApplicationSigningKeyRotationResponse,\n type ApplicationSigningKeysStatus,\n buildAdminApplicationLegacyEnvelopeKeyPath,\n buildAdminApplicationLegacyEnvelopeKeyRestorePath,\n buildAdminApplicationLegacyEnvelopeKeyRetirePath,\n ApplicationLegacyEnvelopeKeyResponseSchema,\n ApplicationLegacyEnvelopeKeyRestoreRequestSchema,\n ApplicationLegacyEnvelopeKeyRetirementRequestSchema,\n ApplicationLegacyEnvelopeKeyStatusSchema,\n type ApplicationLegacyEnvelopeKeyResponse,\n type ApplicationLegacyEnvelopeKeyRestoreRequest,\n type ApplicationLegacyEnvelopeKeyRetirementRequest,\n type ApplicationLegacyEnvelopeKeyStatus,\n KeyringRotationRequestSchema,\n KeyringRotationResponseSchema,\n type KeyringRotationRequest,\n type KeyringStatus,\n REGISTRY_KEYS_ADMIN_PATH,\n RegistryKeyListResponseSchema,\n RegistryKeyMintRequestSchema,\n RegistryKeyMintResponseSchema,\n RegistryKeyRevokeRequestSchema,\n type RegistryKeyMintRequest,\n type RegistryKeyListResponse,\n type RegistryKeyMintResponse,\n type AdminAppReapplyDeclarationResponse,\n AppBootstrapCredentialsResponseSchema,\n buildAdminInitializeApplicationPath,\n buildAdminReapplyDeclarationPath,\n buildAdminDeregisterApplicationPath,\n buildAdminApplicationResiduePath,\n buildAdminApplicationScheduledJobsPath,\n buildAdminApplicationScheduledJobRunPath,\n ApplicationScheduledJobsResponseSchema,\n ApplicationScheduledJobRunRequestSchema,\n ApplicationScheduledJobRunResponseSchema,\n type ApplicationScheduledJobsResponse,\n type ApplicationScheduledJobRunRequest,\n type ApplicationScheduledJobRunResponse,\n buildAdminRestoreApplicationPath,\n buildAppBootstrapCredentialsPath,\n buildLocalhostApplicationRuntimeEndpoints,\n selectPrimaryBackendService,\n buildK8sApplicationRuntimeEndpoints,\n buildComposeApplicationRuntimeEndpoints,\n buildK8sApplicationIngressRoutes,\n buildK8sInternalUrl,\n APP_RUNTIME_SUBDIR_NAMES,\n type K8sIngressRoute,\n ConfigModuleResolution,\n loadConfig,\n resolveAppLayout,\n WildoDeploymentRuntime,\n WildoLocationType,\n WORKSPACE_HOME_NAMES,\n WORKER_CONFIG_FILENAME,\n MINION_CONFIG_FILENAME,\n WildoWorkerConfigSchema,\n WildoMinionConfigSchema,\n ApplicationRuntimePrincipalKind,\n buildMinionRedisKeyPrefix,\n registerMinionLocalProviders,\n buildRuntimePrincipalKey,\n DEVELOPMENT_COMPANION_PRINCIPAL,\n enumerateRuntimePrincipalsWithBootstrapSecrets,\n runtimeEnvironmentHostsDevelopmentCompanion,\n type ApplicationRuntimePrincipal,\n DatabaseEngine,\n resolveApplicationDatabaseEngine,\n AppDatabaseSeedingPhase,\n AppDatabaseSeedingOutcome,\n type BackingServiceKind,\n} from '@wildo-ai/platform-config-lib';\nimport { buildWorkerInternalUrl, buildWorkerLocalUrl } from '@wildo-ai/platform-core-shared';\nimport type { PlatformEnvSecretsJson } from '~wildo-cli/services/credentials/credentials.schemas';\nimport type { PlatformEnvConfigJson } from '~wildo-cli/services/credentials/credentials.schemas';\nimport type { PlatformEnvironmentConfiguration } from '~wildo-cli/services/environment/environment.schemas';\nimport { resolveApplicationBackingServiceAddressing } from '~wildo-cli/services/environment/application-backing-service-addressing.utils';\nimport type {\n ApplicationBackendEnvTarget,\n CompanionPlatformEnvTarget,\n ApplicationFrontendEnvExampleTarget,\n ApplicationOperatorEnvTarget,\n ApplicationWorkerEnvTarget,\n ApplicationMinionEnvTarget,\n K8sPodPort,\n} from '~wildo-cli/services/environment/env-configuration-generator.service';\nimport { ApplicationOperatorEnvFileDisposition } from '~wildo-cli/services/environment/env-configuration-generator.service';\nimport { AddressPerspective, ServiceAddressResolver } from '~wildo-cli/services/catalog/service-address-resolver.service';\nimport { buildAppsManagerDiagnosticMessage } from '~wildo-cli/services/deployment/apps-manager-diagnostics.service';\nimport { ErrorUtils } from '~wildo-cli/infrastructure/errors/error.utils';\nimport { EnvironmentUtils } from '~wildo-cli/services/environment/environment.service';\nimport { AppRuntimeTargetsService, type ResolvedAppRuntimeTarget } from './app-runtime-targets.service';\nimport { applyAppSchemaMigrations, resolveAppMigrationsDirectory } from './app-schema-bootstrap.service';\nimport { applyTunnelToRuntimeEndpoints, readLiveApplicationTunnel } from './local-tunnel.service';\n\n\n/**\n * Budget for a LIGHT apps-manager call — a read, or an idempotent config re-source.\n *\n * Short on purpose: for an operation that should answer in well under a second, a short budget is\n * what gives the timeout its diagnostic value. It says \"apps-manager is not answering\", and it says\n * it quickly.\n */\nconst APPS_MANAGER_TIMEOUT_MS = 15_000;\n\n/**\n * Budget for `POST /admin/apps/:appSlug/initialize` — a HEAVY, long-running provisioning call.\n *\n * ## Why this is not the same number as above\n *\n * Both budgets used to be one constant, and that conflated two unrelated questions: \"is apps-manager\n * unresponsive?\" and \"is apps-manager doing a long job it is supposed to be doing?\". Initialization\n * provisions the application database and its user, mints runtime-principal credentials, reconciles\n * ACLs, connects, and constructs the application's ENTIRE repository registry — ensuring every\n * declared index on every resource.\n *\n * Measured on Wonder Todos, 2026-08-19, on a machine where nothing was wrong: **12.2s** and **21.5s**\n * for the same call on two runs, against an application database holding 95 collections and 514\n * indexes. Both exceeded 15s, so `wildo local dev` aborted the whole session — and did so at the\n * point where the CLI kills the process tree, which made a healthy platform look like a failed one.\n *\n * Note the cost is NOT first-run index CREATION: those 514 indexes already existed. Ensuring them is\n * re-paid on every initialize, so the budget has to cover the steady state, not a cold start.\n *\n * ## Why raising the SHARED constant would have been the wrong fix\n *\n * It would have bought this call its headroom by taking detection value away from the two light\n * calls, which would then need the full budget to report an apps-manager that is simply dead.\n * A budget belongs to an operation, not to a client.\n *\n * The value is deliberately generous rather than tuned to the measurement: the work scales with the\n * application's resource count, and a larger app, a cold page cache or a loaded machine can be\n * several times slower without anything being wrong. It is still bounded, so a genuinely hung\n * apps-manager is reported well inside an interactive session.\n */\nconst APPS_MANAGER_INITIALIZE_TIMEOUT_MS = 180_000;\n\n/**\n * Per-OPERATION budget for withdrawing an application and restoring it (#1307).\n *\n * Both now act on every backing server once per runtime principal — delete or re-create a Redis ACL user, a\n * broker user, a MongoDB user and role (on Atlas, several Admin API round trips each) and a PostgreSQL role — so the\n * 15s liveness budget could expire while apps-manager was still revoking. The operator would then see a timeout\n * instead of the list of credentials still live, and the work would carry on unobserved. Same reasoning as\n * {@link APPS_MANAGER_INITIALIZE_TIMEOUT_MS}: a budget belongs to an operation, not to a client. Shorter than\n * initialization because nothing here builds a repository registry.\n */\nconst APPS_MANAGER_CREDENTIAL_LIFECYCLE_TIMEOUT_MS = 120_000;\n\n/**\n * `waitForPlatformServicesReady` gates entry into registered-app bootstrap on\n * apps-manager answering `/health/ready`, but that check and this request are\n * two separate round-trips: apps-manager can pass readiness and then crash\n * (observed 2026-08-06: an uncaught exception from an unrelated OTel\n * telemetry batch-flush timer killed apps-manager seconds after it reported\n * ready) before the registration POST lands, producing an immediate\n * connection-refused \"fetch failed\" that aborted the whole `wildo local dev`\n * session. `platform-lifecycle.service.ts`'s runtime supervisor auto-respawns\n * a crashed platform service within seconds, so a bounded reconnect-wait here\n * — NOT a soft-success, still fails hard on HTTP error responses and after\n * this budget is exhausted — turns a transient crash/respawn window into a\n * short, silent retry instead of a hard command failure.\n */\nconst APPS_MANAGER_RECONNECT_ATTEMPTS = 2;\nconst APPS_MANAGER_RECONNECT_WAIT_MS = 30_000;\nconst APPS_MANAGER_RECONNECT_POLL_INTERVAL_MS = 1_000;\n\n/**\n * Has apps-manager answered AT ALL during this process?\n *\n * The reconnect window above is for a crash/RESPAWN — its own contract says apps-manager \"can pass\n * readiness and then crash\". Riding that out presupposes it was up. When it was never up there is\n * nothing to respawn, and waiting only postpones a conclusion the first `ECONNREFUSED` already\n * reached.\n *\n * Measured 2026-08-28: `wildo config sync` against a deliberately stopped platform took ~3.5\n * minutes, of which ~120 seconds was this wait — `prepareApplicationEnvTargets` is reached by four\n * target builders, and each burned the full 30-second deadline before giving up. The command then\n * degraded to `reconstructBootstrapCredentialsOffline` exactly as designed, so the two minutes\n * bought nothing: the offline path was always going to be taken. Running `config sync` with the\n * platform down is not an error state — it is how an operator regenerates env files between\n * sessions.\n *\n * Process-scoped rather than per-call, because the point is whether THIS run ever established that\n * a platform is there. A stale value cannot outlive the command.\n */\nlet appsManagerAnsweredThisRun = false;\n\n/**\n * Record that apps-manager has been OBSERVED reachable in this process.\n *\n * Called by every successful fetch here and by `waitForServiceReady` in `platform-lifecycle.service.ts`\n * whenever the service it proved ready is apps-manager — so BOTH readiness barriers\n * (`waitForAppsManagerReady` and the `waitForPlatformServicesReady` that `wildo local dev` uses)\n * record it. The readiness barrier is the reason this is exported rather than private. The reconnect window exists for the\n * gap that barrier itself documents — apps-manager \"can pass readiness and then crash\" before the\n * registration POST lands — so the very case the retry is FOR is one where the only proof the\n * platform was up came from a probe that never went through `fetchWithReconnect`. Keying the skip\n * solely on this module's own successes would therefore have removed the retry from the one window\n * it was written for, and the pinned crash/respawn test caught exactly that.\n */\nexport function markAppsManagerObservedReachable(): void {\n appsManagerAnsweredThisRun = true;\n}\n\n/**\n * Why a deploy-artifact build could not reach a usable apps-manager (issue #279).\n *\n * A closed vocabulary with a named home, because the two REACHABLE-but-unusable cases mean\n * opposite things to a creator and the old code could tell neither: it reported both as\n * \"Failed to prepare application deploy artifacts: … Check PLATFORM_ADMIN_SECRET\", which is the\n * wrong remedy for both.\n */\nexport enum AppsManagerUnavailableReason {\n /** Nothing answered: no platform is running for this application yet — the fresh-creator case. */\n PLATFORM_NOT_RUNNING = 'PLATFORM_NOT_RUNNING',\n /**\n * Something answered and refused our credentials. On a shared development host this is very\n * rarely a wrong secret: it is ANOTHER application's platform occupying the port.\n */\n PLATFORM_NOT_OURS = 'PLATFORM_NOT_OURS',\n}\n\n/**\n * Classify a deploy-artifact failure, or `null` when it is neither of the known benign shapes.\n *\n * `null` is the important return: a genuine defect must keep failing the command. Only the two\n * cases a first-time creator legitimately hits are skippable, and they are skippable because the\n * artifacts that step produces are CI deploy inputs under `.wildo-saas/deploy/` — nothing\n * `wildo local up` needs, which is why the phase's other outputs (compose, env files, provider\n * runtime) are complete and correct without them.\n */\nexport function classifyAppsManagerUnavailable(error: unknown): AppsManagerUnavailableReason | null {\n const message = error instanceof Error ? error.message : String(error ?? '');\n // 401/403 — `requestJson` names this exactly, and it is the only place that phrasing is produced.\n if (message.includes('rejected bootstrap authentication')) return AppsManagerUnavailableReason.PLATFORM_NOT_OURS;\n\n // Connection-shaped failures. `fetch` wraps the cause, so the code can sit one or two levels down.\n const codes: string[] = [];\n let cursor: unknown = error;\n for (let depth = 0; depth < 4 && cursor instanceof Error; depth += 1) {\n const code = (cursor as NodeJS.ErrnoException).code;\n if (typeof code === 'string') codes.push(code);\n if ((cursor as Error).name) codes.push((cursor as Error).name);\n cursor = (cursor as { cause?: unknown }).cause;\n }\n const connectionShaped = ['ECONNREFUSED', 'ENOTFOUND', 'ECONNRESET', 'EHOSTUNREACH', 'ETIMEDOUT', 'AbortError', 'TimeoutError'];\n if (codes.some((code) => connectionShaped.includes(code))) return AppsManagerUnavailableReason.PLATFORM_NOT_RUNNING;\n if (/fetch failed|ECONNREFUSED|timed? out|was aborted/i.test(message)) return AppsManagerUnavailableReason.PLATFORM_NOT_RUNNING;\n\n return null;\n}\n\n/**\n * Progress for a wait a human is sitting through. stderr, not stdout: callers parse stdout, and a\n * silent multi-second stall is exactly what made this cost so long to explain.\n */\nfunction reportAppsManagerWait(message: string): void {\n process.stderr.write(` ${message}\\n`);\n}\n\n/**\n * Coerce a service key (e.g. `backendApi`) into a K8s-valid port name:\n * lowercase, only `[a-z0-9-]`, no leading/trailing `-`, ≤15 chars (the\n * IANA/K8s `IS_DNS1123_LABEL`-for-ports limit). `backendApi` → `backend-api`.\n * Empty/degenerate input falls back to `port`.\n */\nfunction toK8sPortName(raw: string): string {\n const kebab = raw\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n const trimmed = kebab.slice(0, 15).replace(/-+$/g, '');\n if (trimmed.length === 0) return 'port';\n // K8s port names are IANA_SVC_NAME — they MUST contain at least one letter.\n // An all-numeric service key (e.g. '123') would otherwise emit an invalid\n // port name that kubectl rejects; prefix it to guarantee an alpha char.\n if (!/[a-z]/.test(trimmed)) return `p-${trimmed}`.slice(0, 15);\n return trimmed;\n}\n\nfunction buildLocalRuntimeEndpoint(url: string): { publicUrl: string; internalUrl: string } {\n return {\n publicUrl: url,\n internalUrl: url,\n };\n}\n\nfunction resolveRuntimeEnvironment(\n env: PlatformEnvironmentConfiguration,\n config: PlatformEnvConfigJson | null,\n): RuntimeEnvironment {\n if (config?.runtimeEnvironment) {\n return config.runtimeEnvironment;\n }\n\n if (env.runtimeEnvironment) {\n return env.runtimeEnvironment;\n }\n\n throw new Error(\n `Environment '${env.name}' is missing explicit runtime semantics. Set runtimeEnvironment in config.json or in the environment registry before bootstrapping applications.`,\n );\n}\n\nasync function readErrorBody(response: Response): Promise<string> {\n try {\n const body = await response.text();\n return body.trim();\n } catch {\n return '';\n }\n}\n\nexport interface RegisteredApplicationEnvTargetInput {\n env: PlatformEnvironmentConfiguration;\n credentials: PlatformEnvSecretsJson;\n saasRoot: string;\n config?: PlatformEnvConfigJson | null;\n requestedAppSlug?: string | undefined;\n}\n\n/** One authoritative application-registration/credential snapshot used by every runtime projection. */\n/**\n * What one registration call (`POST /admin/apps/:slug/initialize`) reported.\n *\n * Both fields are `undefined` when apps-manager predates them — \"not reported\", never \"nothing\n * happened\" — which is why neither is defaulted here.\n */\nexport interface ApplicationRegistrationOutcome {\n /** What provisioning did about the application's own bootstrap rows. */\n appDatabaseSeeding: AppDatabaseSeedingOutcome | undefined;\n /** The declaration slices this registration applied to the stored config. */\n declarationConvergedFields: string[] | undefined;\n}\n\nexport interface PreparedApplicationEnvTargets {\n runtimeTarget: ResolvedAppRuntimeTarget;\n bootstrapCredentials: AppBootstrapCredentials;\n /**\n * The declaration slices THIS run's registration applied to the stored config (both provisioning\n * phases, de-duplicated). `undefined` when no registration reported it: a degraded run (which never\n * registered) or an apps-manager predating the field. Lets `wildo local dev` name the edit it applied.\n */\n declarationConvergedFields?: string[] | undefined;\n /**\n * True when apps-manager was UNREACHABLE and the credentials were reconstructed\n * from material already on disk (Step: degraded env generation).\n *\n * Callers MUST surface this. A `.env` that looks current but was written without\n * consulting the control plane is the same \"correct and believed otherwise\"\n * failure as a silent partial sync, pointing the other way — and the one thing a\n * degraded run cannot know is whether apps-manager holds material the runtime\n * does not yet have.\n */\n degraded?: boolean;\n /**\n * Principals that could NOT be regenerated offline, each naming itself and the\n * `.env` it expected. Non-empty only in degraded mode.\n *\n * These are OMITTED from `runtimePrincipalCredentials` rather than faked, so\n * `requireRuntimePrincipalCredentials` still refuses to substitute the\n * application backend's identity for them. The caller reports them; their\n * existing `.env` files are left untouched.\n */\n unresolvedPrincipals?: string[];\n /**\n * The runtime endpoints the application's runtimes receive. While a local tunnel is live (#3907) the tunnel's frontend\n * has the public origin as its `publicUrl` and its local origin in `additionalBrowserOrigins`.\n */\n runtimeEndpoints: Record<string, { publicUrl: string; internalUrl: string; additionalBrowserOrigins?: string[] }>;\n /**\n * The same endpoints WITHOUT the tunnel: the companion's. A tunnel coming up or down must never restart the companion\n * under a live run (#3493), and nothing the companion does needs the public origin.\n */\n companionRuntimeEndpoints: Record<string, { publicUrl: string; internalUrl: string }>;\n /**\n * The environment resolved during preparation, carried so per-runtime\n * credential fetches reuse it instead of re-deriving.\n *\n * Re-deriving imposed a NEW requirement on callers that construct a target\n * without a fully-populated env — `resolveRuntimeEnvironment` throws rather\n * than defaulting — and a second derivation could in principle disagree with\n * the first, which would fetch a different environment's credentials.\n */\n runtimeEnvironment: RuntimeEnvironment;\n /**\n * Each declared minion's and worker's OWN bootstrap credentials, keyed by\n * `buildRuntimePrincipalKey` (Step 1 / F11).\n *\n * Populated HERE rather than fetched inside the target builders for two\n * reasons. It keeps preparation the single credential-fetch phase — the\n * builders stay pure and a caller that supplies `prepared` needs no network.\n * And it makes the field REQUIRED, so a hand-constructed `prepared` has to\n * state what each runtime holds; an optional map would invite a fallback to\n * the application backend's credentials, which is precisely the collapse this\n * step removes.\n *\n * The application backend is NOT in the map — its credentials are\n * `bootstrapCredentials`.\n */\n runtimePrincipalCredentials: Record<string, AppBootstrapCredentials>;\n}\n\nexport interface ApplicationEnvProjectionInput extends RegisteredApplicationEnvTargetInput {\n /** Supplied by the coordinator so every target family is derived from one logical bootstrap generation. */\n prepared?: PreparedApplicationEnvTargets;\n}\n\n/** The residue probe's wire shape (#1556). `null` everywhere means \"could not ask\", never \"none\". */\nexport interface ApplicationResidueResponse {\n success: boolean;\n appSlug: string;\n applicationId: string | null;\n status: string;\n deregisteredAt: string | null;\n schedule: {\n scheduledForApplication: number | null;\n platformScheduledTotal: number | null;\n schedulerRunning: boolean | null;\n unavailableReason: string | null;\n };\n broker: {\n vhost: string | null;\n vhostExists: boolean | null;\n queueCount: number | null;\n queuedMessages: number | null;\n unavailableReason: string | null;\n };\n notInspected: string[];\n}\n\n/**\n * One principal's credential on one backing service, as apps-manager reports it (#1307). `service` is absent\n * when the entry names a whole principal — a minion re-minted by the reconcile, or one it could not reach.\n */\nexport interface ApplicationCredentialReportEntry {\n principalKey: string;\n service?: BackingServiceKind;\n}\n\n/** `POST /admin/apps/:appSlug/deregister` — the withdrawal and every credential it revoked. */\nexport interface ApplicationDeregistrationResponse {\n success: boolean;\n appSlug: string;\n applicationId: string;\n alreadyDeregistered: boolean;\n withdrawnJobs: number;\n deletedExecutions: number;\n revokedCredentials: ApplicationCredentialReportEntry[];\n /**\n * Broker credentials no running broker could revoke (#2303 slice D): minted before the platform moved to a profile that\n * runs no broker. Absent when there are none; each names its remedy.\n */\n unreachableCredentials?: Array<ApplicationCredentialReportEntry & { reason: string }>;\n}\n\n/** `POST /admin/apps/:appSlug/restore` — the restore and every credential it re-minted. */\nexport interface ApplicationRestoreResponse {\n success: boolean;\n appSlug: string;\n alreadyActive: boolean;\n ensuredCredentials: ApplicationCredentialReportEntry[];\n}\n\n/**\n * How the env projection evaluates `wildo.saas.config.ts` and each minion's and worker's own configuration: FRESH (see\n * `AppBootstrapService.readAuthoredConfig`) and against the CLI's own built framework packages\n * ({@link ConfigModuleResolution.LOADER_INSTANCES}, #3440).\n *\n * These reads ask only what the files DECLARE (runtimes, their paths, access, provider scopes, isolation, liveness), the\n * question the compose render asks of the same files with the same mode (#3646). A fresh read in the loader's inferred\n * mode re-evaluates the framework from SOURCE every time: measured 2026-11-18 on Wonder Todos, 1.1–1.3 s per read,\n * which for an application with five minions and a worker is about ten seconds added to every regeneration; with this\n * mode the same fresh read took 2–23 ms. These files import framework packages and, at most, an application's role\n * enums; none defines a zod schema of its own, so the decorated-zod caveat of that mode does not arise.\n */\nconst RUNTIME_DECLARATION_EVALUATION = { moduleResolution: ConfigModuleResolution.LOADER_INSTANCES } as const;\n\nexport class AppBootstrapService {\n /**\n * Service keys (`config.services.<key>`) of the app's frontends that are\n * CDN-served in this environment — authored `cdn?[key].enabled === true` in\n * `wildo.infra.<env>.config.ts`.\n *\n * A CDN-served frontend is served OFF-CLUSTER (its public host resolves via\n * DNS to a CDN edge fronting an object-storage bucket), so it is dropped from\n * BOTH the per-frontend nginx Deployment/Service\n * ({@link buildApplicationFrontendDeployTargets}) AND the ingress / compose\n * route ({@link buildApplicationIngressRoutes}). It is deliberately KEPT in\n * {@link buildRuntimeEndpoints} so `runtime.endPoints.publicUrl` still\n * advertises `<serviceHost>.<publicDomain>` — the browser gets the same URL,\n * it just resolves to the CDN. This advertised-but-not-ingress-routed\n * asymmetry IS the CDN opt-in: the coherence invariant relaxes from \"every\n * advertised host is routed by the ingress\" to \"…routed by the ingress OR\n * served by a CDN\". Maintained by construction here (ingress/deploy frontends\n * = all frontends − these keys; endpoints = all frontends).\n *\n * Keys on `enabled === true`, NOT mere presence, so an authored-but-disabled\n * entry falls back to normal nginx-pod serving (never silently drops a route).\n */\n private static cdnFrontendKeys(env: PlatformEnvironmentConfiguration): ReadonlySet<string> {\n return new Set(\n Object.entries(env.cdn ?? {})\n .filter(([, cdnConfig]) => cdnConfig.enabled)\n .map(([serviceKey]) => serviceKey),\n );\n }\n\n /**\n * The runtime endpoints, and the same endpoints with a live local tunnel applied (#3907). Only a LOCAL environment can\n * have a tunnel; a state file whose process is not running is ignored and named, so a crash or a reboot never leaves a\n * dead issuer advertised. See `local-tunnel.service.ts`.\n */\n private static buildRuntimeEndpointsWithTunnel(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): Pick<PreparedApplicationEnvTargets, 'runtimeEndpoints' | 'companionRuntimeEndpoints'> {\n const base = AppBootstrapService.buildRuntimeEndpoints(runtimeTarget, env);\n if (env.locationType === WildoLocationType.REMOTE) return { runtimeEndpoints: base, companionRuntimeEndpoints: base };\n const { live, staleReason } = readLiveApplicationTunnel(runtimeTarget.appRoot);\n if (staleReason) {\n // eslint-disable-next-line no-console\n console.warn(` ! The local tunnel state is ignored: ${staleReason}. Run \\`wildo local tunnel up\\` or \\`wildo local tunnel down\\`.`);\n }\n const applied = applyTunnelToRuntimeEndpoints(base, live);\n if (applied.skipped) {\n // eslint-disable-next-line no-console\n console.warn(` ! The local tunnel is not applied: ${applied.skipped}.`);\n }\n return { runtimeEndpoints: applied.endpoints, companionRuntimeEndpoints: base };\n }\n\n private static buildRuntimeEndpoints(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): Record<string, { publicUrl: string; internalUrl: string }> {\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n const primaryBackendPort = primaryBackend?.defaultPort;\n // Public frontends with the endpoints map key (`serviceName`) DECOUPLED from\n // the serviceHosts resolution key (`.key` = `config.services.<key>`). Keying\n // hosts on `serviceName` silently ignores authored `serviceHosts` (the\n // serviceName `wonder-todos-app` misses the authored `app` entry) and\n // diverges from the apps-manager ingress. See the domain plan.\n const publicFrontends = runtimeTarget.frontendServices.flatMap((frontend) =>\n frontend.defaultPort\n ? [{ serviceName: frontend.serviceName, serviceKey: frontend.key, port: frontend.defaultPort }]\n : [],\n );\n const frontendApplicationPorts = Object.fromEntries(\n publicFrontends.map((frontend) => [frontend.serviceName, frontend.port]),\n );\n const websiteFrontend = runtimeTarget.frontendServices.find(\n (frontend) => frontend.frontendType === AppFrontendType.STATIC_WEBSITE,\n );\n const docsFrontend = runtimeTarget.frontendServices.find(\n (frontend) => frontend.frontendType === AppFrontendType.TECH_DOC,\n );\n\n // Remote Kubernetes: serviceHosts-driven public subdomains of the operator's\n // OWN publicDomain (greenfield — no `{svc}-{slug}-{env}` fan-out); internal\n // URLs are the app's cluster-DNS Service. Local dev + compose stay on\n // localhost.\n const namespace = env.kubernetes?.namespace;\n if (\n env.runtime === WildoDeploymentRuntime.KUBERNETES &&\n env.locationType === WildoLocationType.REMOTE &&\n namespace\n ) {\n const runtimeEndpoints = buildK8sApplicationRuntimeEndpoints({\n publicDomain: env.publicDomain,\n namespace,\n serviceHosts: env.serviceHosts,\n appServiceName: runtimeTarget.appSlug,\n frontends: publicFrontends,\n websiteServiceKey: websiteFrontend?.key,\n technicalDocumentationServiceKey: docsFrontend?.key,\n mainBackendApiServiceKey: primaryBackend?.key,\n mainBackendApiPort: primaryBackendPort,\n });\n // Secondary backends ride the same app Service on their own port; the\n // dev companion is a local-only concept (omitted remotely).\n for (const backendService of runtimeTarget.backendServices) {\n if (!backendService.defaultPort) {\n continue;\n }\n const url = buildK8sInternalUrl(runtimeTarget.appSlug, backendService.defaultPort, namespace);\n runtimeEndpoints[backendService.serviceName] = { publicUrl: url, internalUrl: url };\n }\n return runtimeEndpoints;\n }\n\n // Remote Docker Compose: SAME serviceHosts-driven public subdomains as k8s\n // (so the Traefik ingress routes and `runtime.endPoints.publicUrl` agree —\n // the CORS invariant holds for compose too); internal URLs are the app\n // container's own name on the shared compose network. Must NOT fall through\n // to the localhost branch below, which would advertise localhost topology\n // for a remotely-served app.\n if (env.runtime === WildoDeploymentRuntime.DOCKER_COMPOSE && env.locationType === WildoLocationType.REMOTE) {\n const runtimeEndpoints = buildComposeApplicationRuntimeEndpoints({\n publicDomain: env.publicDomain,\n serviceHosts: env.serviceHosts,\n appServiceName: runtimeTarget.appSlug,\n frontends: publicFrontends,\n websiteServiceKey: websiteFrontend?.key,\n technicalDocumentationServiceKey: docsFrontend?.key,\n mainBackendApiServiceKey: primaryBackend?.key,\n mainBackendApiPort: primaryBackendPort,\n });\n // Secondary backends reachable at their own port on the app container\n // (`http://<appSlug>:<port>` on the shared compose network). No dev\n // companion remotely.\n for (const backendService of runtimeTarget.backendServices) {\n if (!backendService.defaultPort) {\n continue;\n }\n const url = `http://${runtimeTarget.appSlug}:${backendService.defaultPort}`;\n runtimeEndpoints[backendService.serviceName] = { publicUrl: url, internalUrl: url };\n }\n return runtimeEndpoints;\n }\n\n const runtimeEndpoints = buildLocalhostApplicationRuntimeEndpoints({\n mainBackendApiPort: primaryBackendPort,\n frontendApplicationPorts,\n websitePort: websiteFrontend?.defaultPort,\n });\n for (const backendService of runtimeTarget.backendServices) {\n if (!backendService.defaultPort) {\n continue;\n }\n\n runtimeEndpoints[backendService.serviceName] = buildLocalRuntimeEndpoint(\n `http://localhost:${backendService.defaultPort}`,\n );\n }\n if (runtimeTarget.localServiceAddresses?.devCompanion?.url) {\n runtimeEndpoints[devCompanionRuntimeEndpointKey(runtimeTarget.appSlug)] = buildLocalRuntimeEndpoint(\n runtimeTarget.localServiceAddresses.devCompanion.url,\n );\n }\n\n return runtimeEndpoints;\n }\n\n /**\n * serviceHosts-driven ingress routes for the app's public services — the\n * per-app deploy context shared by the k8s ingress + the compose Traefik lane\n * (`buildK8sApplicationIngressRoutes`, runtime-agnostic host→port). Remote\n * only; local has no reverse proxy. Coherent with the runtime endpoints\n * (same resolver + topology).\n */\n private static buildApplicationIngressRoutes(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): K8sIngressRoute[] {\n if (env.locationType !== WildoLocationType.REMOTE) {\n return [];\n }\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n // Host resolution keys on `.key` (config.services key), NOT serviceName —\n // matches the runtime endpoints + the operator's authored serviceHosts.\n // CDN-served frontends are EXCLUDED: their public host is served off-cluster\n // by the CDN, so no ingress rule (k8s) / Traefik router (compose) is emitted\n // for them — while they stay in `buildRuntimeEndpoints` (advertised host\n // preserved). See {@link cdnFrontendKeys}.\n const cdnKeys = AppBootstrapService.cdnFrontendKeys(env);\n const publicFrontends = runtimeTarget.frontendServices.flatMap((frontend) =>\n frontend.defaultPort && !cdnKeys.has(frontend.key)\n ? [{ serviceName: frontend.serviceName, serviceKey: frontend.key, port: frontend.defaultPort }]\n : [],\n );\n return buildK8sApplicationIngressRoutes({\n publicDomain: env.publicDomain,\n serviceHosts: env.serviceHosts,\n frontends: publicFrontends,\n mainBackendApiServiceKey: primaryBackend?.key,\n // Per-service model: the api host routes to the backend's OWN k8s Service\n // (its serviceName), not a shared app Service.\n mainBackendApiServiceName: primaryBackend?.serviceName,\n mainBackendApiPort: primaryBackend?.defaultPort,\n });\n }\n\n /**\n * Derive the BACKEND pod's container/Service ports (per-service deploy model),\n * per-app from the authored `services.<backendKey>.defaultPort`:\n * - the primary backend on `mainBackendApiPort` — the ONE port its process binds.\n * Frontends are NOT here — each is its own nginx Deployment/Service (see\n * `buildApplicationFrontendDeployTargets`). `healthPort` is that same port, the\n * listener serving `/health` and `/health/ready`, and drives the k8s probes. It\n * was `mainBackendApiPort - 1`, a declared \"health sibling\" no backend process\n * binds, so every probe failed (#1760); the four siblings (API − 1..4) are no\n * longer declared at all (#1783). Remote only (local has no app k8s deploy).\n *\n * Ports are de-duplicated by number and carry K8s-valid names (see\n * {@link toK8sPortName}); a name collision after sanitisation is disambiguated\n * with a numeric suffix so the emitted Service is always valid.\n */\n private static buildBackendPodPorts(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): { podPorts: K8sPodPort[]; healthPort: number | undefined } {\n if (env.locationType !== WildoLocationType.REMOTE) {\n return { podPorts: [], healthPort: undefined };\n }\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n const backendPort = primaryBackend?.defaultPort;\n\n const seenPorts = new Set<number>();\n const usedNames = new Set<string>();\n const podPorts: K8sPodPort[] = [];\n const add = (rawName: string, containerPort: number | undefined): void => {\n if (containerPort === undefined || seenPorts.has(containerPort)) return;\n seenPorts.add(containerPort);\n let name = toK8sPortName(rawName);\n if (usedNames.has(name)) {\n // Disambiguate on a collision. Truncate the base to leave room for the\n // `-NN` suffix WITHIN the 15-char K8s port-name cap — appending the\n // suffix through `toK8sPortName` again would just re-truncate it back to\n // the colliding base and spin forever. Result stays ≤15 chars.\n const base = name.slice(0, 12).replace(/-+$/g, '');\n let suffix = 2;\n while (suffix < 100 && usedNames.has(`${base}-${suffix}`)) suffix += 1;\n name = `${base}-${suffix}`;\n }\n usedNames.add(name);\n podPorts.push({ name, containerPort });\n };\n\n // Per-service model: the BACKEND pod exposes ONLY the primary backend's\n // port. The engine's HTTP server binds exactly one, and serves health,\n // webhooks, the OAuth provider and MCP as routes on it — the four \"sibling\"\n // ports (API − 1..4) this used to expose were bound by nothing (#1783).\n // Frontends are SEPARATE nginx Deployments\n // (see `buildApplicationFrontendDeployTargets`), so their ports are NOT\n // folded into this pod. (Non-primary backend services, if any, would become\n // their own Deployments — a multi-backend follow-up; wonder-todos has one.)\n if (backendPort !== undefined) {\n add('backend', backendPort);\n }\n\n return { podPorts, healthPort: backendPort };\n }\n\n /**\n * The app's public frontends as per-service k8s deploy targets — each becomes\n * its OWN nginx Deployment + Service. `serviceName` is both the k8s object name\n * and the built image name (`{registry}/{serviceName}:{tag}`); `port` is the\n * authored `defaultPort` the frontend Service exposes (forwarded to nginx :80).\n * Frontends without a `defaultPort` are non-served (skipped). CDN-served\n * frontends are ALSO skipped — they get no nginx pod at all (served\n * off-cluster; see {@link cdnFrontendKeys}). Remote only.\n */\n private static buildApplicationFrontendDeployTargets(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n env: PlatformEnvironmentConfiguration,\n ): Array<{\n serviceKey: string;\n serviceName: string;\n port: number;\n isolation: { runAsUser: number; runAsGroup: number; writablePaths: string[] };\n }> {\n if (env.locationType !== WildoLocationType.REMOTE) {\n return [];\n }\n const cdnKeys = AppBootstrapService.cdnFrontendKeys(env);\n return runtimeTarget.frontendServices.flatMap((frontend) =>\n frontend.defaultPort && !cdnKeys.has(frontend.key)\n ? [{\n serviceKey: frontend.key,\n serviceName: frontend.serviceName,\n port: frontend.defaultPort,\n // Already resolved at the config boundary — passed through, never\n // re-derived, so the k8s and compose lanes cannot disagree.\n isolation: {\n runAsUser: frontend.isolation.runAsUser,\n runAsGroup: frontend.isolation.runAsGroup,\n writablePaths: [...frontend.isolation.writablePaths],\n },\n }]\n : [],\n );\n }\n\n /**\n * Read a runtime's ALREADY-GENERATED `.env` for the one value that cannot be\n * derived offline: its bootstrap secret.\n *\n * Returns `null` when the file does not exist or carries no secret — which is\n * exactly the FIRST-RUN case, and the case that must NOT be papered over: a\n * runtime apps-manager has never registered has no Redis ACL user, no RabbitMQ\n * user and no database role either, so inventing an env for it would produce a\n * runtime that boots and is refused by every backing service.\n */\n private static readPersistedBootstrapSecret(envFilePath: string): string | null {\n if (!existsSync(envFilePath)) return null;\n for (const line of readFileSync(envFilePath, 'utf8').split('\\n')) {\n const match = line.match(/^PLATFORM_APPLICATION_PRIMARY_SECRET=(.+)$/);\n if (match) {\n const value = match[1]!.trim().replace(/^[\"']|[\"']$/g, '');\n return value.length > 0 ? value : null;\n }\n }\n return null;\n }\n\n /**\n * Rebuild {@link AppBootstrapCredentials} WITHOUT contacting apps-manager.\n *\n * Only ONE of the four fields is a secret. `APPLICATION_ID` is already persisted\n * by `saveApplicationRuntimeIdentity` for exactly this reason (this rebuild is\n * its consumer), and the apps-manager URL and environment are\n * local configuration. So a degraded regeneration reuses the secret the runtime\n * already holds and derives the rest, which is precisely what apps-manager would\n * have returned: it PRESERVES an existing principal's secret rather than\n * re-minting, because rotating it would break a running runtime.\n *\n * `null` means the material is not on disk. The caller must then fail for THAT\n * runtime and say so, rather than degrade the whole sync.\n */\n private static reconstructBootstrapCredentialsOffline(input: {\n envName: string;\n appSlug: string;\n runtimeEnvironment: RuntimeEnvironment;\n appsManagerUrl: string;\n envFilePath: string;\n }): AppBootstrapCredentials | null {\n const primarySecret = AppBootstrapService.readPersistedBootstrapSecret(input.envFilePath);\n const applicationId = EnvironmentUtils.loadApplicationRuntimeIdentity(input.envName)?.[input.appSlug]?.applicationId;\n if (!primarySecret || !applicationId) return null;\n return buildAppBootstrapCredentialsResponse({\n appSlug: input.appSlug,\n applicationId,\n primarySecret,\n appsManagerUrl: input.appsManagerUrl,\n environment: input.runtimeEnvironment,\n }).credentials;\n }\n\n /**\n * True only for a CONNECTION-level failure — apps-manager not listening.\n *\n * Deliberately NOT true for an HTTP error response or a timeout. A 4xx/5xx means\n * apps-manager IS running and rejected the request (bad admin secret, invalid\n * declaration); degrading there would hide a real error behind a reassuring\n * warning. A timeout is ambiguous and is left fatal for the same reason.\n */\n private static isAppsManagerUnreachable(error: unknown): boolean {\n return /Unable to reach apps-manager/.test(ErrorUtils.extractErrorMessage(error));\n }\n\n /**\n * Rebuild EVERY declared principal's credentials offline (Step: degraded env).\n *\n * A minion's or worker's secret is its OWN — that is the entire point of Step 1,\n * which replaced one shared `PLATFORM_APPLICATION_PRIMARY_SECRET` per application\n * with one per runtime. So each principal's value is read from ITS OWN `.env`,\n * located through the same `saasConfig.{minions,workers}.<name>.path` the target\n * builders already use.\n *\n * ⚠️ There is deliberately NO fallback to the application-level secret. Reusing\n * it here would make every runtime present the same identity at the apps-manager\n * door — precisely the F11 collapse Step 1 exists to have removed — and it would\n * do so silently, in a code path whose whole purpose is to be reassuring. A\n * principal whose own secret is not on disk THROWS, naming itself.\n */\n private static async reconstructRuntimePrincipalCredentialsOffline(input: {\n envName: string;\n runtimeTarget: ResolvedAppRuntimeTarget;\n runtimeEnvironment: RuntimeEnvironment;\n appsManagerUrl: string;\n /**\n * The application backend's secret, as resolved for this run. A principal whose `.env` still holds THIS value was\n * last written before it had an identity of its own (the development companion before #2941), so it is reported\n * unresolved rather than handed the backend's identity again.\n */\n applicationBackendSecret: string;\n }): Promise<{ credentials: Record<string, AppBootstrapCredentials>; unresolved: string[] }> {\n const saasConfig = await AppBootstrapService.readAuthoredConfig<{\n minions?: Record<string, { path: string }>;\n workers?: Record<string, { path: string }>;\n }>(input.runtimeTarget.saasConfigPath, RUNTIME_DECLARATION_EVALUATION);\n\n const entries: Array<readonly [string, AppBootstrapCredentials]> = [];\n const unresolved: string[] = [];\n for (const principal of enumerateRuntimePrincipalsWithBootstrapSecrets(input.runtimeTarget.managedDeclaration, {\n hostsDevelopmentCompanion: AppBootstrapService.hostsDevelopmentCompanion(input.runtimeTarget, input.runtimeEnvironment),\n })) {\n const name = principal.name ?? '';\n const relativePath = AppBootstrapService.runtimePrincipalRelativeDir(principal, input.runtimeTarget, saasConfig);\n const reconstructed = relativePath\n ? AppBootstrapService.reconstructBootstrapCredentialsOffline({\n envName: input.envName,\n appSlug: input.runtimeTarget.appSlug,\n runtimeEnvironment: input.runtimeEnvironment,\n appsManagerUrl: input.appsManagerUrl,\n envFilePath: join(input.runtimeTarget.appRoot, relativePath, '.env'),\n })\n : null;\n const credentials = reconstructed && reconstructed.PLATFORM_APPLICATION_PRIMARY_SECRET !== input.applicationBackendSecret\n ? reconstructed\n : null;\n if (!credentials) {\n // Per-runtime granularity: this principal cannot be regenerated offline,\n // but the OTHERS can. Omitting it from the map (rather than throwing)\n // leaves its existing `.env` untouched and lets every other runtime be\n // written — and the omission is REPORTED, not silent, by the caller.\n //\n // Omission is the safe representation: `requireRuntimePrincipalCredentials`\n // refuses to substitute the application backend's identity for a missing\n // entry, so a skipped principal can never end up with the wrong secret.\n unresolved.push(\n `${buildRuntimePrincipalKey(principal)}`\n + `${relativePath ? ` (expected its own secret in ${join(relativePath, '.env')})` : ' (no declared path)'}`,\n );\n continue;\n }\n entries.push([buildRuntimePrincipalKey(principal), credentials] as const);\n }\n return { credentials: Object.fromEntries(entries), unresolved };\n }\n\n /**\n * Whether this run writes a development companion's environment, and so fetches its own secret (#2941): the\n * environment is a development one (the platform mints a companion secret there and nowhere else) and the\n * application has a companion to write it for.\n */\n private static hostsDevelopmentCompanion(runtimeTarget: ResolvedAppRuntimeTarget, runtimeEnvironment: RuntimeEnvironment): boolean {\n return runtimeEnvironmentHostsDevelopmentCompanion(runtimeEnvironment)\n && existsSync(resolveAppLayout(runtimeTarget.appRoot).companionHome);\n }\n\n /** Where a principal's `.env` lives, relative to the application root; `undefined` when nothing declares one. */\n private static runtimePrincipalRelativeDir(\n principal: ApplicationRuntimePrincipal,\n runtimeTarget: ResolvedAppRuntimeTarget,\n saasConfig: { minions?: Record<string, { path: string }>; workers?: Record<string, { path: string }> },\n ): string | undefined {\n switch (principal.kind) {\n case ApplicationRuntimePrincipalKind.MINION:\n return saasConfig.minions?.[principal.name ?? '']?.path;\n case ApplicationRuntimePrincipalKind.WORKER:\n return saasConfig.workers?.[principal.name ?? '']?.path;\n case ApplicationRuntimePrincipalKind.DEVELOPMENT_COMPANION:\n return AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, resolveAppLayout(runtimeTarget.appRoot).companionHome, `Application companion for '${runtimeTarget.appSlug}'`,\n );\n case ApplicationRuntimePrincipalKind.APPLICATION_BACKEND:\n // The backend's credentials are `bootstrapCredentials`, never a per-principal entry.\n return undefined;\n }\n }\n\n static async prepareApplicationEnvTargets(\n input: RegisteredApplicationEnvTargetInput,\n ): Promise<PreparedApplicationEnvTargets | null> {\n const runtimeTarget = await AppBootstrapService.resolveRuntimeTarget({ ...input, environmentName: input.env.name });\n if (!runtimeTarget) {\n return null;\n }\n\n await AppBootstrapService.validateFirstAdminSeedAgainstBackendConfig(runtimeTarget);\n\n if (runtimeTarget.backendServices.length === 0) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no backend services to prepare. Check wildo.saas.config.ts service definitions.`,\n );\n }\n\n const config = input.config ?? EnvironmentUtils.loadConfigJson(input.env.name);\n if (!config) {\n throw new Error(`No config for '${input.env.name}'. Run 'wildo config sync' to generate config.json.`);\n }\n\n const runtimeEnvironment = resolveRuntimeEnvironment(input.env, config);\n\n /**\n * Where this application's broker and storage live (#1107), from the SAME function that writes\n * `RABBITMQ_VHOST` / `STORAGE_BUCKET` into its backend env. Hoisted for the same reason as\n * `applicationDatabaseDeclaration` below: both provisioning phases must send one value.\n */\n const backingServiceAddressing = resolveApplicationBackingServiceAddressing(config);\n\n /**\n * ## Breaking the provisioning ↔ schema cycle\n *\n * An application whose own resources persist to PostgreSQL cannot be seeded before its schema\n * exists, and its schema is produced by migration artifacts that only the tooling can read. So\n * provisioning runs in TWO phases with the schema apply between them:\n *\n * 1. register with `DEFERRED` — infrastructure, credentials and platform records; no app rows;\n * 2. apply the application's migrations through the shared runner;\n * 3. register again (idempotent, `REQUIRED`) — now the bootstrap rows land.\n *\n * Phase 3 is a full re-invocation rather than a narrow seed call ON PURPOSE: provisioning also\n * issues the per-role GRANTs, and a grant can only be issued on a table that exists. Running the\n * whole provision after the migrations is what gives every confined role (minions, workers) its\n * grants on the tables the migrations just created — a seed-only endpoint would have left them\n * ungranted and moved the failure into the first minion boot.\n *\n * MongoDB is untouched: no migrations directory means one phase, exactly as before.\n */\n /**\n * From the ALREADY-LOADED config.json rather than the registry record: `applicationDatabase` is\n * deliberately not round-tripped through `environments.json`, because nothing reads it off that\n * cache — see the note in `hydrateEnvironmentFromConfig` about fields the registry does not own.\n *\n * Hoisted to a local so BOTH provisioning phases send the identical declaration. Recomputing it\n * for the second call would be two spellings of one value, and a divergence would land on the\n * provisioner as a database rename mid-provision.\n */\n const applicationDatabaseDeclaration = {\n /*\n * RESOLVED, never forwarded as absent (#1571). An environment that authors no\n * `applicationDatabase` is a PostgreSQL application, and sending the resolved engine means\n * apps-manager, the schema bootstrap below and `env-vars-builder` cannot answer silence\n * differently — which is exactly how the 2026-09-15 incident happened.\n */\n engine: resolveApplicationDatabaseEngine(config.applicationDatabase),\n // The SAME authored value `env-vars-builder` emits as `POSTGRESQL_DATABASE`, so the\n // database the backend connects to and the one the provisioner creates are one name\n // from one source.\n databaseName: config.backingServices?.postgresql?.database,\n };\n\n /**\n * Two-phase provisioning applies only when a PostgreSQL schema must exist before the application\n * can be seeded — see {@link resolveAppSchemaMigrationsDirectory} for why the ENGINE, and not\n * merely the presence of the migrations directory, is half of that question.\n */\n const usesTwoPhaseProvisioning = AppBootstrapService.resolveAppSchemaMigrationsDirectory(\n runtimeTarget,\n applicationDatabaseDeclaration,\n ) !== undefined;\n\n let bootstrapResponse: { credentials: AppBootstrapCredentials };\n let degraded = false;\n let declarationConvergedFields: string[] | undefined;\n try {\n const firstPhase = await AppBootstrapService.ensureApplicationRegistered(input.env, input.credentials, {\n appSlug: runtimeTarget.appSlug,\n appDisplayName: runtimeTarget.appDisplayName,\n appDatabaseName: runtimeTarget.appDatabaseName,\n managedDeclaration: runtimeTarget.managedDeclaration,\n applicationDatabase: applicationDatabaseDeclaration,\n backingServiceAddressing,\n firstAdminSeed: runtimeTarget.firstAdminSeed,\n appDatabaseSeeding: usesTwoPhaseProvisioning\n ? AppDatabaseSeedingPhase.DEFERRED\n : AppDatabaseSeedingPhase.REQUIRED,\n });\n\n declarationConvergedFields = firstPhase.declarationConvergedFields;\n if (usesTwoPhaseProvisioning) {\n const secondPhase = await AppBootstrapService.completeDeferredAppDatabaseSeeding({\n env: input.env,\n credentials: input.credentials,\n runtimeTarget,\n applicationDatabase: applicationDatabaseDeclaration,\n backingServiceAddressing,\n firstPhaseOutcome: firstPhase.appDatabaseSeeding,\n });\n // The first phase converges; the second normally reports nothing. Union them so neither is lost.\n if (secondPhase?.declarationConvergedFields !== undefined) {\n declarationConvergedFields = [...new Set([...(declarationConvergedFields ?? []), ...secondPhase.declarationConvergedFields])];\n }\n }\n\n bootstrapResponse = await AppBootstrapService.fetchBootstrapCredentials(\n input.env,\n input.credentials,\n {\n appSlug: runtimeTarget.appSlug,\n runtimeEnvironment,\n },\n );\n } catch (error) {\n // Degrade ONLY when apps-manager is not listening, and ONLY when the\n // material is already on disk. Every other failure — an HTTP rejection, a\n // timeout, a first run with no persisted secret — stays fatal, because\n // degrading there would either hide a real error or fabricate an identity\n // no backing service recognises.\n if (!AppBootstrapService.isAppsManagerUnreachable(error)) throw error;\n const authoritativeBackend = AppBootstrapService.resolveAuthoritativeBackendTarget(runtimeTarget);\n const offline = authoritativeBackend\n ? AppBootstrapService.reconstructBootstrapCredentialsOffline({\n envName: input.env.name,\n appSlug: runtimeTarget.appSlug,\n runtimeEnvironment,\n appsManagerUrl: AppBootstrapService.getAppsManagerBaseUrl(input.env),\n // `path` is app-root-relative; the runtime target carries the root.\n envFilePath: join(runtimeTarget.appRoot, authoritativeBackend.path, '.env'),\n })\n : null;\n if (!offline) throw error;\n /*\n * Say what was skipped, and why. The degrade used to be silent past the reconnect line, which\n * dropped the one fact the next failure depends on: registration is what converges the stored\n * declaration (`/initialize` reapplies `wildo.saas.config.ts` unconditionally), so a degraded\n * run serves the STORED declaration, not the authored one. On 2026-10-01 that surfaced two\n * steps later as an \"out of generation\" verification failure that named neither cause.\n */\n reportAppsManagerWait(\n `Registration of '${runtimeTarget.appSlug}' did not reach apps-manager `\n + `(${ErrorUtils.extractErrorMessage(error)}). Writing runtime env from the credentials already on disk; `\n + 'wildo.saas.config.ts was NOT applied to the stored application config in this run.',\n );\n degraded = true;\n bootstrapResponse = { credentials: offline };\n }\n\n // Persist the apps-manager-minted APPLICATION_ID (a Mongo `_id`, NOT\n // derivable offline from the slug) so a degraded regeneration can rebuild\n // bootstrap credentials without re-contacting apps-manager\n // (`reconstructBootstrapCredentialsOffline`). This method is the single\n // credential-fetch choke point (every app-target builder funnels through\n // it), so one write here keeps the persisted identity fresh.\n EnvironmentUtils.saveApplicationRuntimeIdentity(\n input.env.name,\n runtimeTarget.appSlug,\n bootstrapResponse.credentials.APPLICATION_ID,\n );\n\n // The THIRD apps-manager call site, and the one the first draft missed: it sat\n // inside the return expression, outside the try above. Degrading two of three\n // calls moved the failure one step later rather than removing it.\n let runtimePrincipalCredentials: Record<string, AppBootstrapCredentials>;\n let unresolvedPrincipals: string[] = [];\n try {\n runtimePrincipalCredentials = await AppBootstrapService.fetchDeclaredRuntimePrincipalCredentials(\n input,\n runtimeTarget,\n runtimeEnvironment,\n );\n } catch (error) {\n if (!AppBootstrapService.isAppsManagerUnreachable(error)) throw error;\n const offlinePrincipals = await AppBootstrapService.reconstructRuntimePrincipalCredentialsOffline({\n envName: input.env.name,\n runtimeTarget,\n runtimeEnvironment,\n appsManagerUrl: AppBootstrapService.getAppsManagerBaseUrl(input.env),\n applicationBackendSecret: bootstrapResponse.credentials.PLATFORM_APPLICATION_PRIMARY_SECRET,\n });\n runtimePrincipalCredentials = offlinePrincipals.credentials;\n unresolvedPrincipals = offlinePrincipals.unresolved;\n degraded = true;\n\n // Report ALL unresolved principals at once, then fail.\n //\n // Why fail rather than skip: a skipped runtime would be SILENT here — this\n // service has no logger, and the sync command does not hold `prepared`, so\n // nothing would tell the operator that one runtime's `.env` was left stale.\n // Shipping a silent skip would trade a loud failure for exactly the\n // \"correct and believed otherwise\" defect this whole change exists to\n // remove. Granular WRITING is worth having, but only once the skip can be\n // reported — see the note in the plan; the mechanism is the existing\n // `input.prepared` passthrough, which lets the sync command prepare once\n // and read `unresolvedPrincipals` itself.\n //\n // What IS improved: every unresolved principal is named in one message\n // instead of failing on the first, so one run tells the operator the whole\n // list rather than one name per re-run.\n if (unresolvedPrincipals.length > 0) {\n throw new Error(\n `Cannot regenerate env files without apps-manager. `\n + `${unresolvedPrincipals.length} runtime principal(s) have no existing secret on disk:\\n`\n + unresolvedPrincipals.map((entry) => ` - ${entry}`).join('\\n')\n + `\\nA runtime apps-manager has never registered also has no Redis ACL user, no broker `\n + `user and no database role, so its env cannot be produced offline. Every OTHER runtime `\n + `could be regenerated — start apps-manager and re-run to write them all.`,\n );\n }\n }\n\n return {\n runtimeTarget,\n degraded,\n declarationConvergedFields,\n bootstrapCredentials: bootstrapResponse.credentials,\n ...AppBootstrapService.buildRuntimeEndpointsWithTunnel(runtimeTarget, input.env),\n runtimeEnvironment,\n runtimePrincipalCredentials,\n unresolvedPrincipals,\n };\n }\n\n private static resolveAuthoritativeBackendTarget(\n runtimeTarget: Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>,\n ) {\n if (!runtimeTarget || runtimeTarget.backendServices.length === 0) {\n return null;\n }\n\n return selectPrimaryBackendService(runtimeTarget.backendServices) ?? null;\n }\n\n private static resolveAuthoritativeBackendConfigPath(\n runtimeTarget: Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>,\n ): string | null {\n const backendTarget = AppBootstrapService.resolveAuthoritativeBackendTarget(runtimeTarget);\n if (!backendTarget || !runtimeTarget) {\n return null;\n }\n\n const candidatePaths = [\n resolve(runtimeTarget.appRoot, backendTarget.path, 'src', 'saas-config.backend.ts'),\n resolve(runtimeTarget.appRoot, backendTarget.path, 'src', 'config', 'app-config.backend.ts'),\n ];\n\n return candidatePaths.find((candidatePath) => existsSync(candidatePath)) ?? candidatePaths[0]!;\n }\n\n private static async validateFirstAdminSeedAgainstBackendConfig(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n ): Promise<void> {\n const projectedUserTypes = runtimeTarget.firstAdminSeed?.userTypes;\n if (!projectedUserTypes || projectedUserTypes.length === 0) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' is missing bootstrap.firstAdmin.userTypes in '${runtimeTarget.saasConfigPath}'. `\n + 'Declare the first-admin bootstrap seed before running bootstrap, sync, reinit, or dev start.',\n );\n }\n\n const authoritativeBackend = AppBootstrapService.resolveAuthoritativeBackendTarget(runtimeTarget);\n if (!authoritativeBackend) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' declares bootstrap.firstAdmin.userTypes but has no backend service to validate against.`,\n );\n }\n\n const backendConfigPath = AppBootstrapService.resolveAuthoritativeBackendConfigPath(runtimeTarget);\n if (!backendConfigPath || !existsSync(backendConfigPath)) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' declares bootstrap.firstAdmin.userTypes, but the authoritative backend config was not found at '${backendConfigPath ?? 'unknown'}' for service '${authoritativeBackend.serviceName}'.`,\n );\n }\n\n const backendConfig = await AppBootstrapService.readAuthoredConfig<AppConfiguration_BackendAuthored>(backendConfigPath);\n const declaredBackendUserTypes = new Set(Object.keys(backendConfig.userTypes ?? {}));\n const unknownUserTypes = projectedUserTypes.filter((userType) => !declaredBackendUserTypes.has(userType));\n\n if (unknownUserTypes.length > 0) {\n throw new Error(\n `Invalid bootstrap.firstAdmin.userTypes for application '${runtimeTarget.appSlug}': `\n + `[${unknownUserTypes.join(', ')}] not found in backend config '${backendConfigPath}'. `\n + `Declared backend userTypes: [${[...declaredBackendUserTypes].join(', ')}].`,\n );\n }\n }\n\n /**\n * A target's directory as a path relative to ITS application root — the anchor every env writer\n * joins it back onto (see `ApplicationRuntimeTargetAnchor`). Refuses a service path that escapes\n * the application: a `wildo.saas.config.ts` naming `../elsewhere` would otherwise have the CLI\n * write a `.env` into a directory the application does not own.\n */\n private static relativeToApplicationRoot(applicationRoot: string, targetDirectory: string, subject: string): string {\n const relativeDir = relative(resolve(applicationRoot), resolve(targetDirectory));\n if (relativeDir.startsWith('..') || isAbsolute(relativeDir)) {\n throw new Error(`${subject} is outside the application root and cannot receive generated .env files.`);\n }\n return relativeDir;\n }\n\n private static async resolveRuntimeTarget(input: {\n saasRoot: string;\n requestedAppSlug?: string | undefined;\n /** The environment the declaration is registered in; `null` when only the service topology is read. */\n environmentName: string | null;\n }) {\n return AppRuntimeTargetsService.resolve(input.saasRoot, {\n environmentName: input.environmentName,\n requestedAppSlug: input.requestedAppSlug,\n });\n }\n\n private static getAppsManagerBaseUrl(env: PlatformEnvironmentConfiguration): string {\n const addressContext = ServiceAddressResolver.fromEnvironment(env, AddressPerspective.HOST_FACING);\n const addresses = ServiceAddressResolver.resolve(addressContext);\n return `${addresses.platform.appsManager.url}${APPS_MANAGER_API_PREFIX}`;\n }\n\n private static getAdminSecret(credentials: PlatformEnvSecretsJson): string {\n return credentials.platform.adminSecret;\n }\n\n /**\n * Bounded, silent poll of apps-manager's own `/health/ready` (unversioned —\n * outside `APPS_MANAGER_API_PREFIX`, mirroring `waitForServiceReady` in\n * `platform-lifecycle.service.ts`). Used ONLY to ride out the crash/respawn\n * window documented on {@link APPS_MANAGER_RECONNECT_ATTEMPTS}; not a\n * general-purpose readiness wait — `wildo local dev`'s own platform-readiness\n * barrier already owns that responsibility before this service is entered.\n */\n /**\n * One reconnect PROBE, inside the poll loop.\n *\n * Short on purpose, and shorter than the loop's own budget: the caller already owns \"how long do\n * we wait for apps-manager\" through `APPS_MANAGER_RECONNECT_WAIT_MS`, so a probe that lingers\n * only eats that budget in one bite instead of polling with it. 5s is enough for a service on\n * this machine to answer a readiness route, and a probe that cannot is not ready.\n */\n private static readonly APPS_MANAGER_PROBE_TIMEOUT_MS = 5_000;\n\n private static async waitForAppsManagerReconnect(env: PlatformEnvironmentConfiguration): Promise<boolean> {\n const addressContext = ServiceAddressResolver.fromEnvironment(env, AddressPerspective.HOST_FACING);\n const addresses = ServiceAddressResolver.resolve(addressContext);\n const readyUrl = `${addresses.platform.appsManager.url.replace(/\\/$/, '')}/health/ready`;\n\n const deadline = Date.now() + APPS_MANAGER_RECONNECT_WAIT_MS;\n while (Date.now() < deadline) {\n try {\n const probe = await fetch(readyUrl, { signal: AbortSignal.timeout(AppBootstrapService.APPS_MANAGER_PROBE_TIMEOUT_MS), redirect: 'manual' });\n if (probe.ok) return true;\n } catch {\n // Connection still refused/reset — keep polling until the deadline.\n }\n await new Promise((resolve) => setTimeout(resolve, APPS_MANAGER_RECONNECT_POLL_INTERVAL_MS));\n }\n return false;\n }\n\n /**\n * Connects with a bounded reconnect-retry on connection-level failure only\n * (never on an HTTP error response, and never on a request timeout — both\n * are handled/thrown by the caller). See {@link APPS_MANAGER_RECONNECT_ATTEMPTS}.\n */\n private static async fetchWithReconnect(\n url: string,\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n init: RequestInit,\n /** Per-OPERATION budget. Defaults to the light-call budget; heavy calls pass their own. */\n timeoutMs: number = APPS_MANAGER_TIMEOUT_MS,\n ): Promise<Response> {\n for (let attempt = 0; ; attempt++) {\n try {\n const response = await fetch(url, {\n ...init,\n headers: {\n [APPS_MANAGER_ADMIN_SECRET_HEADER]: AppBootstrapService.getAdminSecret(credentials),\n ...(init.body ? { [WildoHeaderKeys.CONTENT_TYPE]: 'application/json' } : {}),\n ...(init.headers ?? {}),\n },\n signal: AbortSignal.timeout(timeoutMs),\n });\n // REACHABILITY, not success: an HTTP error response still proves a platform is listening,\n // which is the only question the reconnect decision asks.\n appsManagerAnsweredThisRun = true;\n return response;\n } catch (error) {\n if (error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')) {\n throw new Error(\n buildAppsManagerDiagnosticMessage({\n envName: env.name,\n summary: `Apps-manager request timed out after ${timeoutMs}ms at ${url}.`,\n }),\n );\n }\n\n /**\n * Never reached in this run ⇒ nothing to ride out. Fail now, and SAY so — the alternative\n * is a silent 30-second stall per call, four times over, ending in the same answer.\n */\n if (!appsManagerAnsweredThisRun) {\n reportAppsManagerWait(\n `apps-manager is not answering at ${AppBootstrapService.getAppsManagerBaseUrl(env)} and has not answered `\n + 'at any point in this run, so there is no crash/respawn to wait out. Continuing without it — a command '\n + 'that can use already-persisted material will; one that cannot will fail with its own diagnostic.',\n );\n throw new Error(\n buildAppsManagerDiagnosticMessage({\n envName: env.name,\n summary: `Unable to reach apps-manager at ${url}: ${ErrorUtils.extractErrorMessage(error)}.`,\n }),\n );\n }\n\n const canRetry = attempt < APPS_MANAGER_RECONNECT_ATTEMPTS;\n if (canRetry) {\n reportAppsManagerWait(\n `apps-manager stopped answering mid-run (attempt ${attempt + 1}/${APPS_MANAGER_RECONNECT_ATTEMPTS}) — `\n + `waiting up to ${APPS_MANAGER_RECONNECT_WAIT_MS / 1_000}s for the supervisor to respawn it...`,\n );\n if (await AppBootstrapService.waitForAppsManagerReconnect(env)) {\n reportAppsManagerWait('apps-manager is back; retrying.');\n continue;\n }\n reportAppsManagerWait('apps-manager did not come back within the window.');\n }\n\n throw new Error(\n buildAppsManagerDiagnosticMessage({\n envName: env.name,\n summary: `Unable to reach apps-manager at ${url}: ${ErrorUtils.extractErrorMessage(error)}.`,\n }),\n );\n }\n }\n }\n\n private static async requestJson(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n path: string,\n init: RequestInit = {},\n /** Per-OPERATION budget — see {@link APPS_MANAGER_INITIALIZE_TIMEOUT_MS}. */\n timeoutMs: number = APPS_MANAGER_TIMEOUT_MS,\n ): Promise<unknown> {\n const baseUrl = AppBootstrapService.getAppsManagerBaseUrl(env).replace(/\\/$/, '');\n const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n\n const response = await AppBootstrapService.fetchWithReconnect(url, env, credentials, init, timeoutMs);\n\n if (!response.ok) {\n if (response.status === 401 || response.status === 403) {\n throw new Error(\n 'Apps-manager rejected bootstrap authentication. Check PLATFORM_ADMIN_SECRET.',\n );\n }\n\n const errorBody = await readErrorBody(response);\n throw new Error(\n `Apps-manager request failed at ${url}: ${response.status} ${response.statusText}${errorBody ? ` - ${errorBody}` : ''}`,\n );\n }\n\n return response.json();\n }\n\n /**\n * The application's migration artifacts, or `undefined` when no PostgreSQL schema has to be\n * applied before the application can be seeded.\n *\n * BOTH conditions are required, and the engine is the one that was missing.\n *\n * The first revision keyed solely on the directory, reasoning that \"an application that HAS\n * migrations needs them applied whatever its declared engine says, because the declaration and the\n * artifacts are two statements that can disagree while only the artifacts can create a table.\"\n * That is false for a MongoDB application: the artifacts describe a POSTGRESQL schema for a store\n * it does not use. The engine declaration is precisely what decides whether any PostgreSQL schema\n * is needed at all.\n *\n * Measured 2026-08-23, flipping this application back to MongoDB for the control run: the\n * `backend-api/migrations` directory survives the flip (it is committed), so two-phase provisioning\n * engaged, deferred the seed, and then tried to migrate a PostgreSQL database that a MongoDB\n * install never creates. `wildo local dev` aborted during application bootstrap with the\n * application left deliberately unseeded — worse than the deadlock the two-phase flow exists to\n * break, because it also affects the engine that never had the problem.\n */\n private static resolveAppSchemaMigrationsDirectory(\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>,\n applicationDatabase: { engine: DatabaseEngine; databaseName?: string } | undefined,\n ): string | undefined {\n if (applicationDatabase?.engine !== DatabaseEngine.POSTGRESQL) return undefined;\n // `appRoot` IS the saas root — `resolveRuntimeTarget` derives `saasConfigPath` by joining the\n // config filename onto it — so it is the same anchor `wildo db migrate` resolves from.\n return resolveAppMigrationsDirectory(runtimeTarget.appRoot);\n }\n\n /**\n * Phase 2 + 3: apply the application's schema, then re-invoke provisioning so the deferred\n * bootstrap rows land and every per-role GRANT is issued over the tables that now exist.\n *\n * Fails closed at both ends, because every degradation here produces an application that looks\n * provisioned and cannot boot:\n *\n * - an apps-manager that did not honour the phase (it is older than the contract, so it reported\n * nothing) is NOT assumed to have seeded — the migrations still run, and the idempotent second\n * call still completes the seed;\n * - an apps-manager that reports anything other than `SEEDED` after the schema exists is a defect,\n * not a state to retry past.\n */\n private static async completeDeferredAppDatabaseSeeding(input: {\n env: PlatformEnvironmentConfiguration;\n credentials: PlatformEnvSecretsJson;\n runtimeTarget: NonNullable<Awaited<ReturnType<typeof AppBootstrapService.resolveRuntimeTarget>>>;\n applicationDatabase: { engine: DatabaseEngine; databaseName?: string } | undefined;\n backingServiceAddressing: ApplicationBackingServiceAddressing;\n firstPhaseOutcome: AppDatabaseSeedingOutcome | undefined;\n }): Promise<ApplicationRegistrationOutcome | undefined> {\n if (input.firstPhaseOutcome === AppDatabaseSeedingOutcome.NO_PERSISTENCE_TARGET) {\n /**\n * Nothing the tooling does next can seed this application — the target itself is missing, and\n * apps-manager has already logged why. Applying migrations would fail on a database that was\n * never provisioned, with a message about connectivity rather than about the real cause.\n */\n return undefined;\n }\n\n await applyAppSchemaMigrations({\n envName: input.env.name,\n saasRoot: input.runtimeTarget.appRoot,\n appliedBy: `cli:bootstrap:${input.runtimeTarget.appSlug}`,\n reportMissing: (message) => { throw new Error(message); },\n });\n\n const secondPhase = await AppBootstrapService.ensureApplicationRegistered(input.env, input.credentials, {\n appSlug: input.runtimeTarget.appSlug,\n appDisplayName: input.runtimeTarget.appDisplayName,\n appDatabaseName: input.runtimeTarget.appDatabaseName,\n managedDeclaration: input.runtimeTarget.managedDeclaration,\n applicationDatabase: input.applicationDatabase,\n backingServiceAddressing: input.backingServiceAddressing,\n firstAdminSeed: input.runtimeTarget.firstAdminSeed,\n appDatabaseSeeding: AppDatabaseSeedingPhase.REQUIRED,\n });\n\n const secondPhaseOutcome = secondPhase.appDatabaseSeeding;\n if (secondPhaseOutcome !== undefined && secondPhaseOutcome !== AppDatabaseSeedingOutcome.SEEDED) {\n throw new Error(\n `Application '${input.runtimeTarget.appSlug}' was not seeded after its schema was applied `\n + `(apps-manager reported '${secondPhaseOutcome}'). Its backend requires exactly one APPLICATION `\n + 'row and cannot boot without it.',\n );\n }\n return secondPhase;\n }\n\n static async ensureApplicationRegistered(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: {\n appSlug: string;\n appDisplayName: string;\n appDatabaseName?: string | undefined;\n managedDeclaration: AdminAppManagedDeclaration;\n /**\n * The application's own persistence engine, from the authored `applicationDatabase`.\n *\n * This is the CLI half of the door that did not exist: apps-manager's per-application\n * PostgreSQL provisioning is gated on `usePostgreSQL`, which nothing in the repository set\n * until 2026-08-19. Omitted means MongoDB, so an environment that authors nothing is unchanged.\n */\n applicationDatabase?: { engine: DatabaseEngine; databaseName?: string } | undefined;\n /**\n * The application's authored broker vhost and storage bucket (#1107). REQUIRED rather than\n * optional: a registration that omits it makes apps-manager provision this application under\n * the platform owner's values, which is the defect the field exists to remove.\n */\n backingServiceAddressing: ApplicationBackingServiceAddressing;\n firstAdminSeed?: AppBootstrapFirstAdminSeed | undefined;\n /**\n * WHEN apps-manager should seed the application's own database. See\n * {@link AppDatabaseSeedingPhase} for the circularity `DEFERRED` breaks.\n */\n appDatabaseSeeding?: AppDatabaseSeedingPhase | undefined;\n },\n ): Promise<ApplicationRegistrationOutcome> {\n const body = AdminAppInitializeRequestSchema.parse({\n name: input.appDisplayName,\n appDatabaseName: input.appDatabaseName,\n userEmail: credentials.admin.email,\n userFirstName: credentials.admin.firstName,\n userLastName: credentials.admin.lastName,\n userPassword: credentials.admin.password,\n /*\n * The SECOND administrator (#575), and this site was enumerated as \"read only — no change\n * expected\" when the CLI half landed. That was WRONG, and it is the site that matters most:\n * `applicationAccessGrants` has zero mentions under `platform/` — it is an ENGINE resource, so\n * the two-person rule bites inside the GENERATED APPLICATION, not on the platform plane. This\n * request is what carries an identity into that application's own database, where\n * `_getDefault_App_FirstUser` is the only writer of `APP_ADMIN_SUPER_ADMIN` at provisioning\n * time.\n *\n * Spread, so a `secrets.json` predating the `approver` block sends nothing at all rather than\n * four `undefined`s that would read as a half-stated identity at the door.\n */\n ...(credentials.approver\n ? {\n approverEmail: credentials.approver.email,\n approverFirstName: credentials.approver.firstName,\n approverLastName: credentials.approver.lastName,\n approverPassword: credentials.approver.password,\n }\n : {}),\n managedDeclaration: input.managedDeclaration,\n applicationDatabase: input.applicationDatabase,\n backingServiceAddressing: input.backingServiceAddressing,\n firstAdminSeed: input.firstAdminSeed,\n appDatabaseSeeding: input.appDatabaseSeeding,\n /**\n * Forward the authored `serviceAuth` snapshot mirrored from\n * `wildo.infra.<env>.config.ts`. Apps-manager seeds platform-managed\n * JWT TTLs from this when present, including re-registration of an existing app.\n * An omitted block preserves an existing policy; first registration uses schema defaults.\n */\n serviceAuth: env.serviceAuth,\n });\n\n const response = await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminInitializeApplicationPath(input.appSlug),\n {\n method: 'POST',\n body: JSON.stringify(body),\n },\n APPS_MANAGER_INITIALIZE_TIMEOUT_MS,\n );\n\n /**\n * Returns the outcome rather than discarding it. An `undefined` field means an apps-manager that\n * predates it and therefore said nothing — which the caller must treat as UNKNOWN (not seeded, not\n * converged), never as the reassuring answer.\n */\n const parsed = AdminAppInitializeResponseSchema.parse(response);\n return {\n appDatabaseSeeding: parsed.appDatabaseSeeding,\n declarationConvergedFields: parsed.declarationConvergedFields,\n };\n }\n\n /**\n * POST /admin/apps/:appSlug/reapply-declaration\n *\n * Re-source the declaration-managed slices of the app's stored config\n * from the latest `wildo.saas.config.ts` projection. Idempotent.\n *\n * See `AdminAppReapplyDeclarationRequestSchema` (platform-config-lib)\n * for the contract scope: this does NOT touch K8s endpoints, infra, admin\n * user/role seeding, or any credential except the minions' runtime-principal\n * credentials, which apps-manager reconciles when the `minions` slice changes.\n */\n static async reapplyApplicationDeclaration(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: {\n appSlug: string;\n managedDeclaration: AdminAppManagedDeclaration;\n /**\n * Ask the server to report the diff and write nothing (issue #97).\n *\n * An empty `updatedFields` under a dry run is the coherence proof the init postcondition\n * and `wildo local doctor` rely on.\n */\n dryRun?: boolean;\n },\n ): Promise<AdminAppReapplyDeclarationResponse> {\n /*\n * The flag is omitted rather than sent as `false` when not requested, so the wire payload of an\n * ordinary reapply is byte-identical to what it was before `dryRun` existed. The request schema\n * is a `strictObject`, so this is also what keeps an older apps-manager from rejecting the call.\n */\n const body = AdminAppReapplyDeclarationRequestSchema.parse({\n managedDeclaration: input.managedDeclaration,\n ...(input.dryRun === true ? { dryRun: true } : {}),\n });\n\n const response = await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminReapplyDeclarationPath(input.appSlug),\n {\n method: 'POST',\n body: JSON.stringify(body),\n },\n );\n\n return AdminAppReapplyDeclarationResponseSchema.parse(response);\n }\n\n /**\n * POST /admin/registry/keys — mint a module-registry key for an organization (default: the platform\n * owner organization) (#1756). The response carries the secret exactly once.\n */\n static async mintRegistryKey(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n request: RegistryKeyMintRequest,\n ): Promise<RegistryKeyMintResponse> {\n const response = await AppBootstrapService.requestJson(env, credentials, REGISTRY_KEYS_ADMIN_PATH, {\n method: 'POST',\n body: JSON.stringify(RegistryKeyMintRequestSchema.parse(request)),\n });\n return RegistryKeyMintResponseSchema.parse(response);\n }\n\n /** GET /admin/registry/keys[?organizationSlug=] — an organization's registry keys, no secrets (#1756). */\n static async listRegistryKeys(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n organizationSlug?: string,\n ): Promise<RegistryKeyListResponse> {\n const query = organizationSlug ? `?organizationSlug=${encodeURIComponent(organizationSlug)}` : '';\n const response = await AppBootstrapService.requestJson(env, credentials, `${REGISTRY_KEYS_ADMIN_PATH}${query}`, { method: 'GET' });\n return RegistryKeyListResponseSchema.parse(response);\n }\n\n /** POST /admin/registry/keys/:apiKeyId/revoke — the registry refuses the key from then on (#1756). */\n static async revokeRegistryKey(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { apiKeyId: string; organizationSlug?: string },\n ): Promise<void> {\n await AppBootstrapService.requestJson(env, credentials, buildRegistryKeyRevokePath(input.apiKeyId), {\n method: 'POST',\n body: JSON.stringify(RegistryKeyRevokeRequestSchema.parse(input.organizationSlug ? { organizationSlug: input.organizationSlug } : {})),\n });\n }\n\n /**\n * POST /admin/apps/:appSlug/keys/rotate — rotate one of an application's keyrings: planned, emergency or root-lost (#2891).\n * Answers with the application's keyring status afterwards.\n */\n static async rotateKeyring(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n request: KeyringRotationRequest,\n ): Promise<KeyringStatus> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminKeyringRotationPath(appSlug), {\n method: 'POST',\n body: JSON.stringify(KeyringRotationRequestSchema.parse(request)),\n });\n return KeyringRotationResponseSchema.parse(response);\n }\n\n /** GET /admin/apps/:appSlug/signing-keys — an application's signing keys as `kid`s and dates, no material (#2895). */\n static async readApplicationSigningKeys(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n ): Promise<ApplicationSigningKeysStatus> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationSigningKeysPath(appSlug), { method: 'GET' });\n return ApplicationSigningKeysStatusSchema.parse(response);\n }\n\n /**\n * POST /admin/apps/:appSlug/signing-keys/rotate — rotate an application's signing keys, naming the keys it replaces\n * (#2895). A failed attempt is sent ONCE more, unchanged: the request is a compare-and-set on the keys it names, so a\n * re-send of a rotation that happened (its answer lost to a timeout or a dropped connection) is answered\n * `already_rotated` and rotates nothing, and a refused one is refused again.\n */\n static async rotateApplicationSigningKeys(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n request: ApplicationSigningKeyRotationRequest,\n ): Promise<ApplicationSigningKeyRotationResponse> {\n const send = async () => ApplicationSigningKeyRotationResponseSchema.parse(\n await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationSigningKeyRotationPath(appSlug), {\n method: 'POST',\n body: JSON.stringify(ApplicationSigningKeyRotationRequestSchema.parse(request)),\n }),\n );\n try {\n return await send();\n } catch {\n return await send();\n }\n }\n\n /**\n * POST /admin/apps/:appSlug/signing-keys/stage or /promote (#2895), the two halves of a planned rotation. A failed\n * attempt is sent ONCE more, unchanged: a re-sent staging is answered `already_staged`, a re-sent promotion (a\n * compare-and-set on the staged keys it names) `already_promoted`, and a refused one is refused again.\n */\n static async planApplicationSigningKeyRotation(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n step: { stage: ApplicationSigningKeyStageRequest } | { promote: ApplicationSigningKeyPromoteRequest },\n ): Promise<ApplicationSigningKeyRotationResponse> {\n const [path, body] = 'stage' in step\n ? [buildAdminApplicationSigningKeyStagePath(appSlug), ApplicationSigningKeyStageRequestSchema.parse(step.stage)]\n : [buildAdminApplicationSigningKeyPromotePath(appSlug), ApplicationSigningKeyPromoteRequestSchema.parse(step.promote)];\n const send = async () => ApplicationSigningKeyRotationResponseSchema.parse(\n await AppBootstrapService.requestJson(env, credentials, path, { method: 'POST', body: JSON.stringify(body) }),\n );\n try {\n return await send();\n } catch {\n return await send();\n }\n }\n\n /** GET /admin/apps/:appSlug/legacy-envelope-key — whether the legacy session encryption key is delivered (#3028). */\n static async readApplicationLegacyEnvelopeKey(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n ): Promise<ApplicationLegacyEnvelopeKeyStatus> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationLegacyEnvelopeKeyPath(appSlug), { method: 'GET' });\n return ApplicationLegacyEnvelopeKeyStatusSchema.parse(response);\n }\n\n /**\n * POST /admin/apps/:appSlug/legacy-envelope-key/retire or /restore (#3028). A failed attempt is sent ONCE more,\n * unchanged: both doors are idempotent (a re-sent retirement is answered `already_retired`, a re-sent restoration\n * `already_delivered`), and a refused one is refused again.\n */\n static async changeApplicationLegacyEnvelopeKeyDelivery(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n change: { retire: ApplicationLegacyEnvelopeKeyRetirementRequest } | { restore: ApplicationLegacyEnvelopeKeyRestoreRequest },\n ): Promise<ApplicationLegacyEnvelopeKeyResponse> {\n const [path, body] = 'retire' in change\n ? [buildAdminApplicationLegacyEnvelopeKeyRetirePath(appSlug), ApplicationLegacyEnvelopeKeyRetirementRequestSchema.parse(change.retire)]\n : [buildAdminApplicationLegacyEnvelopeKeyRestorePath(appSlug), ApplicationLegacyEnvelopeKeyRestoreRequestSchema.parse(change.restore)];\n const send = async () => ApplicationLegacyEnvelopeKeyResponseSchema.parse(\n await AppBootstrapService.requestJson(env, credentials, path, { method: 'POST', body: JSON.stringify(body) }),\n );\n try {\n return await send();\n } catch {\n return await send();\n }\n }\n\n /**\n * GET /admin/apps/:appSlug/residue\n *\n * What the platform still holds for this application (#1556) — read-only. Every count arrives\n * beside the means to tell absence from inability to ask, which is the whole reason the probe\n * exists: an empty answer that cannot prove it looked is indistinguishable from success.\n */\n static async inspectApplicationResidue(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { appSlug: string },\n ): Promise<ApplicationResidueResponse> {\n return await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminApplicationResiduePath(input.appSlug),\n { method: 'GET' },\n ) as ApplicationResidueResponse;\n }\n\n /**\n * GET /admin/apps/:appSlug/scheduled-jobs (#4006) — the jobs the crontabs manager holds for this application, each with\n * the selector `wildo local jobs run` takes, beside the platform-wide total (an empty list beside a zero total says the\n * scheduler holds nothing for anyone).\n */\n static async listApplicationScheduledJobs(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n ): Promise<ApplicationScheduledJobsResponse> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationScheduledJobsPath(appSlug), { method: 'GET' });\n return ApplicationScheduledJobsResponseSchema.parse(response);\n }\n\n /**\n * POST /admin/apps/:appSlug/scheduled-jobs/run (#4006) — run one of the application's jobs now, once. Not re-sent on a\n * failed answer as the signing-key doors are: a manual trigger carries no occurrence id the crontabs manager could\n * deduplicate by, so a re-send whose first attempt landed would run the job twice. One residual, stated rather than\n * hidden: `fetchWithReconnect` re-sends a request whose connection failed, and a connection that drops AFTER apps-manager\n * forwarded the trigger is such a failure, so that rare case can run the job twice (each run is an audit row).\n */\n static async runApplicationScheduledJob(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n appSlug: string,\n request: ApplicationScheduledJobRunRequest,\n ): Promise<ApplicationScheduledJobRunResponse> {\n const response = await AppBootstrapService.requestJson(env, credentials, buildAdminApplicationScheduledJobRunPath(appSlug), {\n method: 'POST',\n body: JSON.stringify(ApplicationScheduledJobRunRequestSchema.parse(request)),\n });\n return ApplicationScheduledJobRunResponseSchema.parse(response);\n }\n\n /**\n * POST /admin/apps/:appSlug/deregister\n *\n * Withdraw an application from the platform (#1556): its cron schedule is removed, its row is marked, and\n * every credential minted for it — the backend's and each minion's Redis, RabbitMQ, MongoDB and PostgreSQL\n * credentials — is REVOKED (#1307). **Destroys no data**: database, broker vhost, cache namespace and blobs\n * are kept, which is why this takes no confirmation and no environment gate, and why `restore` can bring the\n * application back. Destruction is a separate, parked concern (#1562).\n *\n * A withdrawal that could not revoke every credential answers 500 with the list of what still authenticates;\n * `requestJson` surfaces that body in the error it throws.\n *\n * Idempotent: an already-withdrawn application is withdrawn again, and a retry converges.\n */\n static async deregisterApplication(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { appSlug: string; reason?: string },\n ): Promise<ApplicationDeregistrationResponse> {\n return await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminDeregisterApplicationPath(input.appSlug),\n {\n method: 'POST',\n body: JSON.stringify(input.reason ? { reason: input.reason } : {}),\n },\n APPS_MANAGER_CREDENTIAL_LIFECYCLE_TIMEOUT_MS,\n ) as ApplicationDeregistrationResponse;\n }\n\n /**\n * POST /admin/apps/:appSlug/restore\n *\n * Return a withdrawn application to service and RE-MINT the credentials its withdrawal revoked, with the\n * recorded material (#1307), so it can boot. The schedule is re-established by the application's own next\n * boot, because only the application knows its jobs.\n */\n static async restoreApplication(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: { appSlug: string },\n ): Promise<ApplicationRestoreResponse> {\n return await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAdminRestoreApplicationPath(input.appSlug),\n { method: 'POST', body: JSON.stringify({}) },\n APPS_MANAGER_CREDENTIAL_LIFECYCLE_TIMEOUT_MS,\n ) as ApplicationRestoreResponse;\n }\n\n static async fetchBootstrapCredentials(\n env: PlatformEnvironmentConfiguration,\n credentials: PlatformEnvSecretsJson,\n input: {\n appSlug: string;\n runtimeEnvironment: RuntimeEnvironment;\n /**\n * Which runtime principal to fetch for (Step 1 / F11). Omitted ⇒ the\n * application backend, which is what every caller wanted when one secret\n * per application was the only thing that existed.\n */\n principal?: ApplicationRuntimePrincipal;\n },\n ) {\n const response = await AppBootstrapService.requestJson(\n env,\n credentials,\n buildAppBootstrapCredentialsPath(\n input.appSlug,\n input.runtimeEnvironment,\n input.principal ? buildRuntimePrincipalKey(input.principal) : undefined,\n ),\n { method: 'GET' },\n );\n\n return AppBootstrapCredentialsResponseSchema.parse(response);\n }\n\n /**\n * Fetch ONE runtime's own bootstrap credentials.\n *\n * The app-level `prepared.bootstrapCredentials` is the APPLICATION BACKEND's\n * identity. Minion and worker targets used to reuse it verbatim — which is\n * exactly what F11 measured when it compared `backend-api/.env` and\n * `marketing-scrapper/.env` and found the secret byte-identical.\n *\n * The `APPLICATION_ID` and apps-manager URL are per-application and come back\n * identical; only `PLATFORM_APPLICATION_PRIMARY_SECRET` differs. Keeping the\n * whole envelope (rather than splicing one field into the app's) means the\n * runtime's `.env` is built from a response that was authenticated and\n * validated as a unit.\n */\n /**\n * Fetch one bootstrap credential set PER declared minion and worker.\n *\n * The app-level `bootstrapCredentials` is the APPLICATION BACKEND's identity.\n * Minion and worker targets used to reuse it verbatim — which is exactly what\n * F11 measured when it compared `backend-api/.env` with\n * `marketing-scrapper/.env` and found the secret byte-identical.\n *\n * `APPLICATION_ID` and the apps-manager URL come back identical for every\n * principal; only `PLATFORM_APPLICATION_PRIMARY_SECRET` differs. The whole\n * envelope is kept rather than splicing one field into the app's, so each\n * runtime's `.env` is built from a response that was authenticated and\n * validated as a unit.\n */\n private static async fetchDeclaredRuntimePrincipalCredentials(\n input: ApplicationEnvProjectionInput,\n runtimeTarget: ResolvedAppRuntimeTarget,\n runtimeEnvironment: RuntimeEnvironment,\n ): Promise<Record<string, AppBootstrapCredentials>> {\n // Sourced from the MANAGED DECLARATION, not a re-read of the saas config.\n // That is the same input apps-manager mints from, so the set of principals\n // the CLI asks for and the set apps-manager stores cannot drift — and it\n // costs no extra filesystem access, since the declaration is already\n // resolved on the target.\n // The development companion joins on a development environment (#2941), from the same derivation apps-manager mints\n // from, so the CLI never asks for a companion secret the platform did not mint.\n const principals = enumerateRuntimePrincipalsWithBootstrapSecrets(runtimeTarget.managedDeclaration, {\n hostsDevelopmentCompanion: AppBootstrapService.hostsDevelopmentCompanion(runtimeTarget, runtimeEnvironment),\n });\n\n const entries = await Promise.all(\n principals.map(async (principal) => {\n const response = await AppBootstrapService.fetchBootstrapCredentials(\n input.env,\n input.credentials,\n { appSlug: runtimeTarget.appSlug, runtimeEnvironment, principal },\n );\n return [buildRuntimePrincipalKey(principal), response.credentials] as const;\n }),\n );\n return Object.fromEntries(entries);\n }\n\n /**\n * Read an application-authored configuration as the working tree holds it NOW: `wildo.saas.config.ts`, a minion's or\n * a worker's own configuration, the authoritative backend config.\n *\n * Every env-projection read in this service goes through here, and none through a bare `loadConfig`, because jiti's\n * module cache is PROCESS-WIDE: `wildo local dev` regenerates the runtimes' env files in its own long-lived process\n * whenever the declaration changes, and a cached read answers with the file as that process first evaluated it.\n * {@link AppRuntimeTargetsService.resolve} reads the declaration fresh (#3985), so the target, and the identities\n * apps-manager mints from it, already knew a runtime declared later; these builders did not. On reference run\n * 44255624884 five minions and a worker declared after the stack started were minted, then given no `.env`\n * (\"0 worker, 0 minion target(s)\"), and each minion refused its unset `APPLICATION_ENV` about 150 times.\n *\n * What a fresh read costs depends on how the file's framework imports are evaluated: see\n * {@link RUNTIME_DECLARATION_EVALUATION}, which the declaration and runtime-configuration reads pass. The backend\n * config keeps the loader's own inference (`evaluation` omitted): it may define zod schemas of its own, which is the\n * case that evaluation mode does not cover.\n */\n private static readAuthoredConfig<T>(\n filePath: string,\n evaluation: { readonly moduleResolution?: ConfigModuleResolution } = {},\n ): Promise<T> {\n return loadConfig<T>(filePath, { ...evaluation, freshModuleCache: true });\n }\n\n /**\n * Degraded-mode counterpart of {@link requireRuntimePrincipalCredentials}.\n *\n * Returns `null` for a principal the offline reconstruction could not resolve,\n * so the caller SKIPS that runtime and writes the others. Outside degraded mode\n * it delegates and still THROWS — a missing entry there means preparation and\n * the declaration disagree, which is a bug to surface rather than skip.\n *\n * The strictness that matters is untouched either way: nothing ever substitutes\n * the application backend's identity for a principal's.\n */\n private static resolveRuntimePrincipalCredentialsOrSkip(\n prepared: PreparedApplicationEnvTargets,\n principal: ApplicationRuntimePrincipal,\n ): AppBootstrapCredentials | null {\n if (prepared.degraded && !prepared.runtimePrincipalCredentials[buildRuntimePrincipalKey(principal)]) {\n return null;\n }\n return AppBootstrapService.requireRuntimePrincipalCredentials(prepared, principal);\n }\n\n /**\n * A declared runtime's own credentials, or a hard failure.\n *\n * Deliberately NO fallback to `prepared.bootstrapCredentials`. A fallback here\n * would hand the runtime the application backend's identity and the sync would\n * report success — reintroducing F11 silently, at the one seam built to close\n * it. A missing entry means preparation and the declaration disagree, which is\n * a bug to surface, not to paper over.\n */\n private static requireRuntimePrincipalCredentials(\n prepared: PreparedApplicationEnvTargets,\n principal: ApplicationRuntimePrincipal,\n ): AppBootstrapCredentials {\n const principalKey = buildRuntimePrincipalKey(principal);\n const credentials = prepared.runtimePrincipalCredentials[principalKey];\n if (!credentials) {\n throw new Error(\n `No bootstrap credentials prepared for runtime principal '${principalKey}'. `\n + 'Every declared minion and worker, and the development companion, must have its own identity; refusing to fall back to the application backend\\'s.',\n );\n }\n return credentials;\n }\n\n static async buildApplicationBackendTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<ApplicationBackendEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n const { runtimeTarget, bootstrapCredentials, runtimeEndpoints } = prepared;\n\n // App-level deploy context (same value on every backend target, like\n // runtimeEndpoints) — the CI render path reads it to emit the serviceHosts\n // ingress (k8s) / Traefik routing (compose). Empty for local.\n const ingressRoutes = AppBootstrapService.buildApplicationIngressRoutes(runtimeTarget, input.env);\n const { podPorts, healthPort } = AppBootstrapService.buildBackendPodPorts(runtimeTarget, input.env);\n // Per-service model: the frontends deploy as their own nginx Deployments —\n // carried on the (primary-first) backend target's app-deploy context so the\n // CI render emits a backend Deployment + one frontend Deployment per entry.\n const frontends = AppBootstrapService.buildApplicationFrontendDeployTargets(runtimeTarget, input.env);\n // Backend→worker dispatch URLs (G-8 / MW4): every declared worker's per-app\n // k8s Service URL, keyed by bucket name. Emitted into the backend env as\n // `WILDO_WORKER_<NAME>_URL` so the backend's WorkerRemoteClientFactory can\n // call each worker. BOTH location types since #426 — a k8s Service URL for\n // REMOTE, a loopback address for LOCAL; same value on every backend target.\n const workerUrls = AppBootstrapService.buildApplicationWorkerDispatchUrls(runtimeTarget, input.env);\n\n\n // Emit the targets PRIMARY-FIRST. The shared `{appSlug}-secret`\n // (k8s-secrets-generator §5, deduped by appName, first-wins) must bake the\n // PRIMARY backend's identity env (SERVICE_NAME / OTEL_SERVICE_NAME) — the\n // single app pod + every minion mount it — not whichever backend happened to\n // be authored first. The same `selectPrimaryBackendService` rule the runtime endpoints and pod\n // ports use.\n const primaryBackend = selectPrimaryBackendService(runtimeTarget.backendServices);\n const orderedBackends = primaryBackend\n ? [primaryBackend, ...runtimeTarget.backendServices.filter((backend) => backend !== primaryBackend)]\n : runtimeTarget.backendServices;\n\n return orderedBackends.map((service) => {\n const serviceRoot = resolve(runtimeTarget.appRoot, service.path);\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, serviceRoot, `Application backend '${service.serviceName}'`,\n );\n return {\n bootstrapCredentials,\n serviceKey: service.key,\n serviceName: service.serviceName,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n applicationRuntimeSignalsHome: join(runtimeTarget.appRoot, WORKSPACE_HOME_NAMES.APP_RUNTIME_HOME, APP_RUNTIME_SUBDIR_NAMES.RUNTIME_SIGNALS),\n appDatabaseName: runtimeTarget.appDatabaseName,\n redisKeyPrefix: runtimeTarget.redisKeyPrefix,\n storageBucketPrefix: runtimeTarget.storageBucketPrefix,\n runtimeEndpoints,\n appName: runtimeTarget.appSlug,\n ingressRoutes: ingressRoutes.length > 0 ? ingressRoutes : undefined,\n podPorts: podPorts.length > 0 ? podPorts : undefined,\n healthPort,\n frontends: frontends.length > 0 ? frontends : undefined,\n // Per-service, not per-app: each backend row carries its own resolved\n // isolation. Passed through from the config boundary unchanged.\n isolation: {\n runAsUser: service.isolation.runAsUser,\n runAsGroup: service.isolation.runAsGroup,\n writablePaths: [...service.isolation.writablePaths],\n },\n workerUrls,\n // The backend's own declared provider scope. It legitimately declares\n // most providers, so this changes nothing for it today — but it must be\n // threaded explicitly, because the builder now fails CLOSED: an omitted\n // scope yields no provider secrets rather than all of them.\n scopedProviderRefs: runtimeTarget.backendScopedProviderRefs,\n };\n });\n }\n\n /**\n * Build the backend→worker dispatch URL map (G-8 / MW4): for every worker\n * declared in `wildo.saas.config.ts > workers`, its in-cluster base URL\n * `http://{appSlug}-worker-{bucketKey}:{http.port}`, keyed by bucket name.\n *\n * BOTH location types, by different addressing (#426).\n *\n * REMOTE resolves the per-app k8s Service, coherent-by-construction with\n * `renderWorkerForTarget` via the shared `buildWorkerInternalUrl` helper (same\n * `{appSlug}-worker-{key}` Service name). LOCAL has no Service to resolve, so it\n * addresses the supervised worker process on loopback at its authored port.\n *\n * This was `REMOTE only` until 2026-09-09, on the reasoning that \"local dev has no\n * k8s Services, and worker dispatch is a k8s-deploy concern\". The first half is\n * still true; the second stopped being true when `wildo local dev` began starting\n * workers. What local dev lacked was never a worker — it was an ADDRESS, and\n * without one `WorkerRemoteClientFactory.client()` fails closed on the absent\n * `WILDO_WORKER_<NAME>_URL`. That is why the backend-to-worker chain had never run\n * for anyone: it was unreachable in the only environment where anyone could try.\n *\n * The worker `http.port` comes from the resolved runtime target's managed\n * declaration, which `AppRuntimeTargetsService.resolve` built by parsing every\n * worker config through `WildoWorkerConfigSchema` — the same authoritative parse\n * `buildApplicationWorkerTargets` uses — so a wrong port can never drift from the\n * deployed Service or the local listener.\n *\n * It deliberately does NOT re-load `wildo.saas.config.ts` here. The runtime target\n * IS the parsed row; reading the file again would be a second parse of the same\n * truth, and it made this builder the one step of `buildApplicationBackendTargets`\n * that could not run against a resolved target alone (measured 2026-09-09: the\n * backend-targets pin, which stands in a resolved target for a config file that\n * does not exist, failed here and nowhere else once LOCAL joined REMOTE).\n */\n private static buildApplicationWorkerDispatchUrls(\n runtimeTarget: ResolvedAppRuntimeTarget,\n env: PlatformEnvironmentConfiguration,\n ): Record<string, string> | undefined {\n const workers = runtimeTarget.managedDeclaration.workers ?? {};\n const urls: Record<string, string> = {};\n for (const [workerName, worker] of Object.entries(workers)) {\n urls[workerName] = env.locationType === WildoLocationType.REMOTE\n ? buildWorkerInternalUrl(runtimeTarget.appSlug, workerName, worker.http.port)\n : buildWorkerLocalUrl(worker.http.port);\n }\n return Object.keys(urls).length > 0 ? urls : undefined;\n }\n\n static async buildApplicationCompanionTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<CompanionPlatformEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n\n // The companion's endpoints never follow a local tunnel (#3907): a tunnel coming up must not restart it mid-run.\n const { runtimeTarget, companionRuntimeEndpoints: runtimeEndpoints } = prepared;\n // A companion runs on a development environment only (#2941): no other platform mints it a secret.\n if (!AppBootstrapService.hostsDevelopmentCompanion(runtimeTarget, prepared.runtimeEnvironment)) {\n return [];\n }\n const companionRoot = resolveAppLayout(runtimeTarget.appRoot).companionHome;\n // The companion's OWN identity (#2941), never the backend's `bootstrapCredentials`: presenting the backend's secret\n // made it indistinguishable from the backend at apps-manager. Degraded mode skips it when its own secret is not on\n // disk; otherwise a missing entry throws, as for a minion.\n const companionCredentials = AppBootstrapService.resolveRuntimePrincipalCredentialsOrSkip(prepared, DEVELOPMENT_COMPANION_PRINCIPAL);\n if (!companionCredentials) {\n return [];\n }\n\n const companionRelativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, companionRoot, `Application companion for '${runtimeTarget.appSlug}'`,\n );\n\n const companionExtraEnv: Record<string, string> = {};\n\n if (runtimeTarget.localServiceAddresses?.devCompanion?.host) {\n companionExtraEnv.HOST = runtimeTarget.localServiceAddresses.devCompanion.host;\n }\n if (runtimeTarget.localServiceAddresses?.devCompanion?.port) {\n companionExtraEnv.PORT = String(runtimeTarget.localServiceAddresses.devCompanion.port);\n }\n\n return [{\n bootstrapCredentials: companionCredentials,\n serviceName: `${runtimeTarget.appSlug}-dev-companion`,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir: companionRelativeDir,\n runtimeEndpoints,\n extraEnv: companionExtraEnv,\n }];\n }\n\n static async buildApplicationWorkerTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<ApplicationWorkerEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n\n const { runtimeTarget, bootstrapCredentials, runtimeEndpoints } = prepared;\n const isRemote = input.env.locationType === WildoLocationType.REMOTE;\n const saasConfig = await AppBootstrapService.readAuthoredConfig<{\n workers?: Record<string, { path: string }>;\n providers?: { scopes?: { workers?: Record<string, { providers?: Record<string, unknown> }> } };\n }>(runtimeTarget.saasConfigPath, RUNTIME_DECLARATION_EVALUATION);\n const workers = saasConfig.workers ?? {};\n const targets: ApplicationWorkerEnvTarget[] = [];\n\n for (const [workerName, workerRef] of Object.entries(workers)) {\n const workerRoot = resolve(runtimeTarget.appRoot, workerRef.path);\n // Parse through the authoritative schema — validates the authored config\n // AND applies the canonical defaults (port 8080, /healthz, /readyz,\n // replicas 1) from `WorkerHttpSchema`/`WildoWorkerConfigSchema`. Deriving\n // from the spec (rather than re-defaulting `?? 8080` here) keeps the k8s\n // manifest in lockstep with the runtime contract — no drift, no second\n // source of the defaults, and a malformed config fails fast.\n const workerConfig = WildoWorkerConfigSchema.parse(\n await AppBootstrapService.readAuthoredConfig(join(workerRoot, WORKER_CONFIG_FILENAME), RUNTIME_DECLARATION_EVALUATION),\n );\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, workerRoot, `Application worker '${workerName}'`,\n );\n\n const workerCredentials = AppBootstrapService.resolveRuntimePrincipalCredentialsOrSkip(\n prepared,\n { kind: ApplicationRuntimePrincipalKind.WORKER, name: workerName },\n );\n if (!workerCredentials) continue;\n\n targets.push({\n // Workers get their own identity too (D22). Leaving them on the shared\n // application secret would ship the containment with a worker-shaped\n // bypass: a worker could fetch every minion's credentials, so excluding\n // them would not have been the conservative choice.\n bootstrapCredentials: workerCredentials,\n workerName,\n serviceName: workerConfig.name,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n // Where the worker records how its start ended (#3288): the dev supervisor names a process holding its port\n // from that record, as it does for the backend. Written only for a LOCAL deployment (the env builder's guard).\n applicationRuntimeSignalsHome: join(runtimeTarget.appRoot, WORKSPACE_HOME_NAMES.APP_RUNTIME_HOME, APP_RUNTIME_SUBDIR_NAMES.RUNTIME_SIGNALS),\n runtimeEndpoints,\n // Declared provider scope — see the identical field on the minion target.\n // `myRustWorker` declares `providers: {}` and therefore receives no\n // provider secrets at all; it previously received every one of them.\n scopedProviderRefs: Object.keys(\n saasConfig.providers?.scopes?.workers?.[workerName]?.providers ?? {},\n ),\n // Authored worker HTTP (schema-defaulted): nested `http` populated for\n // every env (the `.env` projection is not remote-only), shared by the\n // worker env-gen and the REMOTE k8s render.\n http: {\n port: workerConfig.http.port,\n healthPath: workerConfig.http.healthPath,\n readyPath: workerConfig.http.readyPath,\n metricsPath: workerConfig.http.metricsPath,\n },\n // NOT inside the `isRemote` branch below — container isolation feeds\n // BOTH renderers (k8s securityContext + volumes, compose\n // `user`/`read_only`/`tmpfs`/`pids_limit`). Same placement and same\n // reason as the minion target below.\n isolation: workerConfig.isolation,\n // REMOTE k8s deploy context (appName + replicas).\n ...(isRemote\n ? { appName: runtimeTarget.appSlug, replicas: workerConfig.replicas }\n : {}),\n });\n }\n\n return targets;\n }\n\n static async buildApplicationMinionTargets(\n input: ApplicationEnvProjectionInput,\n ): Promise<ApplicationMinionEnvTarget[]> {\n const prepared = input.prepared ?? await AppBootstrapService.prepareApplicationEnvTargets(input);\n if (!prepared) {\n return [];\n }\n\n const { runtimeTarget, bootstrapCredentials, runtimeEndpoints } = prepared;\n const saasConfig = await AppBootstrapService.readAuthoredConfig<{\n minions?: Record<string, {\n path: string;\n /**\n * The minion's authored application-data access. Read here so env\n * generation can withhold a backing service's TOPOLOGY from a minion that\n * never declared it (object storage) — the same declaration apps-manager\n * reads to decide which tables and storage prefixes beyond the engine floor\n * that minion's credentials cover (#1771).\n *\n * ABSENT and declared-but-empty are different statements and must stay\n * distinguishable all the way down; see `RuntimeAccessDeclaration`.\n */\n resourceAccess?: { read?: readonly string[]; write?: readonly string[] };\n /** Authored opt-in for a route off the host. Default false, never inferred. */\n requiresInternetEgress?: boolean;\n }>;\n // The scope's providers are a REF -> ENTRY map, not a bag of unknowns. Typed\n // that way so `registerMinionLocalProviders` can merge into it without the\n // call site loosening its contract to fit a placeholder type.\n providers?: { scopes?: { minions?: Record<string, { providers?: Record<string, Record<string, unknown>> }> } };\n }>(runtimeTarget.saasConfigPath, RUNTIME_DECLARATION_EVALUATION);\n const minions = saasConfig.minions ?? {};\n const targets: ApplicationMinionEnvTarget[] = [];\n\n const isRemote = input.env.locationType === WildoLocationType.REMOTE;\n for (const [minionName, minionRef] of Object.entries(minions)) {\n const minionRoot = resolve(runtimeTarget.appRoot, minionRef.path);\n // Parse through the authoritative schema — validates AND applies the\n // canonical `MinionReinstantiationSchema`/`MinionLivenessSchema` defaults\n // (kill_previous, file liveness at /tmp/wildo-minion-alive, staleAfterSec\n // 90). Derived from the spec so the k8s manifest never drifts from the\n // runtime contract, and a malformed minion config fails fast.\n const minionConfig = WildoMinionConfigSchema.parse(\n await AppBootstrapService.readAuthoredConfig(join(minionRoot, MINION_CONFIG_FILENAME), RUNTIME_DECLARATION_EVALUATION),\n );\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, minionRoot, `Application minion '${minionName}'`,\n );\n\n const minionCredentials = AppBootstrapService.resolveRuntimePrincipalCredentialsOrSkip(\n prepared,\n { kind: ApplicationRuntimePrincipalKind.MINION, name: minionName },\n );\n // Degraded mode only: a principal whose own secret is not on disk is SKIPPED\n // so every other runtime is still written. Outside degraded mode the resolver\n // throws, preserving the guard that refuses the backend's identity.\n if (!minionCredentials) continue;\n\n targets.push({\n // The minion's OWN identity, not the application backend's. This one\n // line is what F11 was about: every minion previously shipped with the\n // app's `PLATFORM_APPLICATION_PRIMARY_SECRET`, so at the apps-manager\n // door it could ask as the backend — making any narrowing elsewhere\n // bypassable rather than enforced.\n bootstrapCredentials: minionCredentials,\n minionName,\n serviceName: minionConfig.name,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n applicationRuntimeSignalsHome: join(runtimeTarget.appRoot, WORKSPACE_HOME_NAMES.APP_RUNTIME_HOME, APP_RUNTIME_SUBDIR_NAMES.RUNTIME_SIGNALS),\n appDatabaseName: runtimeTarget.appDatabaseName,\n // The minion's OWN Redis namespace (D20), NOT the application's.\n //\n // This is one half of a COUPLED PAIR: apps-manager grants this minion's\n // ACL user exactly `buildMinionRedisKeyPrefix(...)*`, and this is the\n // prefix the minion actually writes under. Derived from the SAME\n // function so the two cannot drift — if they disagree by a character,\n // every Redis operation the minion performs is DENIED and the error\n // names an ACL rather than the mismatch, so nothing in the minion's own\n // configuration explains it.\n //\n // A strict extension of the application prefix, which keeps\n // `RedisService`'s \"an authored prefix must start with `<appSlug>:`\"\n // rule true without changing that rule.\n redisKeyPrefix: buildMinionRedisKeyPrefix(runtimeTarget.appSlug, minionName),\n storageBucketPrefix: runtimeTarget.storageBucketPrefix,\n runtimeEndpoints,\n // NOT inside the `isRemote` branch below: container isolation applies to\n // BOTH renderers. k8s consumes it as securityContext + volumes, compose\n // as `user`/`read_only`/`tmpfs`/`pids_limit`. Gating it on REMOTE would\n // leave local dev running the pre-hardening posture while the manifest\n // claimed otherwise — exactly the k8s/compose asymmetry Step 5b warns\n // about.\n isolation: {\n runAsUser: minionConfig.isolation.runAsUser,\n runAsGroup: minionConfig.isolation.runAsGroup,\n writablePaths: minionConfig.isolation.writablePaths,\n pidsLimit: minionConfig.isolation.pidsLimit,\n },\n // The provider refs this minion DECLARED. Read from the authored scope\n // rather than inherited from the application: a minion scoped to `openai`\n // must not receive the app's Stripe key, and until now it did — the scope\n // was materialised into topology while the SECRETS ignored it entirely.\n // An undeclared scope yields `[]`, i.e. no provider secrets, matching the\n // fail-closed posture `resourceAccess` already takes (D11).\n // R7 — the minion's locally-AUTHORED providers are registered into its own\n // scope before the refs are derived, so a locally-authored provider is\n // visible to this minion exactly as an application-declared one is, and\n // through the SAME projection. Everything downstream — the secret\n // filtering, the generated runtime module — reads the merged scope and\n // cannot tell the two apart, which is what keeps ONE runtime source and\n // ONE secret mechanism.\n //\n // Registered HERE rather than at the catalog: this is the single place\n // that holds both the parsed minion config (which carries the fragment)\n // and the application scope it merges into.\n scopedProviderRefs: Object.keys(\n registerMinionLocalProviders(\n saasConfig.providers?.scopes?.minions?.[minionName],\n minionConfig.localProviders,\n minionName,\n ).providers,\n ),\n // Forwarded VERBATIM, including its absence. Defaulting to `{}` here\n // would turn \"declared nothing\" into \"declared empty\" and hand a\n // non-declaring minion the object-storage route it never asked for;\n // defaulting the other way would strip a declaring minion's object-storage\n // topology. Neither default is safe, so there is none. (The database\n // topology does not depend on the declaration: every minion gets it, #1771.)\n accessDeclaration: {\n resourceAccess: minionRef.resourceAccess,\n requiresInternetEgress: minionRef.requiresInternetEgress,\n },\n // REMOTE k8s deploy context (schema-defaulted fields, read directly).\n ...(isRemote\n ? {\n appName: runtimeTarget.appSlug,\n reinstantiationPolicy: minionConfig.reinstantiation.policy,\n gracePeriodSec: minionConfig.reinstantiation.gracePeriodSec,\n // Whole, so the probe cadence and the heartbeat env are derived from the same parsed value (#1859).\n liveness: minionConfig.liveness,\n }\n : {}),\n });\n }\n\n return targets;\n }\n\n static async buildApplicationFrontendTargets(input: {\n saasRoot: string;\n requestedAppSlug?: string | undefined;\n prepared?: PreparedApplicationEnvTargets;\n }): Promise<ApplicationFrontendEnvExampleTarget[]> {\n // Frontend `.env` targets read the service topology only, which no environment's provider configuration changes.\n const runtimeTarget = input.prepared?.runtimeTarget ?? await AppBootstrapService.resolveRuntimeTarget({ ...input, environmentName: null });\n if (!runtimeTarget) {\n return [];\n }\n\n // The PRIMARY backend's port, never a fallback to another backend's: when `backendApi` declares no\n // port, borrowing `backendServices[0]`'s made the app's API URL name a different backend than the\n // runtime endpoints and the website's local API origin, which all select through the same rule.\n const primaryBackendPort = selectPrimaryBackendService(runtimeTarget.backendServices)?.defaultPort;\n /**\n * Where the DEV SERVER forwards API traffic. This is an internal hop to a plain-http listener and\n * stays http under every edge scheme — the same public/internal split the runtime topology makes.\n */\n const apiProxyTarget = primaryBackendPort ? `http://localhost:${primaryBackendPort}` : undefined;\n\n return runtimeTarget.frontendServices.map((service) => {\n const relativeDir = AppBootstrapService.relativeToApplicationRoot(\n runtimeTarget.appRoot, resolve(runtimeTarget.appRoot, service.path), `Application frontend '${service.serviceName}'`,\n );\n\n /**\n * No `NODE_ENV` here, on purpose (#3097). Vite reads `NODE_ENV=development` from a `.env` file as\n * \"make a development build\", so every `vite build` run from the working tree bundled React's\n * DEVELOPMENT build: StrictMode active, every effect run, cleaned up and run again at mount. A\n * production bundle built that way never showed the sign-in form, and the same would ship to a\n * CDN through `wildo frontend publish`, which uploads a locally built `dist`. Each dev server (Vite,\n * `astro dev`, `docusaurus start`) sets `NODE_ENV` itself, and the SaaS frontend reads its mode\n * from Vite's `MODE`, so nothing needs the line.\n */\n const envExample: Record<string, string> = {\n VITE_APP_SLUG: runtimeTarget.appSlug,\n VITE_APP_NAME: runtimeTarget.appDisplayName,\n ...(service.defaultPort ? { VITE_PORT: String(service.defaultPort) } : {}),\n };\n\n if (service.defaultPort) {\n envExample.VITE_HMR_HOST = 'localhost';\n envExample.VITE_HMR_CLIENT_PORT = String(service.defaultPort);\n // The HMR socket rides the page's own origin, which is plain http locally.\n envExample.VITE_HMR_PROTOCOL = 'ws';\n }\n\n if (service.frontendType === AppFrontendType.SAAS_APP) {\n if (!apiProxyTarget) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no backend API port to bind frontend '${service.serviceName}' to VITE_API_BASE_URL.`,\n );\n }\n\n /**\n * The browser addresses the backend port DIRECTLY. This is the long-standing local behaviour,\n * and as of 2026-08-14 the only one: the dev API proxy was removed, so there is no dev-server\n * origin to address the API on and no proxy target to emit.\n *\n * ⚠️ Under a TLS edge this becomes a mixed-content problem — an https page cannot call the\n * backend's plain-http port. That is one of the reasons the local TLS edge was withdrawn; if\n * one is ever reintroduced, the API origin and the forwarding it implies have to come back\n * TOGETHER, not one before the other.\n */\n envExample.VITE_API_BASE_URL = apiProxyTarget;\n envExample.VITE_FRONTEND_SERVICE_NAME = service.serviceName;\n\n }\n\n if (service.frontendType === AppFrontendType.TECH_DOC) {\n /**\n * The documentation site needs the same three origins the SaaS app does, but under\n * its OWN env names: it is a Docusaurus build, not a Vite app, so it never reads\n * `VITE_*`. Its config refuses to complete a PRODUCTION build when these are unset,\n * because a docs bundle compiles its origins in — a wrong value points every reader\n * at the wrong host instead of failing.\n *\n * Local values are derived here, exactly as `VITE_API_BASE_URL` is, so a developer\n * building the docs locally needs no manual wiring. Remote environments author\n * `documentationSite` in `wildo.infra.<env>.config.ts`, which the documentation image's\n * build arguments and the CI workflow read under the same three names, straight from the\n * loaded descriptor (`ConfigSyncCommand`, `ci-workflow-generator.service.ts`). No runtime\n * environment carries them (#2310).\n */\n if (!apiProxyTarget) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no backend API port to bind documentation site '${service.serviceName}' to WILDO_DOCS_API_BASE_URL.`,\n );\n }\n const saasAppPort = runtimeTarget.frontendServices\n .find((frontend) => frontend.frontendType === AppFrontendType.SAAS_APP)?.defaultPort;\n if (!saasAppPort) {\n throw new Error(\n `Application '${runtimeTarget.appSlug}' has no SaaS application frontend port to bind documentation site '${service.serviceName}' to WILDO_DOCS_APP_URL. `\n + 'The documentation site deep-links anonymous readers to the SaaS app to sign in.',\n );\n }\n // The docs site is itself served plain http locally, so addressing the backend port directly\n // raises no mixed-content problem and needs no proxy of its own.\n envExample[PlatformDocumentationSiteEnvKeys.WILDO_DOCS_API_BASE_URL] = apiProxyTarget;\n // This one points at the SaaS APP, which IS the edge — so it carries the edge scheme. Left as\n // http it deep-links every anonymous reader at a port that no longer answers.\n envExample[PlatformDocumentationSiteEnvKeys.WILDO_DOCS_APP_URL] =\n `http://localhost:${saasAppPort}`;\n envExample[PlatformDocumentationSiteEnvKeys.WILDO_DOCS_FRONTEND_SERVICE_NAME] = service.serviceName;\n }\n\n return {\n serviceName: service.serviceName,\n applicationRoot: runtimeTarget.appRoot,\n relativeDir,\n envExample,\n };\n });\n }\n\n /**\n * Project local authored operator posture into the app-root `.env` target.\n *\n * The generated `config.json` snapshot is the input here. The `.env` file is\n * only a disposable process boundary and is regenerated by both config sync\n * and dev start. Run identity is intentionally absent: the verification\n * supervisor mints it per invocation rather than accepting authored state.\n */\n static buildApplicationOperatorEnvTargets(input: {\n env: PlatformEnvironmentConfiguration;\n config: PlatformEnvConfigJson;\n saasRoot: string;\n }): ApplicationOperatorEnvTarget[] {\n const verification = input.config.applicationCreationVerification;\n if (input.env.locationType !== WildoLocationType.LOCAL) {\n if (verification === undefined) return [];\n throw new Error('Application-creation verification operator environment is local-only.');\n }\n\n return [{\n applicationRoot: resolve(input.saasRoot),\n ...(verification === undefined\n ? { disposition: ApplicationOperatorEnvFileDisposition.REMOVE }\n : {\n disposition: ApplicationOperatorEnvFileDisposition.WRITE,\n env: {\n [ApplicationCreationVerificationEnvKey.EVIDENCE_DIRECTORY]: verification.evidenceDirectory,\n [ApplicationCreationVerificationEnvKey.SILENT]: String(verification.silent),\n },\n }),\n }];\n }\n}\n"]}