@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
@@ -3,7 +3,7 @@ export declare const WORKLOAD_RELIABILITY_REGISTRY_PATH: "operations/reliability
3
3
  export interface WorkloadReliabilityPlan {
4
4
  alarmId: string;
5
5
  contents: string;
6
- metricName: 'MatchedEvents' | 'RunningTaskCount';
6
+ metricName: 'LiveTaskCount' | 'MatchedEvents';
7
7
  path: string;
8
8
  runbookRef: string;
9
9
  }
@@ -61,21 +61,21 @@ function planWorkloadReliabilityRegistration(tree, input) {
61
61
  ...operations.alarmRegistrations,
62
62
  (0, reliability_1.validateAlarmRegistrationMetadata)({
63
63
  businessSymptom: input.kind === 'service'
64
- ? `${input.name} Service health checks are failing.`
64
+ ? `${input.name} Service task presence is below one or telemetry is missing.`
65
65
  : `${input.name} Job executions are failing.`,
66
66
  condition: input.kind === 'service'
67
- ? 'The AWS-native ECS RunningTaskCount signal is below one or missing for the exact Service.'
67
+ ? 'The AWS/ECS LiveTaskCount minimum is below one or missing for the exact Service; it counts ACTIVATING, RUNNING, and DEACTIVATING tasks.'
68
68
  : 'An AWS-native ECS task-state event reports an essential container exit for the exact Job task family.',
69
69
  dependencyAlarmIds: [],
70
70
  escalationRouteKey: `${input.slice}-on-call`,
71
71
  expectedFalseNegativeRisk: input.kind === 'service'
72
- ? 'Container Insights delivery can be delayed; missing data is therefore treated as breaching.'
72
+ ? 'Activating, draining, or repeatedly replaced tasks can keep LiveTaskCount positive while readiness or useful work fails.'
73
73
  : 'ECS task-state events are durable but can be delayed before EventBridge reports a match.',
74
74
  expectedFalsePositiveRisk: input.kind === 'service'
75
- ? 'A synthetic health client can fail while the Service remains available.'
75
+ ? 'Metric emission gaps, startup, or lifecycle transitions can breach the missing-data policy while tasks remain present.'
76
76
  : 'A retried Job attempt can fail before a later attempt succeeds.',
77
77
  id: alarmId,
78
- missingData: 'missing',
78
+ missingData: input.kind === 'service' ? 'breaching' : 'missing',
79
79
  owner,
80
80
  runbookRef: `runbook:${runbookRef}`,
81
81
  severity: 'high',
@@ -90,15 +90,15 @@ function planWorkloadReliabilityRegistration(tree, input) {
90
90
  dimensionNames: input.kind === 'service' ? ['ClusterName', 'ServiceName'] : ['RuleName'],
91
91
  evaluationPeriods: 1,
92
92
  id: alarmId,
93
- metricName: input.kind === 'service' ? 'RunningTaskCount' : 'MatchedEvents',
93
+ metricName: input.kind === 'service' ? 'LiveTaskCount' : 'MatchedEvents',
94
94
  name: `${input.slice}-{stage}-${input.kind}-${input.name}-${input.kind === 'service' ? 'running' : 'hard-crash'}`,
95
- namespace: input.kind === 'service' ? 'ECS/ContainerInsights' : 'AWS/Events',
95
+ namespace: input.kind === 'service' ? 'AWS/ECS' : 'AWS/Events',
96
96
  owner,
97
97
  period: 60,
98
98
  route: `${input.slice}-on-call`,
99
99
  runbook: runbookRef,
100
100
  signal: 'metric',
101
- statistic: 'Sum',
101
+ statistic: input.kind === 'service' ? 'Minimum' : 'Sum',
102
102
  threshold: 1,
103
103
  treatMissingData: input.kind === 'service' ? 'breaching' : 'notBreaching',
104
104
  };
@@ -142,7 +142,7 @@ function planWorkloadReliabilityRegistration(tree, input) {
142
142
  return {
143
143
  alarmId,
144
144
  contents: `${JSON.stringify(operations, null, 2)}\n`,
145
- metricName: input.kind === 'service' ? 'RunningTaskCount' : 'MatchedEvents',
145
+ metricName: input.kind === 'service' ? 'LiveTaskCount' : 'MatchedEvents',
146
146
  path,
147
147
  runbookRef,
148
148
  };
@@ -13,5 +13,5 @@ export interface WorkloadFilePlan {
13
13
  }>;
14
14
  project: string;
15
15
  }
16
- export declare function createWorkloadFilePlan(workspace: string, slice: string, workload: string, kind: WorkloadKind, runtimeVersion: string, feature: string, ownsProtectedLoadAdapter: boolean, protectedRuntimeStages?: readonly ('development' | 'production' | 'staging')[]): WorkloadFilePlan;
16
+ export declare function createWorkloadFilePlan(workspace: string, slice: string, workload: string, kind: WorkloadKind, runtimeVersion: string, feature: string, ownsProtectedLoadAdapter: boolean, protectedRuntimeStages: readonly ('development' | 'production' | 'staging')[]): WorkloadFilePlan;
17
17
  export declare function workloadGenerator(tree: Tree, options: WorkloadGeneratorSchema, kind: WorkloadKind): Promise<GeneratorCallback | void>;
@@ -20,6 +20,7 @@ const tool_versions_js_1 = require("../preset/tool-versions.js");
20
20
  const workspace_files_js_1 = require("../preset/workspace-files.js");
21
21
  const built_in_plan_js_1 = require("../slice/built-in-plan.js");
22
22
  const built_in_plan_shared_js_1 = require("../slice/built-in-plan-shared.js");
23
+ const external_blueprint_compositions_js_1 = require("../upgrade/external-blueprint-compositions.js");
23
24
  const frozen_container_js_1 = require("./frozen-container.js");
24
25
  const performance_registration_js_1 = require("./performance-registration.js");
25
26
  const reliability_registration_js_1 = require("./reliability-registration.js");
@@ -139,7 +140,7 @@ exports.SERVICE_WORKLOAD_PACKAGE_MANAGED_JSON_POINTERS = [
139
140
  '/dependencies/@aws-sdk~1client-dynamodb',
140
141
  '/dependencies/sst',
141
142
  ];
142
- function createWorkloadFilePlan(workspace, slice, workload, kind, runtimeVersion, feature, ownsProtectedLoadAdapter, protectedRuntimeStages = ['staging', 'production']) {
143
+ function createWorkloadFilePlan(workspace, slice, workload, kind, runtimeVersion, feature, ownsProtectedLoadAdapter, protectedRuntimeStages) {
143
144
  const plural = kind === 'service' ? 'services' : 'jobs';
144
145
  const relativeRoot = node_path_1.posix.join(plural, workload);
145
146
  const className = `${pascal(slice)}${pascal(workload)}${pascal(kind)}`;
@@ -161,7 +162,7 @@ function createWorkloadFilePlan(workspace, slice, workload, kind, runtimeVersion
161
162
  version: '0.0.0',
162
163
  scripts: {
163
164
  build: 'tsc -p tsconfig.json',
164
- 'docker-build': `docker build -f packages/${slice}/${relativeRoot}/Dockerfile ` +
165
+ 'docker-build': 'docker build -f Dockerfile ' +
165
166
  `-t ${slice}-${kind}-${workload}:local ../../../..`,
166
167
  dev: `node --experimental-strip-types ${kind === 'service' ? 'src/main.ts' : 'src/run.ts'}`,
167
168
  lint: 'eslint .',
@@ -212,7 +213,7 @@ function createWorkloadFilePlan(workspace, slice, workload, kind, runtimeVersion
212
213
  [`${relativeRoot}/src/workload.spec.ts`]: kind === 'service'
213
214
  ? `import { describe, expect, it } from 'vitest';\nimport { healthResponse } from './main.js';\n\ndescribe('${workload} service', () => {\n it('reports healthy only on the health endpoint', () => {\n expect(healthResponse('/health')).toEqual({ body: { service: '${workload}', status: 'ok' }, status: 200 });\n expect(healthResponse('/missing').status).toBe(404);\n });\n});\n`
214
215
  : `import { createLogger, type LogEntry } from '@empire-builder-kit/runtime/logging';\nimport { describe, expect, it } from 'vitest';\nimport { run } from './run.js';\n\ndescribe('${workload} job', () => {\n it('emits canonical start and completion records', async () => {\n const entries: LogEntry[] = [];\n const logger = createLogger({\n component: 'job-${workload}', feature: '${feature}', operation: 'run',\n slice: '${slice}', stage: 'test', workspace: '${workspace}',\n sink: (entry) => entries.push(entry as LogEntry),\n });\n await expect(run(logger)).resolves.toEqual({\n ok: true,\n providerDeliveryAssigned: false,\n });\n expect(entries.map(({ message, outcome }) => ({ message, outcome }))).toEqual([\n { message: '${workload} job started', outcome: undefined },\n { message: '${workload} job completed', outcome: 'success' },\n ]);\n });\n});\n`,
215
- [`${relativeRoot}/infra.ts`]: `import { createManagedLogGroupContract } from '@empire-builder-kit/nx/foundation';\nimport { standardSliceExtensionTaskFamily } from '../../infra/workload-roles/effective-intent.js';\n\nexport function ${factoryName}(\n cluster: any,\n alertTopicArn: any,\n roles?: { executionRole: string; taskRole: string },\n links: any[] = [],\n configuration?: {\n applicationId: any;\n deployment: any;\n environmentId: any;\n profileId: any;\n },\n) {\n const contract = createManagedLogGroupContract({\n component: '${kind}-${workload}',\n slice: '${slice}',\n stage: $app.stage,\n workspace: '${workspace}',\n });\n const workload = new sst.aws.${resource}('${className}', {\n ...(roles ?? {}),\n cluster,\n environment: {\n EBK_STAGE: $app.stage,\n ...(configuration\n ? {\n EBK_APPCONFIG_APPLICATION_ID: configuration.applicationId,\n EBK_APPCONFIG_ENVIRONMENT_ID: configuration.environmentId,\n EBK_APPCONFIG_PROFILE_ID: configuration.profileId,\n }\n : {}),\n },\n link: links,\n ${kind === 'service' ? "image: { context: './services/" + workload + "', dockerfile: 'Dockerfile' },\n health: { command: ['CMD-SHELL', 'wget -qO- http://localhost:3000/health || exit 1'] },\n logging: { name: contract.name, retention: '1 month' },\n serviceRegistry: { port: 3000 }," : "image: { context: './jobs/" + workload + "', dockerfile: 'Dockerfile' },\n logging: { name: contract.name, retention: '1 month' },"}\n transform: {\n logGroup: {\n logGroupClass: contract.logGroupClass,\n tags: contract.tags,\n },\n taskDefinition: {\n family: standardSliceExtensionTaskFamily(\n $app.stage,\n '${workload}',\n '${kind}',\n ),\n },\n },\n }, configuration?.deployment\n ? { dependsOn: [configuration.deployment] }\n : {});\n const dataProtection = new aws.cloudwatch.LogDataProtectionPolicy(\n '${className}LogDataProtection',\n {\n logGroupName: contract.name,\n policyDocument: JSON.stringify(contract.dataProtectionPolicy),\n },\n { dependsOn: [workload.nodes.taskDefinition] },\n );\n const dataProtectionAlarm = new aws.cloudwatch.MetricAlarm(\n '${className}LogDataProtectionFindings',\n {\n alarmActions: [alertTopicArn],\n comparisonOperator: 'GreaterThanOrEqualToThreshold',\n dimensions: { LogGroupName: contract.name },\n evaluationPeriods: 1,\n metricName: 'LogEventsWithFindings',\n namespace: 'AWS/Logs',\n period: 300,\n statistic: 'Sum',\n threshold: 1,\n treatMissingData: 'notBreaching',\n },\n { dependsOn: [dataProtection] },\n );\n void dataProtectionAlarm;\n return workload;\n}\n`,
216
+ [`${relativeRoot}/infra.ts`]: `import { createManagedLogGroupContract } from '@empire-builder-kit/nx/foundation';\nimport { standardSliceExtensionTaskFamily } from '../../infra/workload-roles/effective-intent.js';\n\nexport function ${factoryName}(\n cluster: any,\n alertTopicArn: any,\n roles?: { executionRole: string; taskRole: string },\n links: any[] = [],\n configuration?: {\n applicationId: any;\n deployment: any;\n environmentId: any;\n profileId: any;\n },\n) {\n const contract = createManagedLogGroupContract({\n component: '${kind}-${workload}',\n slice: '${slice}',\n stage: $app.stage,\n workspace: '${workspace}',\n });\n const workload = new sst.aws.${resource}('${className}', {\n ...(roles ?? {}),\n cluster,\n environment: {\n EBK_STAGE: $app.stage,\n ...(configuration\n ? {\n EBK_APPCONFIG_APPLICATION_ID: configuration.applicationId,\n EBK_APPCONFIG_ENVIRONMENT_ID: configuration.environmentId,\n EBK_APPCONFIG_PROFILE_ID: configuration.profileId,\n }\n : {}),\n },\n link: links,\n ${kind === 'service' ? "image: { context: './services/" + workload + "', dockerfile: 'Dockerfile' },\n health: { command: ['CMD-SHELL', 'wget -qO- http://localhost:3000/health || exit 1'] },\n logging: { name: contract.name, retention: '1 month' },\n serviceRegistry: { port: 3000 }," : "image: { context: './jobs/" + workload + "', dockerfile: 'Dockerfile' },\n logging: { name: contract.name, retention: '1 month' },"}\n transform: {\n logGroup: {\n logGroupClass: contract.logGroupClass,\n tags: contract.tags,\n },\n taskDefinition: {\n family: standardSliceExtensionTaskFamily(\n $app.stage,\n '${workload}',\n '${kind}',\n ),\n },\n },\n }, configuration?.deployment\n ? { dependsOn: [configuration.deployment] }\n : {});\n${kind === 'service' ? ' if ($dev) return workload;\n' : ''} const dataProtection = new aws.cloudwatch.LogDataProtectionPolicy(\n '${className}LogDataProtection',\n {\n logGroupName: contract.name,\n policyDocument: JSON.stringify(contract.dataProtectionPolicy),\n },\n { dependsOn: [workload.nodes.taskDefinition] },\n );\n const dataProtectionAlarm = new aws.cloudwatch.MetricAlarm(\n '${className}LogDataProtectionFindings',\n {\n alarmActions: [alertTopicArn],\n comparisonOperator: 'GreaterThanOrEqualToThreshold',\n dimensions: { LogGroupName: contract.name },\n evaluationPeriods: 1,\n metricName: 'LogEventsWithFindings',\n namespace: 'AWS/Logs',\n period: 300,\n statistic: 'Sum',\n threshold: 1,\n treatMissingData: 'notBreaching',\n },\n { dependsOn: [dataProtection] },\n );\n void dataProtectionAlarm;\n return workload;\n}\n`,
216
217
  };
217
218
  if (kind === 'service') {
218
219
  const serviceMainPath = `${relativeRoot}/src/main.ts`;
@@ -311,6 +312,7 @@ ${kind !== 'service' || ownsProtectedLoadAdapter
311
312
  : ''}${kind === 'service' && ownsProtectedLoadAdapter
312
313
  ? ` performanceIngress: {
313
314
  api: any;
315
+ apiPathPrefix: string;
314
316
  originProof: any;
315
317
  router: any;
316
318
  } | undefined,
@@ -413,7 +415,7 @@ ${kind !== 'service' || ownsProtectedLoadAdapter
413
415
  alarmDescription: JSON.stringify({
414
416
  businessSymptom:
415
417
  '${kind === 'service'
416
- ? `${workload} Service has no running task.`
418
+ ? `${workload} Service task presence is below one or telemetry is missing.`
417
419
  : `${workload} Job essential container exited.`}',
418
420
  id: '${kind === 'service'
419
421
  ? `service-${workload}-health`
@@ -428,14 +430,14 @@ ${kind !== 'service' || ownsProtectedLoadAdapter
428
430
  ? 'LessThanThreshold'
429
431
  : 'GreaterThanOrEqualToThreshold'}',
430
432
  dimensions: ${kind === 'service'
431
- ? `{ ClusterName: cluster.name, ServiceName: workload.name }`
433
+ ? `{ ClusterName: cluster.nodes.cluster.name, ServiceName: workload.nodes.service.name }`
432
434
  : `{ RuleName: reliabilityTaskStopped.name }`},
433
435
  evaluationPeriods: 1,
434
- metricName: '${kind === 'service' ? 'RunningTaskCount' : 'MatchedEvents'}',
436
+ metricName: '${kind === 'service' ? 'LiveTaskCount' : 'MatchedEvents'}',
435
437
  name: '${slice}-' + $app.stage + '-${kind}-${workload}-${kind === 'service' ? 'running' : 'hard-crash'}',
436
- namespace: '${kind === 'service' ? 'ECS/ContainerInsights' : 'AWS/Events'}',
438
+ namespace: '${kind === 'service' ? 'AWS/ECS' : 'AWS/Events'}',
437
439
  period: 60,
438
- statistic: 'Sum',
440
+ statistic: '${kind === 'service' ? 'Minimum' : 'Sum'}',
439
441
  tags: standardTags,
440
442
  threshold: 1,
441
443
  treatMissingData: '${kind === 'service' ? 'breaching' : 'notBreaching'}',
@@ -527,6 +529,16 @@ ${kind !== 'service' || ownsProtectedLoadAdapter
527
529
  connectionAttempts: 1,
528
530
  connectionTimeout: '3 seconds',
529
531
  readTimeout: '30 seconds',
532
+ // API Gateway strips a custom-domain API's /<slice> mapping path
533
+ // before route matching, so the edge adds it once more.
534
+ ...(performanceIngress.apiPathPrefix
535
+ ? {
536
+ rewrite: {
537
+ regex: '^/',
538
+ to: performanceIngress.apiPathPrefix + '/',
539
+ },
540
+ }
541
+ : {}),
530
542
  },
531
543
  );
532
544
  performanceIngress.router.route(
@@ -536,6 +548,16 @@ ${kind !== 'service' || ownsProtectedLoadAdapter
536
548
  connectionAttempts: 1,
537
549
  connectionTimeout: '3 seconds',
538
550
  readTimeout: '30 seconds',
551
+ // API Gateway strips a custom-domain API's /<slice> mapping path
552
+ // before route matching, so the edge adds it once more.
553
+ ...(performanceIngress.apiPathPrefix
554
+ ? {
555
+ rewrite: {
556
+ regex: '^/',
557
+ to: performanceIngress.apiPathPrefix + '/',
558
+ },
559
+ }
560
+ : {}),
539
561
  },
540
562
  );
541
563
  }
@@ -551,7 +573,25 @@ through the read-only diagnostic path. Do not restart, scale, retry, or replace
551
573
  protected resources without the named approval.
552
574
 
553
575
  ${kind === 'service'
554
- ? 'Prefer a verified roll-forward; verify readiness, dependency protection, and the critical Service journey after recovery.'
576
+ ? `The native AWS/ECS LiveTaskCount alarm uses Minimum over 60 seconds and
577
+ counts tasks in ACTIVATING, RUNNING, and DEACTIVATING states. It breaches below
578
+ one or when telemetry is missing. ECS can emit no metrics when there are no
579
+ RUNNING tasks; missing telemetry is actionable but does not prove zero tasks.
580
+
581
+ Startup, emission gaps, and lifecycle transitions can cause false positives.
582
+ Activating, draining, or repeatedly replaced tasks can keep the count positive
583
+ while readiness or useful work fails. ALARM is not a diagnosis. OK does not
584
+ prove readiness, freedom from crash loops, or successful business traffic.
585
+
586
+ Inspect ECS events, task states and exit reasons, the existing container health
587
+ check, and the Slice API health and burn alarms. Do not infer that every Service
588
+ has a load-balancer readiness alarm. Prefer a verified roll-forward; verify
589
+ stable tasks, readiness, dependency protection, and the critical Service journey
590
+ after recovery, then confirm telemetry and alarm recovery.
591
+
592
+ LiveTaskCount adds no metric collection charge and needs no Container Insights
593
+ opt-in. Existing alarm, compute, log, and request charges still apply; this is
594
+ not a measured account-cost claim.`
555
595
  : 'Preserve idempotency and checkpoint state; verify the business deadline and postconditions before retrying or declaring recovery.'}
556
596
  `;
557
597
  files[`${relativeRoot}/src/reliability.ts`] = `import {
@@ -1037,6 +1077,24 @@ describe('${workload} ${kind} outage behavior', () => {
1037
1077
  project: `@${slice}/${kind}-${workload}`,
1038
1078
  };
1039
1079
  }
1080
+ /**
1081
+ * Every `apiPathPrefix: publicDomain ? '/<slice>' : '',` member of a Slice's
1082
+ * infra/product.ts, on one line or wrapped across several.
1083
+ */
1084
+ function apiPathPrefixMember(slice) {
1085
+ const name = slice.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
1086
+ return new RegExp(`apiPathPrefix:\\s*publicDomain\\s*\\?\\s*'/${name}'\\s*:\\s*''\\s*,`, 'gu');
1087
+ }
1088
+ /**
1089
+ * Every ` const api = new sst.aws.ApiGatewayV2('<Pascal>Api', {` opening of
1090
+ * a Slice's infra/product.ts, on one line or wrapped. Prettier puts the
1091
+ * call's arguments on their own lines once the PascalCase name is 34
1092
+ * characters or more, at the generated workspace's 80-column print width.
1093
+ */
1094
+ function sliceApiOpening(slice) {
1095
+ const name = pascal(slice).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
1096
+ return new RegExp(` const api = new sst\\.aws\\.ApiGatewayV2\\(\\s*'${name}Api',\\s*\\{`, 'gu');
1097
+ }
1040
1098
  async function executeWorkloadGenerator(tree, options, kind) {
1041
1099
  const slice = name(options.slice, 'Product Slice name');
1042
1100
  const workload = name(options.name, kind === 'service' ? 'Service name' : 'Job name');
@@ -1141,6 +1199,18 @@ async function executeWorkloadGenerator(tree, options, kind) {
1141
1199
  sliceRoot,
1142
1200
  workspace,
1143
1201
  });
1202
+ // The Service that owns the protected-load adapter types its ingress with
1203
+ // the API mapping path; a managed product.ts from before that member would
1204
+ // not typecheck against it. Prettier wraps the member's ternary for a long
1205
+ // Slice name, so the match allows any whitespace between its tokens. On a
1206
+ // Slice the upgrade refuses, the message says so and why, instead of
1207
+ // sending the adopter into that refusal.
1208
+ if (kind === 'service' &&
1209
+ performanceRegistration.ownsProtectedLoadAdapter &&
1210
+ (tree.read(productPath, 'utf8') ?? '').match(apiPathPrefixMember(slice))
1211
+ ?.length !== 1) {
1212
+ throw new Error((0, external_blueprint_compositions_js_1.upgradeSliceFirst)(tree, sliceRoot, `Product Slice ${slice} has no managed API mapping path for its protected-load ingress in ${productPath}`));
1213
+ }
1144
1214
  const reliabilityRegistration = (0, reliability_registration_js_1.planWorkloadReliabilityRegistration)(tree, {
1145
1215
  feature,
1146
1216
  kind,
@@ -1190,11 +1260,15 @@ async function executeWorkloadGenerator(tree, options, kind) {
1190
1260
  const source = tree.read(productPath, 'utf8');
1191
1261
  if (source === null)
1192
1262
  throw new Error('Product Slice API source is missing; no workload files changed.');
1193
- const anchor = ` const api = new sst.aws.ApiGatewayV2('${pascal(slice)}Api', {`;
1194
- if (source.split(anchor).length !== 2)
1263
+ const opening = sliceApiOpening(slice);
1264
+ if (source.match(opening)?.length !== 1)
1195
1265
  throw new Error('Product Slice API composition is not recognized; no workload files changed.');
1196
- tree.write(productPath, source.replace(anchor, anchor +
1197
- '\n ...(performanceDeploymentAuthority ? { vpc: foundation.vpc } : {}),'));
1266
+ tree.write(productPath, source.replace(opening, (text) => {
1267
+ // One level deeper than the line that holds the opening brace.
1268
+ const braceLine = text.slice(text.lastIndexOf('\n') + 1);
1269
+ const indent = /^ */u.exec(braceLine)?.[0] ?? '';
1270
+ return `${text}\n${indent} ...(performanceDeploymentAuthority ? { vpc: foundation.vpc } : {}),`;
1271
+ }));
1198
1272
  }
1199
1273
  tree.write(foundationPath, (0, built_in_plan_foundation_files_js_1.renderSliceFoundationFiles)(slice, pascal(slice), foundationRequirement.capabilities)['infra/foundation.ts']);
1200
1274
  const infraRelative = `../${plural}/${workload}/infra.js`;
@@ -16,12 +16,13 @@ export declare const EBK_STAGING_PROMOTION_PULL_ROLE_SECRET = "AWS_STAGING_PROMO
16
16
  export declare const EBK_PROTECTED_ENVIRONMENT_SECRETS: readonly ["AWS_ASYNC_RECOVERY_ROLE_ARN", "AWS_ECR_INSPECTOR_EVIDENCE_ROLE_ARN", "AWS_DEPLOY_ROLE_ARN", "AWS_STAGING_PROMOTION_PULL_ROLE_ARN"];
17
17
  export declare const EBK_PROTECTED_ENVIRONMENT_VARIABLES: readonly ["AWS_EXPECTED_ACCOUNT_ID", "AWS_REGION", "AWS_STAGING_PROMOTION_EXPECTED_ACCOUNT_ID", "AWS_STAGING_PROMOTION_REGION", "EBK_ALLOW_PRODUCTION_REMOVE", "EBK_FLEET_ORIGIN"];
18
18
  /**
19
- * Non-secret stage environment variables an operator may set to request a
20
- * machine credential generation or its retirement on a workflow deploy. They
21
- * are never required, and a repository- or organization-scoped copy would
22
- * silently apply to every stage, so only the stage environment may hold them.
19
+ * Non-secret stage environment variables an operator may set on a workflow
20
+ * deploy to request a database credential generation, a machine credential
21
+ * generation, or the machine generation's retirement. They are never
22
+ * required, and a repository- or organization-scoped copy would silently
23
+ * apply to every stage, so only the stage environment may hold them.
23
24
  */
24
- export declare const EBK_OPTIONAL_STAGE_ENVIRONMENT_VARIABLES: readonly ["EBK_MACHINE_CREDENTIAL_GENERATION", "EBK_MACHINE_RETIRE_PREVIOUS_GENERATION"];
25
+ export declare const EBK_OPTIONAL_STAGE_ENVIRONMENT_VARIABLES: readonly ["EBK_DATABASE_CREDENTIAL_GENERATION", "EBK_MACHINE_CREDENTIAL_GENERATION", "EBK_MACHINE_RETIRE_PREVIOUS_GENERATION"];
25
26
  export declare const EBK_CODE_OWNER_PLACEHOLDER: "@REPLACE_WITH_GITHUB_CODE_OWNER";
26
27
  type GitHubEnvironmentStage = 'development' | 'production' | 'staging';
27
28
  type GitHubAuxiliaryEnvironment = 'async-recovery' | 'ecr-inspector';
@@ -72,5 +73,23 @@ export interface GitHubRepositoryIdentity {
72
73
  repositoryId: string;
73
74
  subjectPrefix: string;
74
75
  }
76
+ export interface FrameworkNpmStableBootstrapOptions {
77
+ npmStable: true;
78
+ apiBaseUrl?: string;
79
+ apply?: boolean;
80
+ repository: string;
81
+ token: string;
82
+ npmStableReviewerIds: number[];
83
+ npmStablePreventSelfReview: boolean;
84
+ }
85
+ export interface FrameworkNpmStableBootstrapReport {
86
+ kind: 'framework-npm-stable';
87
+ repository: string;
88
+ ready: boolean;
89
+ blockers: string[];
90
+ changes: string[];
91
+ warnings: string[];
92
+ }
93
+ export declare function runGitHubBootstrap(options: FrameworkNpmStableBootstrapOptions): Promise<FrameworkNpmStableBootstrapReport>;
75
94
  export declare function runGitHubBootstrap(options: GitHubBootstrapOptions): Promise<GitHubBootstrapReport>;
76
95
  export {};
@@ -34,12 +34,14 @@ exports.EBK_PROTECTED_ENVIRONMENT_VARIABLES = [
34
34
  'EBK_FLEET_ORIGIN',
35
35
  ];
36
36
  /**
37
- * Non-secret stage environment variables an operator may set to request a
38
- * machine credential generation or its retirement on a workflow deploy. They
39
- * are never required, and a repository- or organization-scoped copy would
40
- * silently apply to every stage, so only the stage environment may hold them.
37
+ * Non-secret stage environment variables an operator may set on a workflow
38
+ * deploy to request a database credential generation, a machine credential
39
+ * generation, or the machine generation's retirement. They are never
40
+ * required, and a repository- or organization-scoped copy would silently
41
+ * apply to every stage, so only the stage environment may hold them.
41
42
  */
42
43
  exports.EBK_OPTIONAL_STAGE_ENVIRONMENT_VARIABLES = [
44
+ 'EBK_DATABASE_CREDENTIAL_GENERATION',
43
45
  'EBK_MACHINE_CREDENTIAL_GENERATION',
44
46
  'EBK_MACHINE_RETIRE_PREVIOUS_GENERATION',
45
47
  ];
@@ -203,11 +205,7 @@ function requiresImmutableOidcSubjectCutover(state) {
203
205
  function immutableOidcTrustAcknowledgement(identity) {
204
206
  return `${GITHUB_IMMUTABLE_OIDC_TRUST_ACKNOWLEDGEMENT_PREFIX}${identity.subjectPrefix}`;
205
207
  }
206
- const PRIVATE_ENVIRONMENT_REVIEWER_PLANS = new Set([
207
- 'business_plus',
208
- 'enterprise',
209
- 'enterprise_cloud',
210
- ]);
208
+ const PRIVATE_ENVIRONMENT_REVIEWER_PLANS = new Set(['enterprise']);
211
209
  class GitHubApiError extends Error {
212
210
  status;
213
211
  constructor(status, message) {
@@ -575,6 +573,14 @@ async function inspectEnvironment(api, repositoryPath, name) {
575
573
  branchPolicies: branchPolicyValues,
576
574
  customBranchPolicies,
577
575
  exists: true,
576
+ canAdminsBypass: environment.can_admins_bypass === false ? false : true,
577
+ protectedBranches: typeof environment.deployment_branch_policy === 'object' &&
578
+ environment.deployment_branch_policy !== null &&
579
+ 'protected_branches' in environment.deployment_branch_policy &&
580
+ typeof environment.deployment_branch_policy.protected_branches ===
581
+ 'boolean'
582
+ ? environment.deployment_branch_policy.protected_branches
583
+ : undefined,
578
584
  preventSelfReview: reviewers.preventSelfReview,
579
585
  reviewers: reviewers.reviewers,
580
586
  secretNames: namedValues(secrets),
@@ -786,7 +792,7 @@ function evaluate(repository, state, inspectionBlockers, productionApprovalMode,
786
792
  privateRepository &&
787
793
  state.ownerPlanName !== undefined &&
788
794
  !PRIVATE_ENVIRONMENT_REVIEWER_PLANS.has(state.ownerPlanName)) {
789
- blockers.push(`Committed environment-reviewer mode requires GitHub Enterprise support for a private repository; the inspected owner plan is ${state.ownerPlanName}.`);
795
+ blockers.push(`Committed environment-reviewer mode does not support inspected owner plan ${state.ownerPlanName} under EBK's verified private environment-reviewer contract; supported REST plan.name: enterprise.`);
790
796
  }
791
797
  if (state.repo.allow_merge_commit !== true) {
792
798
  changes.push('Enable repository merge commits.');
@@ -1099,7 +1105,96 @@ async function applyChanges(api, repositoryPath, state, productionApprovalMode,
1099
1105
  }
1100
1106
  }
1101
1107
  }
1108
+ async function runFrameworkNpmStableBootstrap(options) {
1109
+ if (options.repository !== 'empire-builder-kit/empire-builder-kit')
1110
+ throw new Error('npm-stable is restricted to the exact framework repository.');
1111
+ if (!options.token.trim())
1112
+ throw new Error('GH_TOKEN or GITHUB_TOKEN is required for GitHub bootstrap.');
1113
+ if (!Array.isArray(options.npmStableReviewerIds) ||
1114
+ options.npmStableReviewerIds.length < 1 ||
1115
+ options.npmStableReviewerIds.length > 6 ||
1116
+ options.npmStableReviewerIds.some((id) => !Number.isSafeInteger(id) || id <= 0) ||
1117
+ new Set(options.npmStableReviewerIds).size !==
1118
+ options.npmStableReviewerIds.length ||
1119
+ typeof options.npmStablePreventSelfReview !== 'boolean') {
1120
+ throw new Error('npm-stable requires exact reviewer IDs and explicit prevent-self-review choice.');
1121
+ }
1122
+ const reviewers = existingReviewerPayload([...options.npmStableReviewerIds].sort((left, right) => left - right));
1123
+ const api = new GitHubApi(options.apiBaseUrl?.trim() || 'https://api.github.com', options.token);
1124
+ const repositoryPath = '/repos/empire-builder-kit/empire-builder-kit';
1125
+ const repo = await api.request('GET', repositoryPath);
1126
+ if (repo.full_name !== options.repository)
1127
+ throw new Error('npm-stable repository readback differs from its exact target.');
1128
+ const environmentPath = `${repositoryPath}/environments/npm-stable`;
1129
+ const inspectStable = () => inspectEnvironment(api, repositoryPath, 'npm-stable');
1130
+ const evaluateStable = (state) => {
1131
+ const changes = [];
1132
+ const blockers = [];
1133
+ if (!state.exists ||
1134
+ !state.customBranchPolicies ||
1135
+ state.protectedBranches !== false ||
1136
+ state.canAdminsBypass !== false ||
1137
+ state.preventSelfReview !== options.npmStablePreventSelfReview ||
1138
+ state.waitTimer !== 0 ||
1139
+ JSON.stringify(state.reviewers) !== JSON.stringify(reviewers)) {
1140
+ changes.push('Set exact npm-stable reviewers, explicit self-review choice, administrator bypass false, and custom main-only policy.');
1141
+ }
1142
+ if (state.branchPolicies.length !== 1 ||
1143
+ state.branchPolicies[0]?.name !== 'main' ||
1144
+ state.branchPolicies[0]?.type !== 'branch')
1145
+ changes.push('Restrict npm-stable to the main branch only.');
1146
+ if ([...state.secretNames, ...state.variableNames].some((name) => FORBIDDEN_NPM_TOKEN_NAMES.some((tokenName) => name.toUpperCase() === tokenName)))
1147
+ blockers.push('npm-stable may not contain npm token credentials.');
1148
+ return {
1149
+ kind: 'framework-npm-stable',
1150
+ repository: options.repository,
1151
+ ready: changes.length === 0 && blockers.length === 0,
1152
+ blockers,
1153
+ changes,
1154
+ warnings: [],
1155
+ };
1156
+ };
1157
+ const initial = await inspectStable();
1158
+ const report = evaluateStable(initial);
1159
+ if (!options.apply)
1160
+ return report;
1161
+ if (report.blockers.length)
1162
+ throw new Error(`npm-stable apply is blocked: ${report.blockers.join(' ')}`);
1163
+ if (report.ready)
1164
+ return report;
1165
+ await api.request('PUT', environmentPath, {
1166
+ can_admins_bypass: false,
1167
+ deployment_branch_policy: {
1168
+ protected_branches: false,
1169
+ custom_branch_policies: true,
1170
+ },
1171
+ prevent_self_review: options.npmStablePreventSelfReview,
1172
+ reviewers,
1173
+ wait_timer: 0,
1174
+ });
1175
+ const policies = await readPagedObjects(api, `${environmentPath}/deployment-branch-policies`, 'branch_policies');
1176
+ let mainRetained = false;
1177
+ for (const policy of policies) {
1178
+ if (policy.name === 'main' && policy.type === 'branch' && !mainRetained) {
1179
+ mainRetained = true;
1180
+ continue;
1181
+ }
1182
+ if (!Number.isSafeInteger(policy.id) ||
1183
+ typeof policy.id !== 'number' ||
1184
+ policy.id <= 0)
1185
+ throw new Error('npm-stable branch policy has no exact deletion identity.');
1186
+ await api.request('DELETE', `${environmentPath}/deployment-branch-policies/${policy.id}`);
1187
+ }
1188
+ if (!mainRetained)
1189
+ await api.request('POST', `${environmentPath}/deployment-branch-policies`, {
1190
+ name: 'main',
1191
+ type: 'branch',
1192
+ });
1193
+ return evaluateStable(await inspectStable());
1194
+ }
1102
1195
  async function runGitHubBootstrap(options) {
1196
+ if ('npmStable' in options)
1197
+ return runFrameworkNpmStableBootstrap(options);
1103
1198
  const repository = options.repository.trim();
1104
1199
  const deploymentProfile = options.deploymentProfile ?? 'fully-isolated';
1105
1200
  const { owner, repo } = parseRepository(repository);
@@ -1,4 +1,4 @@
1
- import { type ChildProcess } from 'node:child_process';
1
+ import { type ChildProcess, type SpawnOptions } from 'node:child_process';
2
2
  import type { LocalDevAdapter } from './contracts.js';
3
3
  import type { FleetLogStore } from './fleet-logs.js';
4
4
  import type { FleetProcessIdentity } from './fleet-lock.js';
@@ -70,7 +70,14 @@ export declare function planFleetRestart(completedRestartAttempts: number, maxRe
70
70
  restart: true;
71
71
  };
72
72
  export declare function assertOwnedGroupAbsent(pid: number, deadline?: number): Promise<void>;
73
- export declare function terminateOwnedChild(child: ChildProcess, ownedIdentity?: FleetProcessIdentity): Promise<void>;
73
+ /** Seams that let every host exercise the native Windows tree kill. */
74
+ export interface OwnedChildTerminationEffects {
75
+ /** The environment that names SystemRoot; defaults to this process's. */
76
+ environment?: NodeJS.ProcessEnv;
77
+ platform?: NodeJS.Platform;
78
+ spawn?: (command: string, arguments_: readonly string[], options: SpawnOptions) => ChildProcess;
79
+ }
80
+ export declare function terminateOwnedChild(child: ChildProcess, ownedIdentity?: FleetProcessIdentity, effects?: OwnedChildTerminationEffects): Promise<void>;
74
81
  export declare const FLEET_RUNNER_STOP_MESSAGE = "ebk-fleet-runner-stop";
75
82
  export declare const FLEET_RUNNER_QUIESCE_MESSAGE = "ebk-fleet-runner-quiesce";
76
83
  export declare const FLEET_RUNNER_QUIESCED_MESSAGE = "ebk-fleet-runner-quiesced";
@@ -67,8 +67,10 @@ async function waitForOwnedExit(exited, timeoutMs) {
67
67
  }
68
68
  }
69
69
  async function assertOwnedGroupAbsent(pid, deadline = Date.now() + 1_000) {
70
- // Native Windows retains its existing taskkill contract. This POSIX proof
71
- // is not a claim that Windows orphan trees can be inspected after exit.
70
+ // Windows has no process group to probe once its leader exits, and taskkill
71
+ // /t cannot reach descendants through an exited parent. terminateOwnedChild
72
+ // proves the leader's own exit; descendant absence stays unproved, part of
73
+ // the accepted native-Windows Fleet deferral.
72
74
  if (process.platform === 'win32')
73
75
  return;
74
76
  while ((0, process_group_js_1.exactOwnedProcessGroupExists)(pid)) {
@@ -77,7 +79,7 @@ async function assertOwnedGroupAbsent(pid, deadline = Date.now() + 1_000) {
77
79
  await new Promise((resolve) => setTimeout(resolve, 25));
78
80
  }
79
81
  }
80
- async function terminateOwnedChild(child, ownedIdentity) {
82
+ async function terminateOwnedChild(child, ownedIdentity, effects = {}) {
81
83
  if (!child.pid)
82
84
  throw new errors_js_1.LocalDevContractError('cleanup-incomplete', 'Owned child PID is unavailable.');
83
85
  if (child.exitCode !== null || child.signalCode !== null) {
@@ -86,13 +88,31 @@ async function terminateOwnedChild(child, ownedIdentity) {
86
88
  }
87
89
  const deadline = Date.now() + process_group_js_1.OWNED_PROCESS_SIGNAL_GRACE_MS + process_group_js_1.OWNED_PROCESS_KILL_WAIT_MS;
88
90
  const exited = new Promise((resolvePromise) => child.once('exit', () => resolvePromise()));
89
- if (process.platform === 'win32' && child.pid) {
90
- const killer = (0, node_child_process_1.spawn)('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
91
+ if ((effects.platform ?? process.platform) === 'win32' && child.pid) {
92
+ // A bare name would resolve through the adopter checkout before PATH, so
93
+ // without the canonical system binary nothing is signaled.
94
+ let taskkill;
95
+ try {
96
+ taskkill = (0, process_group_js_1.exactWindowsTaskkill)(effects.environment ?? process.env);
97
+ }
98
+ catch (error) {
99
+ throw new errors_js_1.LocalDevContractError('cleanup-incomplete', `Owned child process tree was not signaled; ownership is retained. ${error instanceof Error ? error.message : String(error)}`);
100
+ }
101
+ // taskkill /f only requests termination, and its status proves nothing
102
+ // either way: /t also fails when a member exits during its walk. Only the
103
+ // leader's own exit is proof. Node's open handle keeps its PID from reuse.
104
+ const killer = (effects.spawn ?? node_child_process_1.spawn)(taskkill.executable, ['/pid', String(child.pid), '/t', '/f'], {
105
+ env: { SystemRoot: taskkill.systemRoot },
106
+ shell: false,
91
107
  stdio: 'ignore',
92
108
  windowsHide: true,
93
109
  });
94
- await new Promise((resolvePromise) => killer.once('exit', () => resolvePromise()));
95
- await waitForOwnedExit(exited, 2_000);
110
+ const requested = await new Promise((resolvePromise) => {
111
+ killer.once('error', (error) => resolvePromise(error.message));
112
+ killer.once('exit', (code, signal) => resolvePromise(`taskkill ${describeExit({ code, signal })}`));
113
+ });
114
+ if (!(await waitForOwnedExit(exited, Math.max(0, deadline - Date.now()))))
115
+ throw new errors_js_1.LocalDevContractError('cleanup-incomplete', `Owned child did not exit after ${requested}; ownership is retained.`);
96
116
  return;
97
117
  }
98
118
  const identity = ownedIdentity ?? (0, process_identity_js_1.captureProcessIdentity)(child.pid);
@@ -22,6 +22,7 @@ class FleetSession {
22
22
  #cleanupStates = new Map();
23
23
  #fleetId;
24
24
  #operation = Promise.resolve();
25
+ #pendingStartup;
25
26
  #processFactory;
26
27
  #processes = new Map();
27
28
  #proxy;
@@ -144,7 +145,19 @@ class FleetSession {
144
145
  upstream: route.upstream,
145
146
  });
146
147
  this.#processes.set(name, process);
147
- await process.start();
148
+ const pending = {
149
+ name,
150
+ process,
151
+ interruptionRequested: false,
152
+ };
153
+ this.#pendingStartup = pending;
154
+ try {
155
+ await process.start();
156
+ }
157
+ finally {
158
+ if (this.#pendingStartup === pending)
159
+ this.#pendingStartup = undefined;
160
+ }
148
161
  }
149
162
  }
150
163
  catch (error) {
@@ -228,7 +241,28 @@ class FleetSession {
228
241
  return sessionError('not-running', `Product Slice ${name} is not selected.`);
229
242
  }
230
243
  const previousState = route.state;
231
- await process.restart();
244
+ const pending = {
245
+ name,
246
+ process,
247
+ interruptionRequested: false,
248
+ };
249
+ this.#pendingStartup = pending;
250
+ try {
251
+ await process.restart();
252
+ }
253
+ catch (error) {
254
+ if (pending.interruptionRequested) {
255
+ const failures = await this.#quiesce([name]);
256
+ if (failures.length > 0) {
257
+ return sessionError('cleanup-incomplete', `Fleet restart failed (${startupFailure(error)}) and owned writer quiescence was incomplete: ${failures.join('; ')}`);
258
+ }
259
+ }
260
+ throw error;
261
+ }
262
+ finally {
263
+ if (this.#pendingStartup === pending)
264
+ this.#pendingStartup = undefined;
265
+ }
232
266
  results.push({
233
267
  changed: true,
234
268
  name,
@@ -314,8 +348,11 @@ class FleetSession {
314
348
  // running up operation owns rollback; down waits for that rollback rather
315
349
  // than racing a second native cleanup against a live writer.
316
350
  const ordered = (0, contracts_js_1.resolveFleetSliceOperation)(this.#adapters, 'down', names, this.selectedSlices());
317
- for (const name of ordered)
318
- this.#processes.get(name)?.interruptStartup?.();
351
+ const pending = this.#pendingStartup;
352
+ if (pending && ordered.includes(pending.name)) {
353
+ pending.interruptionRequested = true;
354
+ pending.process.interruptStartup?.();
355
+ }
319
356
  }
320
357
  allSlices() {
321
358
  return this.routes.map(({ name }) => name).sort();