@empire-builder-kit/nx 1.0.0-rc.45 → 1.0.0-rc.47

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 (187) hide show
  1. package/generators.json +11 -1
  2. package/package.json +3 -3
  3. package/src/aws-authority/stage-authority.d.ts +30 -2
  4. package/src/aws-authority/stage-authority.js +220 -25
  5. package/src/developer-agent/generator-planning.js +109 -9
  6. package/src/developer-agent/model.d.ts +7 -3
  7. package/src/developer-agent/model.js +1 -0
  8. package/src/developer-agent/operation-registry.d.ts +1 -0
  9. package/src/developer-agent/operation-registry.js +44 -3
  10. package/src/developer-agent/planning.js +5 -2
  11. package/src/developer-agent/preview-changes.js +10 -0
  12. package/src/developer-agent/validation.js +7 -3
  13. package/src/developer-agent/workspace-inspection.js +51 -4
  14. package/src/executors/deployment-plan/deployment-plan.js +3 -0
  15. package/src/executors/dev-doctor/dev-doctor.d.ts +25 -3
  16. package/src/executors/dev-doctor/dev-doctor.js +136 -49
  17. package/src/executors/dev-setup/dev-setup.d.ts +18 -1
  18. package/src/executors/dev-setup/dev-setup.js +320 -196
  19. package/src/executors/foundation-preflight/foundation-preflight.js +9 -1
  20. package/src/executors/foundation-remove-preflight/foundation-remove-preflight.js +2 -2
  21. package/src/executors/github-bootstrap/github-bootstrap.d.ts +3 -0
  22. package/src/executors/github-bootstrap/github-bootstrap.js +28 -0
  23. package/src/executors/github-bootstrap/schema.json +14 -0
  24. package/src/executors/infrastructure-plan/infrastructure-plan.js +10 -3
  25. package/src/executors/local-deploy/local-deploy.d.ts +15 -0
  26. package/src/executors/local-deploy/local-deploy.js +96 -14
  27. package/src/executors/sst-lifecycle/logging-preflight.js +12 -1
  28. package/src/executors/sst-lifecycle/run-sst-command.js +51 -5
  29. package/src/foundation/cost-estimate.js +1 -1
  30. package/src/foundation/identity-domain-parent-ready.d.ts +91 -0
  31. package/src/foundation/identity-domain-parent-ready.js +333 -0
  32. package/src/foundation/identity-domain.d.ts +94 -0
  33. package/src/foundation/identity-domain.js +115 -0
  34. package/src/foundation/index.d.ts +2 -0
  35. package/src/foundation/index.js +7 -0
  36. package/src/foundation/preflight.js +17 -1
  37. package/src/foundation/root-site-readiness.d.ts +27 -0
  38. package/src/foundation/root-site-readiness.js +78 -0
  39. package/src/foundation/root-site.d.ts +81 -0
  40. package/src/foundation/root-site.js +268 -0
  41. package/src/generators/framework-prerequisites.d.ts +2 -0
  42. package/src/generators/framework-prerequisites.js +34 -0
  43. package/src/generators/function/function-registration.d.ts +24 -0
  44. package/src/generators/function/function-registration.js +66 -0
  45. package/src/generators/function/function.d.ts +16 -1
  46. package/src/generators/function/function.js +101 -18
  47. package/src/generators/function/schema.d.ts +1 -0
  48. package/src/generators/function/schema.json +6 -0
  49. package/src/generators/function-access/function-access.d.ts +14 -0
  50. package/src/generators/function-access/function-access.js +141 -0
  51. package/src/generators/function-access/schema.d.ts +6 -0
  52. package/src/generators/function-access/schema.json +25 -0
  53. package/src/generators/post-generation-install.d.ts +1 -1
  54. package/src/generators/post-generation-install.js +1 -1
  55. package/src/generators/preset/dependency-overrides.d.ts +1 -1
  56. package/src/generators/preset/dependency-overrides.js +1 -1
  57. package/src/generators/preset/workspace-files-adopter-skills.js +14 -0
  58. package/src/generators/preset/workspace-files-developer-agent.js +17 -11
  59. package/src/generators/preset/workspace-files-stage-authority.js +58 -1
  60. package/src/generators/preset/workspace-files-thin-deploy.d.ts +11 -0
  61. package/src/generators/preset/workspace-files-thin-deploy.js +52 -5
  62. package/src/generators/preset/workspace-files-thin-docs.js +33 -5
  63. package/src/generators/preset/workspace-files.js +238 -41
  64. package/src/generators/repository-policy/repository-policy.js +2 -1
  65. package/src/generators/repository-policy/schema.d.ts +2 -0
  66. package/src/generators/repository-policy/schema.json +7 -2
  67. package/src/generators/site/built-in-site-documentation-files.d.ts +2 -0
  68. package/src/generators/site/built-in-site-documentation-files.js +92 -0
  69. package/src/generators/site/built-in-site-files.d.ts +8 -0
  70. package/src/generators/site/built-in-site-files.js +40 -0
  71. package/src/generators/site/built-in-site-infrastructure-files.d.ts +2 -0
  72. package/src/generators/site/built-in-site-infrastructure-files.js +275 -0
  73. package/src/generators/site/built-in-site-plan.d.ts +19 -0
  74. package/src/generators/site/built-in-site-plan.js +65 -0
  75. package/src/generators/site/built-in-site-project-files.d.ts +3 -0
  76. package/src/generators/site/built-in-site-project-files.js +258 -0
  77. package/src/generators/site/built-in-site-script-files.d.ts +2 -0
  78. package/src/generators/site/built-in-site-script-files.js +306 -0
  79. package/src/generators/site/built-in-site-shared.d.ts +9 -0
  80. package/src/generators/site/built-in-site-shared.js +21 -0
  81. package/src/generators/site/built-in-site-smoke-files.d.ts +2 -0
  82. package/src/generators/site/built-in-site-smoke-files.js +37 -0
  83. package/src/generators/site/built-in-site-sst-config-files.d.ts +2 -0
  84. package/src/generators/site/built-in-site-sst-config-files.js +39 -0
  85. package/src/generators/site/built-in-site-web-files.d.ts +2 -0
  86. package/src/generators/site/built-in-site-web-files.js +284 -0
  87. package/src/generators/site/schema.d.ts +4 -0
  88. package/src/generators/site/schema.json +20 -0
  89. package/src/generators/site/site.d.ts +13 -0
  90. package/src/generators/site/site.js +221 -0
  91. package/src/generators/slice/built-in-plan-alarm-identity.d.ts +9 -0
  92. package/src/generators/slice/built-in-plan-alarm-identity.js +8 -1
  93. package/src/generators/slice/built-in-plan-api-contract-files.js +18 -0
  94. package/src/generators/slice/built-in-plan-async-work-files.js +18 -0
  95. package/src/generators/slice/built-in-plan-data-files.js +126 -14
  96. package/src/generators/slice/built-in-plan-foundation-files.d.ts +12 -0
  97. package/src/generators/slice/built-in-plan-foundation-files.js +114 -5
  98. package/src/generators/slice/built-in-plan-frontend-files.js +2 -271
  99. package/src/generators/slice/built-in-plan-frontend-header-proof.d.ts +6 -0
  100. package/src/generators/slice/built-in-plan-frontend-header-proof.js +282 -0
  101. package/src/generators/slice/built-in-plan-infrastructure-files.js +151 -237
  102. package/src/generators/slice/built-in-plan-key-value-cleanup.js +4 -3
  103. package/src/generators/slice/built-in-plan-log-group-helpers.d.ts +29 -0
  104. package/src/generators/slice/built-in-plan-log-group-helpers.js +130 -0
  105. package/src/generators/slice/built-in-plan-metadata-files.js +25 -5
  106. package/src/generators/slice/built-in-plan-next-build-authority.d.ts +5 -0
  107. package/src/generators/slice/built-in-plan-next-build-authority.js +124 -0
  108. package/src/generators/slice/built-in-plan-operations-files.d.ts +6 -0
  109. package/src/generators/slice/built-in-plan-operations-files.js +107 -219
  110. package/src/generators/slice/built-in-plan-performance-files.js +6 -1
  111. package/src/generators/slice/built-in-plan-release-files.js +0 -1
  112. package/src/generators/slice/built-in-plan-reliability-files.js +12 -8
  113. package/src/generators/slice/built-in-plan-shared.d.ts +1 -1
  114. package/src/generators/slice/built-in-plan-shared.js +1 -1
  115. package/src/generators/slice/built-in-plan-sst-config.d.ts +49 -0
  116. package/src/generators/slice/built-in-plan-sst-config.js +160 -0
  117. package/src/generators/slice/built-in-plan-testing-files.js +92 -49
  118. package/src/generators/slice/built-in-plan-verification-files.js +15 -5
  119. package/src/generators/slice/built-in-plan-web-files.js +69 -5
  120. package/src/generators/slice/built-in-plan.js +1 -2
  121. package/src/generators/slice/deployed-smoke-diagnostics.d.ts +35 -0
  122. package/src/generators/slice/deployed-smoke-diagnostics.js +189 -0
  123. package/src/generators/slice/deployed-smoke-readiness.d.ts +7 -0
  124. package/src/generators/slice/deployed-smoke-readiness.js +118 -23
  125. package/src/generators/slice/persistence-contract.js +2 -2
  126. package/src/generators/slice/pnpm-launch-script.d.ts +13 -0
  127. package/src/generators/slice/pnpm-launch-script.js +28 -0
  128. package/src/generators/slice/slice.js +27 -0
  129. package/src/generators/upgrade/custom-domain-notice.d.ts +19 -0
  130. package/src/generators/upgrade/custom-domain-notice.js +38 -0
  131. package/src/generators/upgrade/external-blueprint-compositions.d.ts +84 -0
  132. package/src/generators/upgrade/external-blueprint-compositions.js +478 -0
  133. package/src/generators/upgrade/framework-package-upgrade.d.ts +58 -0
  134. package/src/generators/upgrade/framework-package-upgrade.js +78 -0
  135. package/src/generators/upgrade/function-authentication-notice.d.ts +29 -0
  136. package/src/generators/upgrade/function-authentication-notice.js +74 -0
  137. package/src/generators/upgrade/schema.json +2 -2
  138. package/src/generators/upgrade/upgrade-plan.d.ts +52 -0
  139. package/src/generators/upgrade/upgrade-plan.js +406 -0
  140. package/src/generators/upgrade/upgrade.d.ts +1 -35
  141. package/src/generators/upgrade/upgrade.js +347 -595
  142. package/src/generators/workload/reliability-registration.d.ts +1 -1
  143. package/src/generators/workload/reliability-registration.js +9 -9
  144. package/src/generators/workload/workload.d.ts +1 -1
  145. package/src/generators/workload/workload.js +87 -13
  146. package/src/git-policy/github-bootstrap.d.ts +24 -5
  147. package/src/git-policy/github-bootstrap.js +105 -10
  148. package/src/local-dev/fleet-process.d.ts +9 -2
  149. package/src/local-dev/fleet-process.js +27 -7
  150. package/src/local-dev/fleet-session.js +41 -4
  151. package/src/local-dev/fleet-supervisor-daemon.js +1 -5
  152. package/src/local-dev/fleet-supervisor.d.ts +1 -0
  153. package/src/local-dev/fleet-supervisor.js +34 -11
  154. package/src/local-dev/gateway-daemon.d.ts +1 -1
  155. package/src/local-dev/gateway-daemon.js +6 -4
  156. package/src/local-dev/portless.d.ts +5 -0
  157. package/src/local-dev/portless.js +5 -0
  158. package/src/local-dev/process-group.d.ts +10 -0
  159. package/src/local-dev/process-group.js +33 -0
  160. package/src/local-dev/tls.js +31 -2
  161. package/src/local-dev/trust-store.d.ts +42 -0
  162. package/src/local-dev/trust-store.js +87 -0
  163. package/src/ownership/composition.d.ts +7 -0
  164. package/src/ownership/composition.js +64 -56
  165. package/src/ownership/index.d.ts +1 -0
  166. package/src/ownership/index.js +1 -0
  167. package/src/ownership/record.d.ts +19 -0
  168. package/src/ownership/record.js +26 -2
  169. package/src/ownership/site-record.d.ts +18 -0
  170. package/src/ownership/site-record.js +105 -0
  171. package/src/repository-policy/deployment-plan.d.ts +3 -0
  172. package/src/repository-policy/deployment-plan.js +33 -4
  173. package/src/repository-policy/index.d.ts +1 -0
  174. package/src/repository-policy/index.js +1 -0
  175. package/src/repository-policy/policy.d.ts +13 -1
  176. package/src/repository-policy/policy.js +55 -1
  177. package/src/repository-policy/public-dns.d.ts +65 -0
  178. package/src/repository-policy/public-dns.js +168 -0
  179. package/src/schemas/generated-ownership-v2.json +6 -0
  180. package/src/schemas/repository-policy-v1.json +67 -1
  181. package/src/supply-chain/blueprint-trust-git.js +24 -0
  182. package/src/supply-chain/blueprint-verification-authority.js +42 -3
  183. package/src/supply-chain/generated-blueprint-trust-command.js +15 -0
  184. package/src/supply-chain/sbom.js +74 -12
  185. package/src/work-markers/work-markers.js +4 -1
  186. package/src/workspace-deployment/ownership.d.ts +15 -0
  187. package/src/workspace-deployment/ownership.js +19 -3
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DeveloperAgentUpgradePreviewBindingError = void 0;
3
+ exports.DeveloperAgentUpgradePreviewBindingError = exports.createUpgradeReport = void 0;
4
4
  exports.developerAgentUpgradeExecutionOptions = developerAgentUpgradeExecutionOptions;
5
5
  exports.preserveCompositionRegions = preserveCompositionRegions;
6
6
  exports.reemitRecordedNativeRuntimeCompositions = reemitRecordedNativeRuntimeCompositions;
7
7
  exports.inspectWorkspaceSstVersion = inspectWorkspaceSstVersion;
8
- exports.createUpgradeReport = createUpgradeReport;
9
8
  exports.upgradeFoundationForRequirements = upgradeFoundationForRequirements;
10
9
  exports.upgradeGenerator = upgradeGenerator;
11
10
  const deterministic_order_js_1 = require("../../deterministic-order.js");
@@ -13,7 +12,7 @@ const capacity_migration_js_1 = require("../../repository-policy/capacity-migrat
13
12
  const dependency_overrides_js_1 = require("../preset/dependency-overrides.js");
14
13
  const observability_js_1 = require("../../foundation/observability.js");
15
14
  const workspace_files_adopter_skills_js_1 = require("../preset/workspace-files-adopter-skills.js");
16
- const observability_policy_js_1 = require("../observability-policy.js");
15
+ const framework_prerequisites_js_1 = require("../framework-prerequisites.js");
17
16
  const sql_seeded_reconciliation_js_1 = require("./sql-seeded-reconciliation.js");
18
17
  const devkit_1 = require("@nx/devkit");
19
18
  const node_buffer_1 = require("node:buffer");
@@ -25,11 +24,14 @@ const yaml_1 = require("yaml");
25
24
  const index_js_1 = require("../../blueprints/index.js");
26
25
  const index_js_2 = require("../../api-contract/index.js");
27
26
  const index_js_3 = require("../../foundation/index.js");
27
+ const root_site_js_1 = require("../../foundation/root-site.js");
28
28
  const capability_plan_js_1 = require("../../foundation/capability-plan.js");
29
29
  const persistence_contract_js_1 = require("../slice/persistence-contract.js");
30
30
  const index_js_4 = require("../../repository-policy/index.js");
31
31
  const index_js_5 = require("../../ownership/index.js");
32
32
  const function_js_1 = require("../function/function.js");
33
+ const function_registration_js_1 = require("../function/function-registration.js");
34
+ const built_in_site_plan_js_1 = require("../site/built-in-site-plan.js");
33
35
  const logging_registry_js_1 = require("../logging-registry.js");
34
36
  const feature_registry_js_1 = require("../feature-registry.js");
35
37
  const generator_js_1 = require("../preset/generator.js");
@@ -45,7 +47,14 @@ const model_js_1 = require("../../developer-agent/model.js");
45
47
  const preview_source_js_1 = require("../../developer-agent/preview-source.js");
46
48
  const preview_changes_js_1 = require("../../developer-agent/preview-changes.js");
47
49
  const validation_js_1 = require("../../developer-agent/validation.js");
50
+ const custom_domain_notice_js_1 = require("./custom-domain-notice.js");
51
+ const function_authentication_notice_js_1 = require("./function-authentication-notice.js");
52
+ const external_blueprint_compositions_js_1 = require("./external-blueprint-compositions.js");
48
53
  const tree_policy_js_1 = require("../repository-policy/tree-policy.js");
54
+ const framework_package_upgrade_js_1 = require("./framework-package-upgrade.js");
55
+ const upgrade_plan_js_1 = require("./upgrade-plan.js");
56
+ var upgrade_plan_js_2 = require("./upgrade-plan.js");
57
+ Object.defineProperty(exports, "createUpgradeReport", { enumerable: true, get: function () { return upgrade_plan_js_2.createUpgradeReport; } });
49
58
  function readRepositoryDeploymentRenderingOptions(tree) {
50
59
  const policy = (0, tree_policy_js_1.readRepositoryOperatingPolicyFromTree)(tree);
51
60
  return {
@@ -267,153 +276,6 @@ async function assertCurrentDeveloperAgentPreviewSource(workspaceRoot, preview,
267
276
  return previewBindingFailure();
268
277
  }
269
278
  }
270
- const SEEDED_RECONCILIATION = {
271
- 'async/recovery-adapters.ts': {
272
- category: 'async-adapter',
273
- implications: [
274
- 'failure-semantics',
275
- 'provider-behavior',
276
- 'provider-permissions',
277
- ],
278
- },
279
- 'async/runtime.ts': {
280
- category: 'async-settings',
281
- implications: [
282
- 'retry-and-dlq-settings',
283
- 'schedule-contracts',
284
- 'workflow-contracts',
285
- ],
286
- },
287
- 'async/webhook.ts': {
288
- category: 'async-adapter',
289
- implications: [
290
- 'provider-authentication',
291
- 'provider-behavior',
292
- 'webhook-replay-protection',
293
- ],
294
- },
295
- 'async/work-contract.json': {
296
- category: 'async-settings',
297
- implications: [
298
- 'recovery-authority',
299
- 'retry-and-dlq-settings',
300
- 'workflow-versioning',
301
- ],
302
- },
303
- 'configuration/declarations.json': {
304
- category: 'configuration-contract',
305
- implications: [
306
- 'configuration-types',
307
- 'outage-policy',
308
- 'provider-permissions',
309
- ],
310
- },
311
- 'configuration/declarations.ts': {
312
- category: 'configuration-contract',
313
- implications: [
314
- 'configuration-types',
315
- 'outage-policy',
316
- 'provider-permissions',
317
- ],
318
- },
319
- 'configuration/local-values.json': {
320
- category: 'configuration-values',
321
- implications: ['local-defaults', 'safe-fallbacks'],
322
- },
323
- 'docs/reliability/slo.json': {
324
- category: 'reliability-slo',
325
- implications: [
326
- 'error-budget-policy',
327
- 'journey-ownership',
328
- 'service-level-objectives',
329
- ],
330
- },
331
- 'frontend/contract.json': {
332
- category: 'frontend-contract',
333
- implications: [
334
- 'accessibility-proof',
335
- 'browser-security-boundary',
336
- 'public-configuration',
337
- ],
338
- },
339
- 'frontend/security-headers.json': {
340
- category: 'frontend-security',
341
- implications: [
342
- 'content-security-policy',
343
- 'response-header-ownership',
344
- 'transport-profile',
345
- ],
346
- },
347
- 'operations/features.json': {
348
- category: 'feature-controls',
349
- implications: ['flag-lifecycle', 'owners', 'stop-conditions'],
350
- },
351
- 'operations/reliability.json': {
352
- category: 'reliability-operations',
353
- implications: [
354
- 'alarm-registration',
355
- 'database-capacity-dynamodb-table-and-pending-events-throttle-metrics',
356
- 'diagnostic-authority',
357
- 'event-delivery-alarms-and-hourly-outbox-backlog-period',
358
- 'incident-remediation',
359
- 'performance-load-cleanup-backlog-two-evaluation-periods',
360
- ],
361
- },
362
- 'operations/release.json': {
363
- category: 'release-controls',
364
- implications: [
365
- 'artifact-inventory',
366
- 'compatibility-sequence',
367
- 'rollout-controls',
368
- ],
369
- },
370
- 'performance/aggregate-count-provider.ts': {
371
- category: 'performance-aggregate-provider',
372
- implications: [
373
- 'aggregate-source-authority',
374
- 'business-capability-counts',
375
- 'provider-data-access',
376
- ],
377
- },
378
- 'performance/policy.json': {
379
- category: 'performance-policy',
380
- implications: [
381
- 'capacity-and-load-settings',
382
- 'cost-budgets',
383
- 'journey-authority',
384
- ],
385
- },
386
- 'reliability/metric-declarations.ts': {
387
- category: 'reliability-metrics',
388
- guidance: 'Review existing custom recordReliabilityOperation calls and declare each finite deployment-owned component/feature/operation tuple in reliability/metric-declarations.ts. Undeclared custom series are dropped by the managed recorder. Never derive declarations from request, user, resource, or correlation IDs. Preserve existing declarations, verify custom metric emission, retain evidence, and resolve the seeded reconciliation marker before protected promotion.',
389
- implications: [
390
- 'custom-metric-series-allowlist',
391
- 'finite-deployment-owned-dimensions',
392
- 'undeclared-custom-series-are-dropped',
393
- ],
394
- },
395
- 'secrets/declarations.ts': {
396
- category: 'secret-contract',
397
- implications: [
398
- 'generation-authority',
399
- 'secret-value-ownership',
400
- 'stage-requirements',
401
- ],
402
- },
403
- 'secrets/metadata.json': {
404
- category: 'secret-contract',
405
- implications: ['logical-identity', 'management-class', 'registry-schema'],
406
- },
407
- 'secrets/workload-access.json': {
408
- category: 'secret-contract',
409
- implications: [
410
- 'logical-identity',
411
- 'runtime-secret-linkage',
412
- 'workload-iam',
413
- ],
414
- },
415
- };
416
- const SEEDED_RECONCILIATION_MARKER_REFERENCE = 'PLAN:5.6/seeded-upgrade-reconciliation';
417
279
  const SEEDED_RECONCILIATION_MARKER = '// EBK-TODO(PLAN:5.6/seeded-upgrade-reconciliation): Review retained seeded async, configuration, feature, frontend, performance, reliability, release, and secret decisions against this framework upgrade before protected promotion.';
418
280
  const SEEDED_RECONCILIATION_MARKER_ANCHOR = 'async/recovery-adapters.ts';
419
281
  const DEVELOPER_AGENT_AGENTS_HEADING = '## Developer-Agent workflow';
@@ -453,11 +315,6 @@ function planDeveloperAgentInstructionAppend(currentAgents, targetAgents) {
453
315
  path: 'AGENTS.md',
454
316
  };
455
317
  }
456
- function seededReconciliationDefinition(path) {
457
- return Object.prototype.hasOwnProperty.call(SEEDED_RECONCILIATION, path)
458
- ? SEEDED_RECONCILIATION[path]
459
- : null;
460
- }
461
318
  function appendSeededReconciliationMarker(tree, root, report) {
462
319
  if (report.seededReconciliation.length === 0)
463
320
  return;
@@ -466,10 +323,158 @@ function appendSeededReconciliationMarker(tree, root, report) {
466
323
  if (current === null) {
467
324
  throw new Error(`Seeded reconciliation requires deterministic anchor ${anchor}.`);
468
325
  }
469
- if (current.includes(SEEDED_RECONCILIATION_MARKER_REFERENCE))
326
+ if (current.includes(upgrade_plan_js_1.SEEDED_RECONCILIATION_MARKER_REFERENCE))
470
327
  return;
471
328
  tree.write(anchor, `${current.replace(/\s*$/, '')}\n\n${SEEDED_RECONCILIATION_MARKER}\n`);
472
329
  }
330
+ function isJsonObject(value) {
331
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
332
+ }
333
+ const DATABASE_CREDENTIAL_ROTATION_RUNBOOK_PATH = 'docs/runbooks/database-credential-rotation.md';
334
+ /**
335
+ * The opening of the retained SQL rotation paragraph that told operators to
336
+ * rotate through the migration workflow and to confirm that the prior version
337
+ * could be restored. A newly generated runbook never contains it.
338
+ */
339
+ const RETAINED_DATABASE_ROTATION_PARAGRAPH = 'To rotate after an authentication failure';
340
+ const DATABASE_CREDENTIAL_ROTATION_GUIDANCE = 'The retained database credential rotation runbook says the database migration workflow rotates this credential and asks you to confirm that the prior version can be restored. A migration with an unchanged EBK_DATABASE_CREDENTIAL_GENERATION only re-applies the current password, and after a real rotation the database refuses the AWSPREVIOUS password, so restoring it would break every new connection. Before rotating with EBK_DATABASE_CREDENTIAL_GENERATION, replace the runbook with the one a newly generated SQL Slice of the same name renders, or at least replace its paragraph that begins "To rotate after an authentication failure" as the framework upgrade guide (docs/upgrades.md) gives it. Preserve any adopter-owned content, never move the version labels of this credential, then resolve the existing seeded reconciliation marker.';
341
+ function appendDatabaseCredentialRotationReconciliation(currentFiles, currentOwnership, targetOwnership, report) {
342
+ const path = DATABASE_CREDENTIAL_ROTATION_RUNBOOK_PATH;
343
+ const current = currentFiles.get(path);
344
+ const targetEntry = targetOwnership.paths.find((entry) => entry.path === path);
345
+ if (current === null ||
346
+ current === undefined ||
347
+ targetEntry?.mode !== 'seeded' ||
348
+ !current.includes(RETAINED_DATABASE_ROTATION_PARAGRAPH))
349
+ return;
350
+ const currentEntry = currentOwnership.paths.find((entry) => entry.path === path);
351
+ report.seededReconciliation.push({
352
+ adopterContentSha256: (0, index_js_5.hashOwnedContent)(current, currentEntry ?? targetEntry),
353
+ category: 'secret-contract',
354
+ currentFrameworkSha256: currentEntry?.sha256 ?? null,
355
+ guidance: DATABASE_CREDENTIAL_ROTATION_GUIDANCE,
356
+ implications: [
357
+ 'database-credential-generation',
358
+ 'no-version-label-rollback',
359
+ ],
360
+ markerReference: upgrade_plan_js_1.SEEDED_RECONCILIATION_MARKER_REFERENCE,
361
+ path,
362
+ requiredAction: 'review-and-reconcile-preserving-adopter-content',
363
+ targetFrameworkSha256: targetEntry.sha256,
364
+ });
365
+ report.seededReconciliation.sort((left, right) => (0, deterministic_order_js_1.compareUtf16)(left.path, right.path));
366
+ }
367
+ const SEEDED_PRODUCT_SMOKE_PATH = 'e2e/product.spec.ts';
368
+ /**
369
+ * A retained seeded deployed smoke that resolves an absolute operation path
370
+ * against apiUrl, as every generated one did before Slice APIs could be mapped
371
+ * under /<slice> on the Foundation's api.<root> domain.
372
+ */
373
+ const ABSOLUTE_API_PATH_RESOLUTION = /new URL\(\s*['"`]\/[^)]*,\s*apiUrl\s*\)/u;
374
+ const API_BASE_PATH_GUIDANCE = "The retained seeded e2e/product.spec.ts builds API URLs with new URL('/<path>', apiUrl). With a custom domain bound for a stage, the Slice's apiUrl is https://api.<root>/<slice>; resolving an absolute path against it drops /<slice>, so the request reaches no API mapping and deployed smoke fails. Replace each such call with productEndpoint(apiUrl, '/<path>'), as a newly generated Slice of the same name renders it and as the framework upgrade guide (docs/upgrades.md) lists, preserve any adopter-owned content, then resolve the existing seeded reconciliation marker. The change is needed before the first deploy with a bound domain and is harmless without one.";
375
+ function appendApiBasePathReconciliation(currentFiles, currentOwnership, targetOwnership, report) {
376
+ const path = SEEDED_PRODUCT_SMOKE_PATH;
377
+ const current = currentFiles.get(path);
378
+ const targetEntry = targetOwnership.paths.find((entry) => entry.path === path);
379
+ if (current === null ||
380
+ current === undefined ||
381
+ targetEntry?.mode !== 'seeded' ||
382
+ !ABSOLUTE_API_PATH_RESOLUTION.test(current))
383
+ return;
384
+ const currentEntry = currentOwnership.paths.find((entry) => entry.path === path);
385
+ report.seededReconciliation.push({
386
+ adopterContentSha256: (0, index_js_5.hashOwnedContent)(current, currentEntry ?? targetEntry),
387
+ category: 'api-base-path',
388
+ currentFrameworkSha256: currentEntry?.sha256 ?? null,
389
+ guidance: API_BASE_PATH_GUIDANCE,
390
+ implications: ['custom-domain-api-mapping', 'deployed-smoke-api-urls'],
391
+ markerReference: upgrade_plan_js_1.SEEDED_RECONCILIATION_MARKER_REFERENCE,
392
+ path,
393
+ requiredAction: 'review-and-reconcile-preserving-adopter-content',
394
+ targetFrameworkSha256: targetEntry.sha256,
395
+ });
396
+ report.seededReconciliation.sort((left, right) => (0, deterministic_order_js_1.compareUtf16)(left.path, right.path));
397
+ }
398
+ function appendServiceTaskPresenceReconciliation(currentFiles, currentOwnership, targetOwnership, report) {
399
+ const services = currentOwnership.compositions
400
+ .filter(({ kind }) => kind === 'service')
401
+ .map(({ name }) => name)
402
+ .sort(deterministic_order_js_1.compareUtf16);
403
+ if (services.length === 0)
404
+ return;
405
+ const registryPath = 'operations/reliability.json';
406
+ const source = currentFiles.get(registryPath);
407
+ if (source === null || source === undefined)
408
+ return;
409
+ let operations;
410
+ try {
411
+ operations = JSON.parse(source);
412
+ }
413
+ catch {
414
+ throw new Error('Retained Service reliability registry must be valid JSON before upgrade.');
415
+ }
416
+ if (!isJsonObject(operations) ||
417
+ !Array.isArray(operations.deployedAlarmResources)) {
418
+ throw new Error('Retained Service reliability registry must expose deployedAlarmResources before upgrade.');
419
+ }
420
+ const resources = operations.deployedAlarmResources;
421
+ const append = (path, guidance) => {
422
+ const current = currentFiles.get(path);
423
+ const targetEntry = targetOwnership.paths.find((entry) => entry.path === path);
424
+ const currentEntry = currentOwnership.paths.find((entry) => entry.path === path);
425
+ if (current === null ||
426
+ current === undefined ||
427
+ targetEntry?.mode !== 'seeded')
428
+ return;
429
+ const existing = report.seededReconciliation.find((entry) => entry.path === path);
430
+ if (existing) {
431
+ existing.guidance = `${existing.guidance ? `${existing.guidance}\n\n` : ''}${guidance}`;
432
+ existing.implications = [
433
+ ...new Set([...existing.implications, 'service-live-task-presence']),
434
+ ].sort(deterministic_order_js_1.compareUtf16);
435
+ return;
436
+ }
437
+ report.seededReconciliation.push({
438
+ adopterContentSha256: (0, index_js_5.hashOwnedContent)(current, currentEntry ?? targetEntry),
439
+ category: 'reliability-operations',
440
+ currentFrameworkSha256: currentEntry?.sha256 ?? null,
441
+ guidance,
442
+ implications: ['alarm-registration', 'service-live-task-presence'],
443
+ markerReference: upgrade_plan_js_1.SEEDED_RECONCILIATION_MARKER_REFERENCE,
444
+ path,
445
+ requiredAction: 'review-and-reconcile-preserving-adopter-content',
446
+ targetFrameworkSha256: targetEntry.sha256,
447
+ });
448
+ };
449
+ for (const name of services) {
450
+ const id = `service-${name}-health`;
451
+ const legacy = resources.some((entry) => {
452
+ if (!isJsonObject(entry))
453
+ return false;
454
+ const expected = {
455
+ comparisonOperator: 'LessThanThreshold',
456
+ evaluationPeriods: 1,
457
+ id,
458
+ metricName: 'RunningTaskCount',
459
+ name: `${currentOwnership.slice}-{stage}-service-${name}-running`,
460
+ namespace: 'ECS/ContainerInsights',
461
+ period: 60,
462
+ signal: 'metric',
463
+ statistic: 'Sum',
464
+ threshold: 1,
465
+ treatMissingData: 'breaching',
466
+ };
467
+ return (Object.entries(expected).every(([key, value]) => entry[key] === value) &&
468
+ JSON.stringify(entry.dimensionNames) ===
469
+ JSON.stringify(['ClusterName', 'ServiceName']));
470
+ });
471
+ if (!legacy)
472
+ continue;
473
+ append(registryPath, `For recorded Service ${name}, reconcile only deployedAlarmResources[id=${id}]: namespace ECS/ContainerInsights -> AWS/ECS, metricName RunningTaskCount -> LiveTaskCount, statistic Sum -> Minimum. Keep its ID, physical name, actions, dimensions, threshold 1, LessThanThreshold, 60-second period, one evaluation period and breaching missing-data policy. In alarmRegistrations[id=${id}], set missingData to breaching and review businessSymptom, condition and both expected risk fields for task presence or missing telemetry, startup/emission-gap false positives, and activating/draining/replacement crash-loop false negatives. Preserve unrelated registrations and every adopter-owned field. Review services/${name}/RUNBOOK.md, run the declared reliability verification after authorized deployment, retain evidence, then resolve the existing seeded reconciliation marker.`);
474
+ append(`services/${name}/RUNBOOK.md`, `Review the retained Service ${name} runbook for AWS/ECS LiveTaskCount Minimum: ACTIVATING, RUNNING and DEACTIVATING task presence, not readiness. Missing telemetry breaches but does not prove zero tasks. Document startup/emission-gap false positives and activating/draining/replacement crash-loop false negatives, preserve custom recovery instructions, verify the critical journey and alarm recovery after an authorized roll-forward, retain evidence, then resolve the existing seeded reconciliation marker.`);
475
+ }
476
+ report.seededReconciliation.sort((left, right) => (0, deterministic_order_js_1.compareUtf16)(left.path, right.path));
477
+ }
473
478
  function currentContractConsumers(tree, root) {
474
479
  const source = tree.read(node_path_1.posix.join(root, 'contracts/dependencies.json'), 'utf8');
475
480
  if (source === null)
@@ -591,10 +596,6 @@ function reemitRecordedNativeRuntimeCompositions(files, ownership) {
591
596
  }
592
597
  return result;
593
598
  }
594
- function exactIndentedStringCallMatches(source, callee, argument) {
595
- const pattern = new RegExp(`^ ${escapeRegularExpression(callee)}\\(\\s*(['"])${escapeRegularExpression(argument)}\\1\\s*,?\\s*\\),[ \\t]*$`, 'gmu');
596
- return [...source.matchAll(pattern)];
597
- }
598
599
  function reconcileFunctionRegistrationArguments(source, ownership) {
599
600
  let reconciled = source;
600
601
  for (const composition of ownership.compositions) {
@@ -625,8 +626,8 @@ function reconcileFunctionRegistrationArguments(source, ownership) {
625
626
  else if (!(previousRouterCount === 0 && currentRouterCount === 1)) {
626
627
  throw new Error(`Retained Function ${composition.name} registration does not expose one exact Router argument shape.`);
627
628
  }
628
- const previousAuthorityMatches = exactIndentedStringCallMatches(registration, 'workloadRoleBindings?.extension.function', composition.name);
629
- const currentAuthorityMatches = exactIndentedStringCallMatches(registration, 'nativeAuthority.permissions', `${composition.name}-function`);
629
+ const previousAuthorityMatches = (0, function_registration_js_1.exactIndentedStringCallMatches)(registration, 'workloadRoleBindings?.extension.function', composition.name);
630
+ const currentAuthorityMatches = (0, function_registration_js_1.exactIndentedStringCallMatches)(registration, 'nativeAuthority.permissions', `${composition.name}-function`);
630
631
  if (previousAuthorityMatches.length === 1 &&
631
632
  currentAuthorityMatches.length === 0) {
632
633
  const [previousAuthority] = previousAuthorityMatches;
@@ -644,6 +645,9 @@ function reconcileFunctionRegistrationArguments(source, ownership) {
644
645
  currentAuthorityMatches.length === 1)) {
645
646
  throw new Error(`Retained Function ${composition.name} registration does not expose one exact native-authority argument shape.`);
646
647
  }
648
+ // A signed-in Function also takes the Slice's Function access; an
649
+ // anonymous one does not. The secret-link call may be Prettier-wrapped.
650
+ registration = (0, function_registration_js_1.setFunctionRegistrationAccess)(registration, composition.name, (0, function_js_1.functionAuthenticationOf)(composition));
647
651
  reconciled =
648
652
  reconciled.slice(0, start) +
649
653
  registration +
@@ -696,53 +700,6 @@ function preserveBuiltInDerivedApiArtifacts(tree, root, currentOwnership, target
696
700
  }
697
701
  return retained;
698
702
  }
699
- function upgradeConflictMessage(label, report) {
700
- const ownershipDetails = [
701
- ...report.conflictingJsonMembers.map((member) => `- conflicting JSON ownership claim: ${member}`),
702
- ...report.expandedJsonOwnership.map((path) => `- unsafe expansion to whole-file JSON ownership: ${path}`),
703
- ];
704
- return `${label} upgrade has user-modified managed files or unsafe JSON ownership changes:\n${report.conflicting.map((path) => `- ${path}`).join('\n')}${ownershipDetails.length > 0 ? `\n${ownershipDetails.join('\n')}` : ''}\nResolve or restore them before applying the upgrade.`;
705
- }
706
- function seededMigrationUpgradeMessage(label, report) {
707
- return `${label} upgrade cannot rewrite an existing seeded database migration:\n${report.incompatibleSeededMigrations.map((path) => `- ${path}`).join('\n')}\nRegenerate this prerelease workspace instead. Stable-v1 upgrades must add a new migration rather than rewrite migration history.`;
708
- }
709
- async function formatRenderedFiles(tree, files, prefix = '') {
710
- const changedOptions = (0, formatting_js_1.changedTreePrettierOptions)(tree);
711
- return Object.fromEntries(await Promise.all(Object.entries(files).map(async ([path, contents]) => {
712
- const workspacePath = node_path_1.posix.join(prefix, path);
713
- if ((0, built_in_plan_js_1.isBuiltInSliceFormatSensitivePath)(path) ||
714
- (0, workspace_files_js_1.isRawWorkspaceAuthorityPath)(workspacePath)) {
715
- return [path, contents];
716
- }
717
- try {
718
- const options = await (0, formatting_js_1.effectiveTreePrettierOptions)(tree, workspacePath, changedOptions);
719
- return [
720
- path,
721
- await (0, formatting_js_1.formatTreeContentsToFixedPoint)(contents, options, workspacePath),
722
- ];
723
- }
724
- catch {
725
- return [path, contents];
726
- }
727
- })));
728
- }
729
- async function formatOwnershipRecord(tree, path, label) {
730
- if (!tree.exists(path)) {
731
- throw new Error(`${label} ownership metadata is missing at ${path}.`);
732
- }
733
- await (0, formatting_js_1.formatTreeFileToFixedPoint)(tree, path);
734
- }
735
- function readJson(tree, path, label) {
736
- const contents = tree.read(path, 'utf8');
737
- if (contents === null)
738
- throw new Error(`${label} does not exist at ${path}.`);
739
- try {
740
- return JSON.parse(contents);
741
- }
742
- catch (error) {
743
- throw new Error(`${label} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
744
- }
745
- }
746
703
  function objectMember(value, member) {
747
704
  if (typeof value !== 'object' || value === null || Array.isArray(value)) {
748
705
  return undefined;
@@ -822,35 +779,58 @@ function inspectWorkspaceSstVersion(tree, packageJson) {
822
779
  function workspaceSstVersionDriftMessage(state) {
823
780
  return `[ebk-upgrade] ${state.classification}: workspace upgrades require the exact audited SST ${state.expectedVersion} manifest and lock resolution before framework ownership can be restamped.\n${state.issues.map((issue) => `- ${issue}`).join('\n')}\nRemediation: ${state.remediation}`;
824
781
  }
825
- function ownershipValidationMessage(label, issues) {
826
- const details = issues
827
- .map((issue) => `- ${issue.path}: ${issue.message}`)
828
- .join('\n');
829
- const regenerateHint = issues.some(({ path }) => path === 'ownership.schemaVersion')
830
- ? '\nOwnership schema v2 has no pre-release migration shim. Regenerate this unpublished alpha workspace as documented in docs/upgrades.md.'
831
- : '';
832
- return `${label} is invalid:\n${details}${regenerateHint}`;
833
- }
834
- function requireUpgradePrerequisites(tree, target) {
835
- const installedVersion = (0, generator_js_1.frameworkPackageVersion)();
836
- const workspaceResult = (0, index_js_5.validateWorkspaceOwnershipRecord)(readJson(tree, '.ebk/ownership.json', 'Workspace ownership metadata'));
837
- if (!workspaceResult.valid) {
838
- throw new Error(ownershipValidationMessage('Workspace ownership metadata', workspaceResult.issues));
839
- }
840
- if (workspaceResult.value.frameworkVersion !== installedVersion) {
841
- throw new Error(`Workspace tooling is recorded at ${workspaceResult.value.frameworkVersion}, but the installed @empire-builder-kit/nx version is ${installedVersion}. Report and apply the workspace upgrade before upgrading the ${target === 'foundation' ? 'Standard Foundation' : 'Product Slice'}.`);
842
- }
843
- (0, observability_policy_js_1.requireObservabilityPolicyFromTree)(tree);
844
- if (target === 'foundation')
782
+ // site is reserved for the workspace root site. A Product Slice generated
783
+ // under that name before the reservation must be renamed first; no upgrade
784
+ // target runs beside it.
785
+ function refuseProductSliceNamedSite(tree) {
786
+ const source = tree.read(node_path_1.posix.join(root_site_js_1.ROOT_SITE_ROOT, '.ebk/ownership.json'), 'utf8');
787
+ if (source === null)
845
788
  return;
846
- const foundationResult = (0, index_js_5.validateFoundationOwnershipRecord)(readJson(tree, 'packages/foundation/.ebk/ownership.json', 'Standard Foundation ownership metadata'));
847
- if (!foundationResult.valid) {
848
- throw new Error(ownershipValidationMessage('Standard Foundation ownership metadata', foundationResult.issues));
789
+ let recorded;
790
+ try {
791
+ recorded = JSON.parse(source);
849
792
  }
850
- if (foundationResult.value.frameworkVersion !== installedVersion) {
851
- throw new Error(`Standard Foundation is recorded at ${foundationResult.value.frameworkVersion}, but the installed @empire-builder-kit/nx version is ${installedVersion}. Report and apply the Foundation upgrade before upgrading a Product Slice.`);
793
+ catch {
794
+ throw new Error(root_site_js_1.ROOT_SITE_UNREADABLE_RECORD_MESSAGE);
795
+ }
796
+ if (recorded !== null &&
797
+ typeof recorded === 'object' &&
798
+ !Array.isArray(recorded) &&
799
+ Object.prototype.hasOwnProperty.call(recorded, 'slice')) {
800
+ throw new Error(`${root_site_js_1.ROOT_SITE_ROOT} holds a Product Slice named ${root_site_js_1.ROOT_SITE_NAME}, but ${root_site_js_1.ROOT_SITE_NAME} is reserved for the workspace root site. ${root_site_js_1.ROOT_SITE_RENAME_GUIDANCE}`);
852
801
  }
853
802
  }
803
+ // The root site upgrade re-renders the site's managed files from the
804
+ // installed framework, preserves its seeded and adopter-owned files, and
805
+ // restamps its record, as the Foundation upgrade does for the Foundation.
806
+ async function upgradeSite(tree, options, packageJson, output) {
807
+ return (0, framework_package_upgrade_js_1.upgradeFrameworkPackage)(tree, options, output, {
808
+ label: 'Root site',
809
+ refusesSeededMigrationRewrites: false,
810
+ reportName: root_site_js_1.ROOT_SITE_NAME,
811
+ root: root_site_js_1.ROOT_SITE_ROOT,
812
+ targetLabel: 'root site',
813
+ requirePrerequisites: () => (0, framework_prerequisites_js_1.requireUpgradePrerequisites)(tree, 'site'),
814
+ validateOwnership: index_js_5.validateSiteOwnershipRecord,
815
+ render: () => {
816
+ const name = packageJson.name?.trim();
817
+ if (!name) {
818
+ throw new Error('Workspace package.json must declare a name.');
819
+ }
820
+ const runtimeVersion = packageJson.dependencies?.['@empire-builder-kit/runtime'];
821
+ if (!runtimeVersion) {
822
+ throw new Error('Workspace package.json must depend on @empire-builder-kit/runtime before upgrading the root site.');
823
+ }
824
+ return (0, built_in_site_plan_js_1.createBuiltInSitePlan)({
825
+ frameworkVersion: (0, generator_js_1.frameworkPackageVersion)(),
826
+ runtimeVersion,
827
+ scope: `@${name}`,
828
+ });
829
+ },
830
+ restamp: index_js_5.restampSiteOwnership,
831
+ installCallback: () => options.skipInstall ? undefined : () => (0, devkit_1.installPackagesTask)(tree, true),
832
+ });
833
+ }
854
834
  function requireName(name) {
855
835
  const value = name.trim();
856
836
  if (!/^[a-z0-9][a-z0-9-]*$/.test(value)) {
@@ -932,185 +912,7 @@ function gateBreakingBlueprintTransition(current, blueprint, apply, output) {
932
912
  }
933
913
  return true;
934
914
  }
935
- function createUpgradeReport(currentFiles, currentOwnership, targetFiles, targetOwnership, jsonOwnershipChanges = {
936
- claimedJsonMembers: [],
937
- conflictingJsonMembers: [],
938
- expandedJsonOwnership: [],
939
- releasedJsonMembers: [],
940
- }) {
941
- const report = {
942
- addedSeeded: [],
943
- appendedSeeded: [],
944
- changed: [],
945
- claimedJsonMembers: [...jsonOwnershipChanges.claimedJsonMembers],
946
- conflicting: [],
947
- conflictingJsonMembers: [...jsonOwnershipChanges.conflictingJsonMembers],
948
- expandedJsonOwnership: [...jsonOwnershipChanges.expandedJsonOwnership],
949
- incompatibleSeededMigrations: [],
950
- missing: [],
951
- obsolete: [],
952
- preservedSeeded: [],
953
- releasedJsonMembers: [...jsonOwnershipChanges.releasedJsonMembers],
954
- seededReconciliation: [],
955
- unchanged: [],
956
- };
957
- const targetPaths = new Set(targetOwnership.paths.map(({ path }) => path));
958
- const currentPathOwnership = new Map(currentOwnership.paths.map((entry) => [entry.path, entry]));
959
- for (const targetEntry of targetOwnership.paths) {
960
- const { mode, path, sha256: targetSha256 } = targetEntry;
961
- const current = currentFiles.get(path) ?? null;
962
- const target = targetFiles.get(path);
963
- const currentEntry = currentPathOwnership.get(path);
964
- if (target === undefined) {
965
- throw new Error(`Target Blueprint did not render owned path ${path}.`);
966
- }
967
- if (mode === 'seeded') {
968
- (current === null ? report.addedSeeded : report.preservedSeeded).push(path);
969
- if (current !== null &&
970
- currentEntry !== undefined &&
971
- currentEntry.sha256 !== targetSha256 &&
972
- path.startsWith('database/migrations/')) {
973
- report.incompatibleSeededMigrations.push(path);
974
- }
975
- else if (((current !== null && currentEntry?.sha256 !== targetSha256) ||
976
- (current === null &&
977
- path === 'reliability/metric-declarations.ts')) &&
978
- seededReconciliationDefinition(path) !== null) {
979
- const reconciliation = seededReconciliationDefinition(path);
980
- if (reconciliation === null) {
981
- throw new Error(`Missing seeded reconciliation definition for ${path}.`);
982
- }
983
- report.seededReconciliation.push({
984
- adopterContentSha256: current === null
985
- ? null
986
- : (0, index_js_5.hashOwnedContent)(current, currentEntry ?? targetEntry),
987
- category: reconciliation.category,
988
- currentFrameworkSha256: currentEntry?.sha256 ?? null,
989
- ...('guidance' in reconciliation
990
- ? { guidance: reconciliation.guidance }
991
- : {}),
992
- implications: [...reconciliation.implications],
993
- markerReference: SEEDED_RECONCILIATION_MARKER_REFERENCE,
994
- path,
995
- requiredAction: current === null
996
- ? 'declare-existing-custom-metric-series-before-promotion'
997
- : 'review-and-reconcile-preserving-adopter-content',
998
- targetFrameworkSha256: targetSha256,
999
- });
1000
- }
1001
- }
1002
- else if (current === null) {
1003
- report.missing.push(path);
1004
- }
1005
- else if (currentEntry !== undefined &&
1006
- (0, index_js_5.hashOwnedContent)(current, currentEntry) !== currentEntry.sha256) {
1007
- report.conflicting.push(path);
1008
- }
1009
- else if (current === target) {
1010
- report.unchanged.push(path);
1011
- }
1012
- else if (currentEntry === undefined) {
1013
- report.conflicting.push(path);
1014
- }
1015
- else {
1016
- report.changed.push(path);
1017
- }
1018
- }
1019
- for (const entry of currentOwnership.paths) {
1020
- const { mode, origin, path, sha256 } = entry;
1021
- if (mode !== 'managed' ||
1022
- origin === 'composition' ||
1023
- targetPaths.has(path)) {
1024
- continue;
1025
- }
1026
- const current = currentFiles.get(path) ?? null;
1027
- if (current === null)
1028
- continue;
1029
- if ((0, index_js_5.hashOwnedContent)(current, entry) === sha256) {
1030
- report.obsolete.push(path);
1031
- }
1032
- else if (!report.conflicting.includes(path)) {
1033
- report.conflicting.push(path);
1034
- }
1035
- }
1036
- const ownershipConflictPaths = new Set([
1037
- ...report.expandedJsonOwnership,
1038
- ...report.conflictingJsonMembers.map((member) => member.slice(0, member.indexOf('#/'))),
1039
- ]);
1040
- for (const path of ownershipConflictPaths) {
1041
- report.changed = report.changed.filter((entry) => entry !== path);
1042
- report.unchanged = report.unchanged.filter((entry) => entry !== path);
1043
- if (!report.conflicting.includes(path))
1044
- report.conflicting.push(path);
1045
- }
1046
- for (const paths of Object.values(report)) {
1047
- paths.sort((left, right) => typeof left === 'string' && typeof right === 'string'
1048
- ? (0, deterministic_order_js_1.compareUtf16)(left, right)
1049
- : (0, deterministic_order_js_1.compareUtf16)(left.path, right.path));
1050
- }
1051
- return report;
1052
- }
1053
- function mergeStructuredTargetFiles(currentFiles, currentOwnership, targetFiles, targetOwnership) {
1054
- const files = new Map(targetFiles);
1055
- const changes = {
1056
- claimedJsonMembers: [],
1057
- conflictingJsonMembers: [],
1058
- expandedJsonOwnership: [],
1059
- releasedJsonMembers: [],
1060
- };
1061
- const currentEntries = new Map(currentOwnership.paths.map((entry) => [entry.path, entry]));
1062
- for (const targetEntry of targetOwnership.paths) {
1063
- const currentEntry = currentEntries.get(targetEntry.path);
1064
- const current = currentFiles.get(targetEntry.path) ?? null;
1065
- const target = files.get(targetEntry.path);
1066
- if (current === null || target === undefined)
1067
- continue;
1068
- if (targetEntry.mode === 'seeded') {
1069
- files.set(targetEntry.path, current);
1070
- continue;
1071
- }
1072
- if (currentEntry?.managedJsonPointers && !targetEntry.managedJsonPointers) {
1073
- if (targetEntry.mode === 'managed') {
1074
- changes.expandedJsonOwnership.push(targetEntry.path);
1075
- }
1076
- else {
1077
- changes.releasedJsonMembers.push(...currentEntry.managedJsonPointers.map((pointer) => `${targetEntry.path}#${pointer}`));
1078
- }
1079
- continue;
1080
- }
1081
- if (!targetEntry.managedJsonPointers)
1082
- continue;
1083
- if (currentEntry?.managedJsonPointers) {
1084
- const transition = (0, index_js_5.analyzeManagedJsonPointerTransition)(current, target, currentEntry.managedJsonPointers, targetEntry.managedJsonPointers);
1085
- changes.claimedJsonMembers.push(...transition.claimed.map((pointer) => `${targetEntry.path}#${pointer}`));
1086
- changes.conflictingJsonMembers.push(...transition.conflictingClaims.map((pointer) => `${targetEntry.path}#${pointer}`));
1087
- changes.releasedJsonMembers.push(...transition.released.map((pointer) => `${targetEntry.path}#${pointer}`));
1088
- if (transition.conflictingClaims.length > 0) {
1089
- files.set(targetEntry.path, current);
1090
- continue;
1091
- }
1092
- }
1093
- files.set(targetEntry.path, (0, index_js_5.mergeManagedJsonContents)(current, target, targetEntry.managedJsonPointers));
1094
- }
1095
- return { files, ...changes };
1096
- }
1097
- async function formatMergedManagedJsonFiles(tree, root, merge, ownership) {
1098
- const files = new Map(merge.files);
1099
- const changedOptions = (0, formatting_js_1.changedTreePrettierOptions)(tree);
1100
- await Promise.all(ownership.paths.map(async (entry) => {
1101
- if (entry.mode !== 'managed' || !entry.managedJsonPointers)
1102
- return;
1103
- const contents = files.get(entry.path);
1104
- if (contents === undefined) {
1105
- throw new Error(`Target did not render managed JSON ${entry.path}.`);
1106
- }
1107
- const workspacePath = node_path_1.posix.join(root, entry.path);
1108
- const options = await (0, formatting_js_1.effectiveTreePrettierOptions)(tree, workspacePath, changedOptions);
1109
- files.set(entry.path, await (0, formatting_js_1.formatTreeContentsToFixedPoint)(contents, options, workspacePath));
1110
- }));
1111
- return { ...merge, files };
1112
- }
1113
- function renderCompositionUpgradePlan(ownership, workspace, runtimeVersion, serviceAdapterOwner) {
915
+ function renderCompositionUpgradePlan(ownership, workspace, runtimeVersion, serviceAdapterOwner, deploymentProfile) {
1114
916
  const compositionPaths = ownership.paths.filter(({ origin }) => origin === 'composition');
1115
917
  const files = {};
1116
918
  const paths = new Map();
@@ -1134,12 +936,12 @@ function renderCompositionUpgradePlan(ownership, workspace, runtimeVersion, serv
1134
936
  };
1135
937
  for (const composition of ownership.compositions) {
1136
938
  if (composition.kind === 'function') {
1137
- const plan = (0, function_js_1.createFunctionFilePlan)(workspace, ownership.slice, composition.name, composition.feature);
939
+ const plan = (0, function_js_1.createFunctionFilePlan)(workspace, ownership.slice, composition.name, composition.feature, (0, function_js_1.functionAuthenticationOf)(composition));
1138
940
  addPlan(plan.files, plan.paths);
1139
941
  }
1140
942
  else {
1141
943
  const plan = (0, workload_js_1.createWorkloadFilePlan)(workspace, ownership.slice, composition.name, composition.kind, runtimeVersion, composition.feature, composition.kind === 'service' &&
1142
- composition.name === serviceAdapterOwner);
944
+ composition.name === serviceAdapterOwner, [(0, index_js_4.productionRehearsalStage)(deploymentProfile), 'production']);
1143
945
  addPlan(plan.files, plan.paths);
1144
946
  }
1145
947
  }
@@ -1167,7 +969,7 @@ function retainedServiceAdapterOwner(tree, root, ownership) {
1167
969
  return null;
1168
970
  throw new Error('Product Slice Service adapter owner cannot be reconciled for upgrade.');
1169
971
  }
1170
- const operations = readJson(tree, operationsPath, 'Product Slice performance operations registry');
972
+ const operations = (0, upgrade_plan_js_1.readJson)(tree, operationsPath, 'Product Slice performance operations registry');
1171
973
  const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
1172
974
  const load = record(operations) ? operations['load'] : undefined;
1173
975
  const allowlistedAdapters = record(load)
@@ -1180,7 +982,7 @@ function retainedServiceAdapterOwner(tree, root, ownership) {
1180
982
  allowlistedAdapters.some((adapter) => typeof adapter !== 'string')) {
1181
983
  throw new Error('Product Slice Service adapter owner cannot be reconciled for upgrade.');
1182
984
  }
1183
- const scenarioDocument = readJson(tree, node_path_1.posix.join(root, 'performance/load-scenarios.json'), 'Product Slice protected-load scenario catalog');
985
+ const scenarioDocument = (0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, 'performance/load-scenarios.json'), 'Product Slice protected-load scenario catalog');
1184
986
  const scenarios = record(scenarioDocument)
1185
987
  ? scenarioDocument['scenarios']
1186
988
  : undefined;
@@ -1188,7 +990,7 @@ function retainedServiceAdapterOwner(tree, root, ownership) {
1188
990
  ? scenarios.filter((scenario) => record(scenario) && scenario['id'] === 'service-extension')
1189
991
  : [];
1190
992
  const serviceScenario = serviceScenarios[0];
1191
- const secretAccess = readJson(tree, node_path_1.posix.join(root, 'secrets/workload-access.json'), 'Product Slice secret workload access registry');
993
+ const secretAccess = (0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, 'secrets/workload-access.json'), 'Product Slice secret workload access registry');
1192
994
  const bindings = record(secretAccess) ? secretAccess['bindings'] : undefined;
1193
995
  const logicalName = 'GeneratedPerformanceLoadHmacKeys';
1194
996
  const prereleaseLogicalName = `${ownership.slice
@@ -1268,81 +1070,52 @@ function carryRetainedServiceAdapterAuthority(targetFiles, owner) {
1268
1070
  return { ...targetFiles, [path]: json(target) };
1269
1071
  }
1270
1072
  async function upgradeFoundation(tree, options, packageJson, output, foundationRequirements = []) {
1271
- if (options.blueprint !== undefined || options.inputs !== undefined) {
1272
- throw new Error('Standard Foundation upgrades do not accept Blueprint or input options.');
1273
- }
1274
1073
  const root = 'packages/foundation';
1275
- const ownershipResult = (0, index_js_5.validateFoundationOwnershipRecord)(readJson(tree, node_path_1.posix.join(root, '.ebk/ownership.json'), 'Standard Foundation ownership metadata'));
1276
- if (!ownershipResult.valid) {
1277
- throw new Error(ownershipValidationMessage('Standard Foundation ownership metadata', ownershipResult.issues));
1278
- }
1279
- if (!packageJson.name) {
1280
- throw new Error('Workspace package.json must declare a name.');
1281
- }
1282
- const currentOwnership = ownershipResult.value;
1283
- const deployment = readRepositoryDeploymentRenderingOptions(tree);
1284
- const renderedTarget = (0, workspace_files_js_1.renderFoundationFilePlan)({
1285
- ...deployment,
1286
- foundationRequirements,
1287
- foundationDescriptor: readJson(tree, node_path_1.posix.join(root, 'contracts/foundation.json'), 'Existing Foundation resource declaration'),
1288
- frameworkVersion: (0, generator_js_1.frameworkPackageVersion)(),
1289
- name: packageJson.name,
1074
+ await (0, framework_package_upgrade_js_1.upgradeFrameworkPackage)(tree, options, output, {
1075
+ label: 'Standard Foundation',
1076
+ refusesSeededMigrationRewrites: true,
1077
+ reportName: 'foundation',
1078
+ root,
1079
+ targetLabel: 'Standard Foundation',
1080
+ validateOwnership: index_js_5.validateFoundationOwnershipRecord,
1081
+ render: () => {
1082
+ if (!packageJson.name) {
1083
+ throw new Error('Workspace package.json must declare a name.');
1084
+ }
1085
+ const deployment = readRepositoryDeploymentRenderingOptions(tree);
1086
+ return (0, workspace_files_js_1.renderFoundationFilePlan)({
1087
+ ...deployment,
1088
+ foundationRequirements,
1089
+ foundationDescriptor: (0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, 'contracts/foundation.json'), 'Existing Foundation resource declaration'),
1090
+ frameworkVersion: (0, generator_js_1.frameworkPackageVersion)(),
1091
+ name: packageJson.name,
1092
+ });
1093
+ },
1094
+ validateTarget: (ownership) => {
1095
+ const targetValidation = (0, index_js_5.validateFoundationOwnershipRecord)(ownership);
1096
+ if (!targetValidation.valid) {
1097
+ throw new Error(`Target Standard Foundation ownership metadata is invalid:\n${targetValidation.issues
1098
+ .map((issue) => `- ${issue.path}: ${issue.message}`)
1099
+ .join('\n')}`);
1100
+ }
1101
+ },
1102
+ afterReport: (currentFiles) => {
1103
+ const customDomainSwitchNotice = (0, custom_domain_notice_js_1.foundationCustomDomainSwitchNotice)({
1104
+ currentFoundationSource: currentFiles.get('infra/foundation.ts') ?? null,
1105
+ policy: (0, tree_policy_js_1.readRepositoryOperatingPolicyFromTree)(tree),
1106
+ });
1107
+ if (customDomainSwitchNotice !== null) {
1108
+ output.warn(customDomainSwitchNotice);
1109
+ }
1110
+ },
1111
+ restamp: index_js_5.restampFoundationOwnership,
1290
1112
  });
1291
- const target = {
1292
- ...renderedTarget,
1293
- files: await formatRenderedFiles(tree, renderedTarget.files, root),
1294
- };
1295
- const targetValidation = (0, index_js_5.validateFoundationOwnershipRecord)(target.ownership);
1296
- if (!targetValidation.valid) {
1297
- throw new Error(`Target Standard Foundation ownership metadata is invalid:\n${targetValidation.issues
1298
- .map((issue) => `- ${issue.path}: ${issue.message}`)
1299
- .join('\n')}`);
1300
- }
1301
- const allPaths = new Set([
1302
- ...currentOwnership.paths.map(({ path }) => path),
1303
- ...target.ownership.paths.map(({ path }) => path),
1304
- ]);
1305
- const currentFiles = new Map([...allPaths].map((path) => [
1306
- path,
1307
- tree.read(node_path_1.posix.join(root, path), 'utf8'),
1308
- ]));
1309
- let mergedTarget = mergeStructuredTargetFiles(currentFiles, currentOwnership, new Map(Object.entries(target.files)), target.ownership);
1310
- mergedTarget = await formatMergedManagedJsonFiles(tree, root, mergedTarget, target.ownership);
1311
- const report = createUpgradeReport(currentFiles, currentOwnership, mergedTarget.files, target.ownership, mergedTarget);
1312
- output.info(`[ebk-upgrade] foundation ${currentOwnership.frameworkVersion} -> ${target.ownership.frameworkVersion}\n${JSON.stringify(report, null, 2)}`);
1313
- if (!options.apply)
1314
- return;
1315
- if (report.incompatibleSeededMigrations.length > 0) {
1316
- throw new Error(seededMigrationUpgradeMessage('Standard Foundation', report));
1317
- }
1318
- if (report.conflicting.length > 0) {
1319
- throw new Error(upgradeConflictMessage('Standard Foundation', report));
1320
- }
1321
- for (const path of report.obsolete)
1322
- tree.delete(node_path_1.posix.join(root, path));
1323
- const writePaths = new Set([
1324
- ...report.changed,
1325
- ...report.missing,
1326
- ...report.addedSeeded,
1327
- '.ebk/ownership.json',
1328
- ]);
1329
- for (const path of writePaths) {
1330
- const contents = mergedTarget.files.get(path);
1331
- if (contents === undefined) {
1332
- throw new Error(`Target Standard Foundation did not render ${path}.`);
1333
- }
1334
- tree.write(node_path_1.posix.join(root, path), contents);
1335
- }
1336
- (0, index_js_5.restampFoundationOwnership)(tree);
1337
- // Ownership bytes are part of the upgrade result, including agent previews
1338
- // that skip workspace formatting. Canonicalize before binding those bytes.
1339
- await formatOwnershipRecord(tree, node_path_1.posix.join(root, '.ebk/ownership.json'), 'Standard Foundation');
1340
1113
  }
1341
1114
  /** Internal paired-generation path: the ordinary ownership-preserving upgrader owns Foundation writes. */
1342
1115
  async function upgradeFoundationForRequirements(tree, requirements, apply, output = devkit_1.logger) {
1343
- requireUpgradePrerequisites(tree, 'product-slice');
1116
+ (0, framework_prerequisites_js_1.requireUpgradePrerequisites)(tree, 'product-slice');
1344
1117
  const capabilityPlan = (0, capability_plan_js_1.planFoundationCapabilities)({
1345
- current: readJson(tree, 'packages/foundation/contracts/foundation.json', 'Standard Foundation descriptor'),
1118
+ current: (0, upgrade_plan_js_1.readJson)(tree, 'packages/foundation/contracts/foundation.json', 'Standard Foundation descriptor'),
1346
1119
  requirements,
1347
1120
  });
1348
1121
  if (capabilityPlan.migratedFromContract !== null)
@@ -1352,112 +1125,73 @@ async function upgradeFoundationForRequirements(tree, requirements, apply, outpu
1352
1125
  return;
1353
1126
  const policy = (0, tree_policy_js_1.readRepositoryOperatingPolicyFromTree)(tree);
1354
1127
  if (tree.exists('packages/foundation/contracts/costs.json'))
1355
- (0, capacity_migration_js_1.assertCapacityMigrationChoice)(policy.productionFoundation.profile, readJson(tree, 'packages/foundation/contracts/costs.json', 'Foundation cost contract'));
1356
- const packageJson = readJson(tree, 'package.json', 'Workspace package.json');
1128
+ (0, capacity_migration_js_1.assertCapacityMigrationChoice)(policy.productionFoundation.profile, (0, upgrade_plan_js_1.readJson)(tree, 'packages/foundation/contracts/costs.json', 'Foundation cost contract'));
1129
+ const packageJson = (0, upgrade_plan_js_1.readJson)(tree, 'package.json', 'Workspace package.json');
1357
1130
  await upgradeFoundation(tree, { name: 'foundation', apply, skipFormat: true, skipInstall: true }, packageJson, output, requirements);
1358
1131
  }
1359
1132
  async function upgradeWorkspace(tree, options, packageJson, output) {
1360
- if (options.blueprint !== undefined || options.inputs !== undefined) {
1361
- throw new Error('Workspace upgrades do not accept Blueprint or input options.');
1362
- }
1363
- const ownershipResult = (0, index_js_5.validateWorkspaceOwnershipRecord)(readJson(tree, '.ebk/ownership.json', 'Workspace ownership metadata'));
1364
- if (!ownershipResult.valid) {
1365
- throw new Error(ownershipValidationMessage('Workspace ownership metadata', ownershipResult.issues));
1366
- }
1367
- if (!packageJson.name) {
1368
- throw new Error('Workspace package.json must declare a name.');
1369
- }
1370
- const sstVersionState = inspectWorkspaceSstVersion(tree, packageJson);
1371
- const currentOwnership = ownershipResult.value;
1372
- const deployment = readRepositoryDeploymentRenderingOptions(tree);
1373
- const renderedTarget = (0, workspace_files_js_1.renderWorkspaceRootFilePlan)({
1374
- ...deployment,
1375
- dependencyOverrides: tree.exists(dependency_overrides_js_1.DEPENDENCY_OVERRIDES_PATH)
1376
- ? readJson(tree, dependency_overrides_js_1.DEPENDENCY_OVERRIDES_PATH, 'Dependency overrides')
1377
- : undefined,
1378
- observabilityPolicy: tree.exists(observability_js_1.OBSERVABILITY_POLICY_PATH)
1379
- ? readJson(tree, observability_js_1.OBSERVABILITY_POLICY_PATH, 'Observability policy')
1380
- : (0, observability_js_1.defaultObservabilityPolicy)((0, index_js_4.activeDeploymentStages)(deployment.deploymentProfile ?? 'starter'), { preserveLegacy: true }),
1381
- frameworkVersion: (0, generator_js_1.frameworkPackageVersion)(),
1382
- name: packageJson.name,
1133
+ let sstVersionState;
1134
+ await (0, framework_package_upgrade_js_1.upgradeFrameworkPackage)(tree, options, output, {
1135
+ label: 'Workspace',
1136
+ refusesSeededMigrationRewrites: true,
1137
+ reportName: 'workspace',
1138
+ root: '',
1139
+ targetLabel: 'workspace',
1140
+ validateOwnership: index_js_5.validateWorkspaceOwnershipRecord,
1141
+ render: () => {
1142
+ if (!packageJson.name) {
1143
+ throw new Error('Workspace package.json must declare a name.');
1144
+ }
1145
+ sstVersionState = inspectWorkspaceSstVersion(tree, packageJson);
1146
+ const deployment = readRepositoryDeploymentRenderingOptions(tree);
1147
+ return (0, workspace_files_js_1.renderWorkspaceRootFilePlan)({
1148
+ ...deployment,
1149
+ dependencyOverrides: tree.exists(dependency_overrides_js_1.DEPENDENCY_OVERRIDES_PATH)
1150
+ ? (0, upgrade_plan_js_1.readJson)(tree, dependency_overrides_js_1.DEPENDENCY_OVERRIDES_PATH, 'Dependency overrides')
1151
+ : undefined,
1152
+ observabilityPolicy: tree.exists(observability_js_1.OBSERVABILITY_POLICY_PATH)
1153
+ ? (0, upgrade_plan_js_1.readJson)(tree, observability_js_1.OBSERVABILITY_POLICY_PATH, 'Observability policy')
1154
+ : (0, observability_js_1.defaultObservabilityPolicy)((0, index_js_4.activeDeploymentStages)(deployment.deploymentProfile ?? 'starter'), { preserveLegacy: true }),
1155
+ frameworkVersion: (0, generator_js_1.frameworkPackageVersion)(),
1156
+ name: packageJson.name,
1157
+ });
1158
+ },
1159
+ validateTarget: (ownership) => {
1160
+ if (!(0, index_js_5.validateWorkspaceOwnershipRecord)(ownership).valid) {
1161
+ throw new Error('Target workspace ownership metadata is invalid.');
1162
+ }
1163
+ },
1164
+ planSeededAppend: (currentFiles, targetFiles) => planDeveloperAgentInstructionAppend(currentFiles.get('AGENTS.md') ?? null, targetFiles['AGENTS.md']),
1165
+ describeReport: (report) => ({
1166
+ ...report,
1167
+ tooling: { sst: sstVersionState },
1168
+ }),
1169
+ afterReport: () => {
1170
+ if (sstVersionState?.classification === 'sst-version-drift') {
1171
+ const message = workspaceSstVersionDriftMessage(sstVersionState);
1172
+ if (options.apply)
1173
+ throw new Error(message);
1174
+ output.warn(message);
1175
+ }
1176
+ },
1177
+ restamp: index_js_5.restampWorkspaceOwnership,
1383
1178
  });
1384
- const target = {
1385
- ...renderedTarget,
1386
- files: await formatRenderedFiles(tree, renderedTarget.files),
1387
- };
1388
- const targetValidation = (0, index_js_5.validateWorkspaceOwnershipRecord)(target.ownership);
1389
- if (!targetValidation.valid) {
1390
- throw new Error('Target workspace ownership metadata is invalid.');
1391
- }
1392
- const allPaths = new Set([
1393
- ...currentOwnership.paths.map(({ path }) => path),
1394
- ...target.ownership.paths.map(({ path }) => path),
1395
- ]);
1396
- const currentFiles = new Map([...allPaths].map((path) => [path, tree.read(path, 'utf8')]));
1397
- let mergedTarget = mergeStructuredTargetFiles(currentFiles, currentOwnership, new Map(Object.entries(target.files)), target.ownership);
1398
- mergedTarget = await formatMergedManagedJsonFiles(tree, '', mergedTarget, target.ownership);
1399
- const developerAgentInstructionAppend = planDeveloperAgentInstructionAppend(currentFiles.get('AGENTS.md') ?? null, target.files['AGENTS.md']);
1400
- if (developerAgentInstructionAppend !== null) {
1401
- mergedTarget.files.set(developerAgentInstructionAppend.path, developerAgentInstructionAppend.contents);
1402
- }
1403
- const report = createUpgradeReport(currentFiles, currentOwnership, mergedTarget.files, target.ownership, mergedTarget);
1404
- if (developerAgentInstructionAppend !== null) {
1405
- report.preservedSeeded = report.preservedSeeded.filter((path) => path !== developerAgentInstructionAppend.path);
1406
- report.appendedSeeded.push(developerAgentInstructionAppend.path);
1407
- }
1408
- output.info(`[ebk-upgrade] workspace ${currentOwnership.frameworkVersion} -> ${target.ownership.frameworkVersion}\n${JSON.stringify({ ...report, tooling: { sst: sstVersionState } }, null, 2)}`);
1409
- if (sstVersionState.classification === 'sst-version-drift') {
1410
- const message = workspaceSstVersionDriftMessage(sstVersionState);
1411
- if (options.apply)
1412
- throw new Error(message);
1413
- output.warn(message);
1414
- }
1415
- if (!options.apply)
1416
- return;
1417
- if (report.incompatibleSeededMigrations.length > 0) {
1418
- throw new Error(seededMigrationUpgradeMessage('Workspace', report));
1419
- }
1420
- if (report.conflicting.length > 0) {
1421
- throw new Error(upgradeConflictMessage('Workspace', report));
1422
- }
1423
- for (const path of report.obsolete)
1424
- tree.delete(path);
1425
- const writePaths = new Set([
1426
- ...report.changed,
1427
- ...report.missing,
1428
- ...report.addedSeeded,
1429
- ...report.appendedSeeded,
1430
- '.ebk/ownership.json',
1431
- ]);
1432
- for (const path of writePaths) {
1433
- if (path === developerAgentInstructionAppend?.path)
1434
- continue;
1435
- const contents = mergedTarget.files.get(path);
1436
- if (contents === undefined) {
1437
- throw new Error(`Target workspace did not render ${path}.`);
1438
- }
1439
- tree.write(path, contents);
1440
- }
1441
- if (developerAgentInstructionAppend !== null) {
1442
- tree.write(developerAgentInstructionAppend.path, developerAgentInstructionAppend.contents);
1443
- }
1444
- (0, index_js_5.restampWorkspaceOwnership)(tree);
1445
- await formatOwnershipRecord(tree, '.ebk/ownership.json', 'Workspace');
1446
1179
  }
1447
1180
  async function executeUpgradeGenerator(tree, options, output = devkit_1.logger, executionOptions = {}) {
1448
1181
  const name = requireName(options.name);
1182
+ refuseProductSliceNamedSite(tree);
1449
1183
  // The policy is seeded: never reinterpret an existing warm production choice
1450
1184
  // as permission to pause it. The operator must make the rename explicitly.
1451
1185
  const costsPath = 'packages/foundation/contracts/costs.json';
1452
1186
  if (tree.exists(costsPath)) {
1453
- (0, capacity_migration_js_1.assertCapacityMigrationChoice)((0, tree_policy_js_1.readRepositoryOperatingPolicyFromTree)(tree).productionFoundation.profile, readJson(tree, costsPath, 'Foundation cost contract'));
1187
+ (0, capacity_migration_js_1.assertCapacityMigrationChoice)((0, tree_policy_js_1.readRepositoryOperatingPolicyFromTree)(tree).productionFoundation.profile, (0, upgrade_plan_js_1.readJson)(tree, costsPath, 'Foundation cost contract'));
1454
1188
  }
1455
- const packageJson = readJson(tree, 'package.json', 'Workspace package.json');
1189
+ const packageJson = (0, upgrade_plan_js_1.readJson)(tree, 'package.json', 'Workspace package.json');
1456
1190
  if (name === 'workspace') {
1457
1191
  return upgradeWorkspace(tree, options, packageJson, output);
1458
1192
  }
1459
1193
  if (name === 'foundation') {
1460
- requireUpgradePrerequisites(tree, 'foundation');
1194
+ (0, framework_prerequisites_js_1.requireUpgradePrerequisites)(tree, 'foundation');
1461
1195
  // Refuse an unsupported core transition before changing shared contracts.
1462
1196
  // This is a preflight, not a prerelease migration or compatibility layer.
1463
1197
  for (const slice of tree.children('packages')) {
@@ -1465,38 +1199,44 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1465
1199
  const path = node_path_1.posix.join(root, '.ebk/ownership.json');
1466
1200
  if (slice === 'foundation' || !tree.exists(path))
1467
1201
  continue;
1468
- const recorded = readJson(tree, path, 'Product Slice ownership metadata');
1202
+ const recorded = (0, upgrade_plan_js_1.readJson)(tree, path, 'Product Slice ownership metadata');
1469
1203
  if (recorded?.blueprint
1470
1204
  ?.name !== index_js_1.BUILTIN_BLUEPRINT_NAME)
1471
1205
  continue;
1472
1206
  const parsed = (0, index_js_5.validateGeneratedOwnershipRecord)(recorded);
1473
1207
  if (!parsed.valid)
1474
- throw new Error(ownershipValidationMessage('Product Slice ownership metadata', parsed.issues));
1208
+ throw new Error((0, upgrade_plan_js_1.ownershipValidationMessage)('Product Slice ownership metadata', parsed.issues));
1475
1209
  (0, persistence_contract_js_1.standardPersistenceContract)({
1476
1210
  inputs: parsed.value.inputs,
1477
1211
  existingStandardRequirement: parsed.value.foundation,
1478
1212
  ...(tree.exists(node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH))
1479
1213
  ? {
1480
- current: readJson(tree, node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH), 'Standard persistence declaration'),
1214
+ current: (0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH), 'Standard persistence declaration'),
1481
1215
  }
1482
1216
  : {}),
1483
1217
  });
1484
1218
  }
1485
1219
  return upgradeFoundation(tree, options, packageJson, output);
1486
1220
  }
1487
- requireUpgradePrerequisites(tree, 'product-slice');
1221
+ if (name === root_site_js_1.ROOT_SITE_NAME) {
1222
+ return upgradeSite(tree, options, packageJson, output);
1223
+ }
1224
+ (0, framework_prerequisites_js_1.requireUpgradePrerequisites)(tree, 'product-slice');
1488
1225
  const root = node_path_1.posix.join('packages', name);
1489
- const ownershipResult = (0, index_js_5.validateGeneratedOwnershipRecord)(readJson(tree, node_path_1.posix.join(root, '.ebk/ownership.json'), 'Product Slice ownership metadata'));
1226
+ const ownershipResult = (0, index_js_5.validateGeneratedOwnershipRecord)((0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, '.ebk/ownership.json'), 'Product Slice ownership metadata'));
1490
1227
  if (!ownershipResult.valid) {
1491
- throw new Error(ownershipValidationMessage('Product Slice ownership metadata', ownershipResult.issues));
1228
+ throw new Error((0, upgrade_plan_js_1.ownershipValidationMessage)('Product Slice ownership metadata', ownershipResult.issues));
1492
1229
  }
1493
1230
  const currentOwnership = ownershipResult.value;
1494
1231
  if (currentOwnership.slice !== name) {
1495
1232
  throw new Error(`Ownership metadata belongs to ${currentOwnership.slice}, not ${name}.`);
1496
1233
  }
1234
+ // Before the Blueprint resolves or its generator runs, and before any write.
1235
+ (0, external_blueprint_compositions_js_1.refuseExternalBlueprintCompositions)(tree, root, currentOwnership);
1497
1236
  for (const composition of currentOwnership.compositions) {
1498
1237
  (0, feature_registry_js_1.requireRegisteredSliceFeature)(tree, root, composition.feature);
1499
1238
  }
1239
+ const functionAccess = (0, function_authentication_notice_js_1.planFunctionAccessTransitions)(currentOwnership.compositions, (functionName) => tree.read(node_path_1.posix.join(root, 'infra/functions', `${functionName}.ts`), 'utf8'));
1500
1240
  const serviceAdapterOwner = retainedServiceAdapterOwner(tree, root, currentOwnership);
1501
1241
  const recordedReference = currentOwnership.blueprint.name === index_js_1.BUILTIN_BLUEPRINT_NAME
1502
1242
  ? index_js_1.BUILTIN_BLUEPRINT_REFERENCE
@@ -1519,7 +1259,7 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1519
1259
  existingStandardRequirement: currentOwnership.foundation,
1520
1260
  ...(tree.exists(node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH))
1521
1261
  ? {
1522
- current: readJson(tree, node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH), 'Standard persistence declaration'),
1262
+ current: (0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH), 'Standard persistence declaration'),
1523
1263
  }
1524
1264
  : {}),
1525
1265
  });
@@ -1536,7 +1276,7 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1536
1276
  const requiredFoundation = blueprint.source === 'built-in'
1537
1277
  ? (0, capability_plan_js_1.standardPersistenceRequirement)(inputResult.value, currentOwnership.compositions)
1538
1278
  : blueprint.manifest.foundation;
1539
- const existingFoundation = readJson(tree, 'packages/foundation/contracts/foundation.json', 'Standard Foundation descriptor');
1279
+ const existingFoundation = (0, upgrade_plan_js_1.readJson)(tree, 'packages/foundation/contracts/foundation.json', 'Standard Foundation descriptor');
1540
1280
  const compatibility = (0, index_js_3.validateFoundationCompatibility)(requiredFoundation, blueprint.source === 'built-in'
1541
1281
  ? (0, capability_plan_js_1.planFoundationCapabilities)({
1542
1282
  current: existingFoundation,
@@ -1565,7 +1305,7 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1565
1305
  compositions: currentOwnership.compositions,
1566
1306
  ...(tree.exists(node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH))
1567
1307
  ? {
1568
- current: readJson(tree, node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH), 'Standard persistence declaration'),
1308
+ current: (0, upgrade_plan_js_1.readJson)(tree, node_path_1.posix.join(root, persistence_contract_js_1.STANDARD_PERSISTENCE_PATH), 'Standard persistence declaration'),
1569
1309
  }
1570
1310
  : {}),
1571
1311
  });
@@ -1672,7 +1412,7 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1672
1412
  targetFiles = preserveBuiltInDerivedApiArtifacts(tree, root, currentOwnership, targetFiles);
1673
1413
  }
1674
1414
  const targetPathSet = new Set(targetOwnership.paths.map(({ path }) => path));
1675
- const compositionPlan = renderCompositionUpgradePlan(currentOwnership, packageJson.name ?? '', packageJson.dependencies?.['@empire-builder-kit/runtime'] ?? '', serviceAdapterOwner);
1415
+ const compositionPlan = renderCompositionUpgradePlan(currentOwnership, packageJson.name ?? '', packageJson.dependencies?.['@empire-builder-kit/runtime'] ?? '', serviceAdapterOwner, (0, tree_policy_js_1.readRepositoryOperatingPolicyFromTree)(tree).deploymentProfile);
1676
1416
  const compositionPaths = compositionPlan.paths.filter(({ path }) => !targetPathSet.has(path));
1677
1417
  if (externalBlueprintDestinationPaths) {
1678
1418
  (0, index_js_1.assertBlueprintDestinationPaths)(tree.root, root, [
@@ -1688,7 +1428,7 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1688
1428
  }
1689
1429
  targetFiles = { ...targetFiles, [entry.path]: contents };
1690
1430
  }
1691
- targetFiles = await formatRenderedFiles(tree, targetFiles, root);
1431
+ targetFiles = await (0, upgrade_plan_js_1.formatRenderedFiles)(tree, targetFiles, root);
1692
1432
  targetOwnership = {
1693
1433
  ...targetOwnership,
1694
1434
  compositions: currentOwnership.compositions,
@@ -1725,8 +1465,8 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1725
1465
  path,
1726
1466
  tree.read(node_path_1.posix.join(root, path), 'utf8'),
1727
1467
  ]));
1728
- let mergedTarget = mergeStructuredTargetFiles(currentFiles, currentOwnership, new Map(Object.entries(targetFiles)), targetOwnership);
1729
- mergedTarget = await formatMergedManagedJsonFiles(tree, root, mergedTarget, targetOwnership);
1468
+ let mergedTarget = (0, upgrade_plan_js_1.mergeStructuredTargetFiles)(currentFiles, currentOwnership, new Map(Object.entries(targetFiles)), targetOwnership);
1469
+ mergedTarget = await (0, upgrade_plan_js_1.formatMergedManagedJsonFiles)(tree, root, mergedTarget, targetOwnership);
1730
1470
  const sqlAppends = blueprint.source === 'built-in' &&
1731
1471
  (0, capability_plan_js_1.readStandardSqlDeclaration)(inputResult.value)
1732
1472
  ? (0, sql_seeded_reconciliation_js_1.planSqlSeededReconciliation)(currentFiles, targetFiles)
@@ -1744,7 +1484,12 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1744
1484
  const formatting = await (0, formatting_js_1.effectiveTreePrettierOptions)(tree, workspacePath, (0, formatting_js_1.changedTreePrettierOptions)(tree));
1745
1485
  mergedTarget.files.set(logging_registry_js_1.SLICE_LOGGING_REGISTRY_PATH, await (0, formatting_js_1.formatTreeContentsToFixedPoint)(loggingAppend, formatting, workspacePath));
1746
1486
  }
1747
- const report = createUpgradeReport(currentFiles, currentOwnership, mergedTarget.files, targetOwnership, mergedTarget);
1487
+ const report = (0, upgrade_plan_js_1.createUpgradeReport)(currentFiles, currentOwnership, mergedTarget.files, targetOwnership, mergedTarget);
1488
+ if (blueprint.source === 'built-in') {
1489
+ appendServiceTaskPresenceReconciliation(currentFiles, currentOwnership, targetOwnership, report);
1490
+ appendDatabaseCredentialRotationReconciliation(currentFiles, currentOwnership, targetOwnership, report);
1491
+ appendApiBasePathReconciliation(currentFiles, currentOwnership, targetOwnership, report);
1492
+ }
1748
1493
  if (loggingAppend !== null) {
1749
1494
  report.preservedSeeded = report.preservedSeeded.filter((path) => path !== logging_registry_js_1.SLICE_LOGGING_REGISTRY_PATH);
1750
1495
  report.appendedSeeded.push(logging_registry_js_1.SLICE_LOGGING_REGISTRY_PATH);
@@ -1754,17 +1499,24 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1754
1499
  report.appendedSeeded.push(path);
1755
1500
  }
1756
1501
  report.appendedSeeded.sort(deterministic_order_js_1.compareUtf16);
1757
- output.info(`[ebk-upgrade] ${name} ${currentOwnership.blueprint.name}@${currentOwnership.blueprint.version} -> ${blueprint.manifest.name}@${blueprint.manifest.version}\n${JSON.stringify(report, null, 2)}`);
1502
+ output.info(`[ebk-upgrade] ${name} ${currentOwnership.blueprint.name}@${currentOwnership.blueprint.version} -> ${blueprint.manifest.name}@${blueprint.manifest.version}\n${JSON.stringify(functionAccess.length > 0 ? { ...report, functionAccess } : report, null, 2)}`);
1503
+ const functionAuthenticationSwitchNotice = (0, function_authentication_notice_js_1.functionAuthenticationNotice)(name, functionAccess);
1504
+ if (functionAuthenticationSwitchNotice !== null) {
1505
+ output.warn(functionAuthenticationSwitchNotice);
1506
+ }
1507
+ const publicFunctionsNotice = (0, function_authentication_notice_js_1.anonymousFunctionNotice)(name, functionAccess);
1508
+ if (publicFunctionsNotice !== null)
1509
+ output.warn(publicFunctionsNotice);
1758
1510
  if (!options.apply) {
1759
1511
  if (blueprint.source === 'built-in')
1760
1512
  await upgradeFoundationForRequirements(tree, [requiredFoundation], false, output);
1761
1513
  return;
1762
1514
  }
1763
1515
  if (report.incompatibleSeededMigrations.length > 0) {
1764
- throw new Error(seededMigrationUpgradeMessage('Product Slice', report));
1516
+ throw new Error((0, upgrade_plan_js_1.seededMigrationUpgradeMessage)('Product Slice', report));
1765
1517
  }
1766
1518
  if (report.conflicting.length > 0) {
1767
- throw new Error(upgradeConflictMessage('Product Slice', report));
1519
+ throw new Error((0, upgrade_plan_js_1.upgradeConflictMessage)('Product Slice', report));
1768
1520
  }
1769
1521
  if (blueprint.source === 'built-in')
1770
1522
  await upgradeFoundationForRequirements(tree, [requiredFoundation], true, output);
@@ -1799,7 +1551,7 @@ async function executeUpgradeGenerator(tree, options, output = devkit_1.logger,
1799
1551
  }
1800
1552
  }
1801
1553
  (0, index_js_5.restampProductSliceOwnership)(tree, name, { preserveSeeded: true });
1802
- await formatOwnershipRecord(tree, node_path_1.posix.join(root, '.ebk/ownership.json'), 'Product Slice');
1554
+ await (0, upgrade_plan_js_1.formatOwnershipRecord)(tree, node_path_1.posix.join(root, '.ebk/ownership.json'), 'Product Slice');
1803
1555
  return options.skipInstall
1804
1556
  ? undefined
1805
1557
  : () => (0, devkit_1.installPackagesTask)(tree, true);