@empire-builder-kit/nx 1.0.0-rc.46 → 1.0.0-rc.48

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 (780) hide show
  1. package/README.md +14 -169
  2. package/executors.json +24 -79
  3. package/generators.json +18 -18
  4. package/package.json +13 -71
  5. package/src/aws/identity.d.ts +1 -1
  6. package/src/aws-authority/boundary-transforms.d.ts +9 -0
  7. package/src/aws-authority/boundary-transforms.js +78 -0
  8. package/src/aws-authority/contracts.d.ts +116 -0
  9. package/src/aws-authority/contracts.js +40 -0
  10. package/src/aws-authority/deployment-guardrails.d.ts +4 -0
  11. package/src/aws-authority/deployment-guardrails.js +543 -0
  12. package/src/aws-authority/deployment-policy-groups.d.ts +3 -0
  13. package/src/aws-authority/deployment-policy-groups.js +299 -0
  14. package/src/aws-authority/deployment-resources.d.ts +64 -0
  15. package/src/aws-authority/deployment-resources.js +265 -0
  16. package/src/aws-authority/deployment-services.d.ts +3 -0
  17. package/src/aws-authority/deployment-services.js +717 -0
  18. package/src/aws-authority/development-authority.d.ts +11 -0
  19. package/src/aws-authority/development-authority.js +160 -0
  20. package/src/aws-authority/guardrail-actions.d.ts +87 -0
  21. package/src/aws-authority/guardrail-actions.js +463 -0
  22. package/src/aws-authority/policy-document.d.ts +15 -0
  23. package/src/aws-authority/policy-document.js +264 -0
  24. package/src/aws-authority/runtime-boundary.d.ts +7 -0
  25. package/src/aws-authority/runtime-boundary.js +211 -0
  26. package/src/aws-authority/service-actions.d.ts +96 -0
  27. package/src/aws-authority/service-actions.js +512 -0
  28. package/src/aws-authority/stage-authority.d.ts +6 -244
  29. package/src/aws-authority/stage-authority.js +114 -3419
  30. package/src/aws-authority/stage-identity.d.ts +6 -0
  31. package/src/aws-authority/stage-identity.js +134 -0
  32. package/src/cli/bootstrap.d.ts +0 -20
  33. package/src/cli/bootstrap.js +2 -153
  34. package/src/cli/dev-command.d.ts +2 -4
  35. package/src/cli/dev-command.js +1 -19
  36. package/src/cli/main.d.ts +0 -4
  37. package/src/cli/main.js +22 -80
  38. package/src/cli/output.d.ts +2 -4
  39. package/src/cli/output.js +2 -8
  40. package/src/executors/deployment-plan/deployment-plan.d.ts +0 -2
  41. package/src/executors/deployment-plan/deployment-plan.js +5 -67
  42. package/src/executors/dev-doctor/dev-doctor.d.ts +25 -3
  43. package/src/executors/dev-doctor/dev-doctor.js +137 -50
  44. package/src/executors/dev-setup/dev-setup.d.ts +18 -1
  45. package/src/executors/dev-setup/dev-setup.js +320 -196
  46. package/src/executors/foundation-preflight/foundation-preflight.js +9 -1
  47. package/src/executors/foundation-remove-preflight/foundation-remove-preflight.js +2 -2
  48. package/src/executors/local-deploy/deployed-smoke.d.ts +12 -0
  49. package/src/executors/local-deploy/deployed-smoke.js +115 -0
  50. package/src/executors/local-deploy/deployment-authority.d.ts +24 -0
  51. package/src/executors/local-deploy/deployment-authority.js +81 -0
  52. package/src/executors/local-deploy/deployment-child.d.ts +18 -0
  53. package/src/executors/local-deploy/deployment-child.js +77 -0
  54. package/src/executors/local-deploy/deployment-contracts.d.ts +96 -0
  55. package/src/executors/local-deploy/deployment-contracts.js +3 -0
  56. package/src/executors/local-deploy/deployment-projects.d.ts +4 -0
  57. package/src/executors/local-deploy/deployment-projects.js +16 -0
  58. package/src/executors/local-deploy/deployment-receipt.d.ts +4 -0
  59. package/src/executors/local-deploy/deployment-receipt.js +55 -0
  60. package/src/executors/local-deploy/deployment-scope.d.ts +17 -0
  61. package/src/executors/local-deploy/deployment-scope.js +239 -0
  62. package/src/executors/local-deploy/deployment-source.d.ts +13 -0
  63. package/src/executors/local-deploy/deployment-source.js +86 -0
  64. package/src/executors/local-deploy/local-deploy.d.ts +5 -106
  65. package/src/executors/local-deploy/local-deploy.js +56 -855
  66. package/src/executors/sst-lifecycle/governed-child-process.d.ts +27 -0
  67. package/src/executors/sst-lifecycle/governed-child-process.js +277 -0
  68. package/src/executors/sst-lifecycle/governed-native-operation.js +4 -10
  69. package/src/executors/sst-lifecycle/run-sst-command.d.ts +4 -85
  70. package/src/executors/sst-lifecycle/run-sst-command.js +28 -788
  71. package/src/executors/sst-lifecycle/sst-contracts.d.ts +44 -0
  72. package/src/executors/sst-lifecycle/sst-contracts.js +3 -0
  73. package/src/executors/sst-lifecycle/sst-invocation.d.ts +17 -0
  74. package/src/executors/sst-lifecycle/sst-invocation.js +502 -0
  75. package/src/executors/sst-lifecycle/task-unlock.js +3 -3
  76. package/src/foundation/discovery.d.ts +1 -5
  77. package/src/foundation/discovery.js +0 -2
  78. package/src/foundation/identity-domain-parent-ready.d.ts +91 -0
  79. package/src/foundation/identity-domain-parent-ready.js +333 -0
  80. package/src/foundation/identity-domain.d.ts +94 -0
  81. package/src/foundation/identity-domain.js +115 -0
  82. package/src/foundation/index.d.ts +2 -2
  83. package/src/foundation/index.js +7 -9
  84. package/src/foundation/local-private-smoke-access.d.ts +6 -15
  85. package/src/foundation/local-private-smoke-access.js +8 -192
  86. package/src/foundation/observability.d.ts +16 -26
  87. package/src/foundation/observability.js +34 -135
  88. package/src/foundation/preflight.js +16 -14
  89. package/src/foundation/private-smoke-access.d.ts +7 -14
  90. package/src/foundation/private-smoke-access.js +4 -126
  91. package/src/foundation/root-site-workspace.d.ts +35 -0
  92. package/src/foundation/root-site-workspace.js +80 -0
  93. package/src/foundation/root-site.d.ts +82 -0
  94. package/src/foundation/root-site.js +276 -0
  95. package/src/generators/formatting.js +5 -4
  96. package/src/generators/framework-prerequisites.d.ts +2 -0
  97. package/src/generators/framework-prerequisites.js +34 -0
  98. package/src/generators/function/function.d.ts +20 -1
  99. package/src/generators/function/function.js +143 -90
  100. package/src/generators/function/schema.d.ts +1 -0
  101. package/src/generators/function/schema.json +8 -2
  102. package/src/generators/function-access/function-access.d.ts +8 -0
  103. package/src/generators/function-access/function-access.js +73 -0
  104. package/src/generators/function-access/schema.d.ts +6 -0
  105. package/src/generators/function-access/schema.json +25 -0
  106. package/src/generators/observability-policy.js +1 -2
  107. package/src/{supply-chain → generators}/pnpm-toolchain-authority.d.ts +3 -3
  108. package/src/{supply-chain → generators}/pnpm-toolchain-authority.js +12 -12
  109. package/src/generators/post-generation-install.d.ts +2 -9
  110. package/src/generators/post-generation-install.js +12 -140
  111. package/src/generators/preset/dependency-overrides.d.ts +14 -20
  112. package/src/generators/preset/dependency-overrides.js +13 -57
  113. package/src/generators/preset/generator.js +0 -3
  114. package/src/generators/preset/workspace-files-foundation-infra.d.ts +6 -0
  115. package/src/generators/preset/workspace-files-foundation-infra.js +586 -0
  116. package/src/generators/preset/workspace-files-foundation-readme.d.ts +5 -0
  117. package/src/generators/preset/workspace-files-foundation-readme.js +90 -0
  118. package/src/generators/preset/workspace-files-foundation.d.ts +3 -0
  119. package/src/generators/preset/workspace-files-foundation.js +170 -0
  120. package/src/generators/preset/workspace-files-ownership.d.ts +9 -0
  121. package/src/generators/preset/workspace-files-ownership.js +124 -0
  122. package/src/generators/preset/workspace-files-root-config.d.ts +32 -0
  123. package/src/generators/preset/workspace-files-root-config.js +356 -0
  124. package/src/generators/preset/workspace-files-root-docs.d.ts +5 -0
  125. package/src/generators/preset/workspace-files-root-docs.js +109 -0
  126. package/src/generators/preset/workspace-files-shared.d.ts +18 -0
  127. package/src/generators/preset/workspace-files-shared.js +7 -0
  128. package/src/generators/preset/workspace-files-workflows.d.ts +39 -0
  129. package/src/generators/preset/workspace-files-workflows.js +306 -0
  130. package/src/generators/preset/workspace-files-workspace-health.d.ts +6 -0
  131. package/src/generators/preset/workspace-files-workspace-health.js +148 -0
  132. package/src/generators/preset/workspace-files.d.ts +10 -24
  133. package/src/generators/preset/workspace-files.js +48 -10511
  134. package/src/generators/site/built-in-site-documentation-files.d.ts +3 -0
  135. package/src/generators/site/built-in-site-documentation-files.js +51 -0
  136. package/src/generators/site/built-in-site-files.d.ts +11 -0
  137. package/src/generators/site/built-in-site-files.js +41 -0
  138. package/src/generators/site/built-in-site-infrastructure-files.d.ts +3 -0
  139. package/src/generators/site/built-in-site-infrastructure-files.js +115 -0
  140. package/src/generators/site/built-in-site-plan.d.ts +23 -0
  141. package/src/generators/site/built-in-site-plan.js +67 -0
  142. package/src/generators/site/built-in-site-project-files.d.ts +11 -0
  143. package/src/generators/site/built-in-site-project-files.js +212 -0
  144. package/src/generators/site/built-in-site-script-files.d.ts +4 -0
  145. package/src/generators/site/built-in-site-script-files.js +102 -0
  146. package/src/generators/site/built-in-site-shared.d.ts +69 -0
  147. package/src/generators/site/built-in-site-shared.js +314 -0
  148. package/src/generators/site/built-in-site-sst-config-files.d.ts +3 -0
  149. package/src/generators/site/built-in-site-sst-config-files.js +107 -0
  150. package/src/generators/site/built-in-site-web-files.d.ts +3 -0
  151. package/src/generators/site/built-in-site-web-files.js +78 -0
  152. package/src/generators/site/schema.d.ts +9 -0
  153. package/src/generators/site/schema.json +26 -0
  154. package/src/generators/site/site.d.ts +5 -0
  155. package/src/generators/site/site.js +153 -0
  156. package/src/generators/slice/built-in-plan-api-files.d.ts +1 -2
  157. package/src/generators/slice/built-in-plan-api-files.js +30 -890
  158. package/src/generators/slice/built-in-plan-database-lifecycle-files.js +57 -1851
  159. package/src/generators/slice/built-in-plan-infrastructure-files.d.ts +5 -2
  160. package/src/generators/slice/built-in-plan-infrastructure-files.js +80 -3358
  161. package/src/generators/slice/built-in-plan-key-value-files.d.ts +3 -2
  162. package/src/generators/slice/built-in-plan-key-value-files.js +3 -21
  163. package/src/generators/slice/built-in-plan-project-files.d.ts +5 -3
  164. package/src/generators/slice/built-in-plan-project-files.js +79 -897
  165. package/src/generators/slice/built-in-plan-shared.d.ts +4 -19
  166. package/src/generators/slice/built-in-plan-shared.js +5 -58
  167. package/src/generators/slice/built-in-plan-sst-config.d.ts +49 -0
  168. package/src/generators/slice/built-in-plan-sst-config.js +160 -0
  169. package/src/generators/slice/built-in-plan-web-files.d.ts +1 -1
  170. package/src/generators/slice/built-in-plan-web-files.js +14 -475
  171. package/src/generators/slice/built-in-plan.d.ts +2 -3
  172. package/src/generators/slice/built-in-plan.js +79 -277
  173. package/src/{developer-agent/preview-changes.d.ts → generators/slice/generation-tree.d.ts} +1 -5
  174. package/src/generators/slice/generation-tree.js +161 -0
  175. package/src/generators/slice/persistence-contract.js +2 -2
  176. package/src/generators/slice/schema.json +12 -4
  177. package/src/generators/slice/slice-config.d.ts +7 -0
  178. package/src/generators/slice/slice-config.js +125 -0
  179. package/src/generators/slice/slice.js +52 -257
  180. package/src/generators/slice/sql-bootstrap.d.ts +1 -0
  181. package/src/generators/slice/sql-bootstrap.js +505 -0
  182. package/src/generators/slice/sql-client.d.ts +1 -0
  183. package/src/generators/slice/sql-client.js +107 -0
  184. package/src/generators/slice/sql-infrastructure.d.ts +1 -0
  185. package/src/generators/slice/sql-infrastructure.js +225 -0
  186. package/src/generators/slice/sql-logging.d.ts +1 -0
  187. package/src/generators/slice/sql-logging.js +266 -0
  188. package/src/generators/slice/sql-migration.d.ts +2 -0
  189. package/src/generators/slice/sql-migration.js +202 -0
  190. package/src/generators/slice/standard-slice-contract.d.ts +25 -0
  191. package/src/generators/slice/standard-slice-contract.js +64 -0
  192. package/src/generators/sql/schema.json +1 -1
  193. package/src/generators/sql/sql.d.ts +1 -1
  194. package/src/generators/sql/sql.js +13 -7
  195. package/src/generators/upgrade/framework-package-upgrade.d.ts +35 -0
  196. package/src/generators/upgrade/framework-package-upgrade.js +55 -0
  197. package/src/generators/upgrade/framework-packages.d.ts +25 -0
  198. package/src/generators/upgrade/framework-packages.js +138 -0
  199. package/src/generators/upgrade/function-authentication-notice.d.ts +21 -0
  200. package/src/generators/upgrade/function-authentication-notice.js +54 -0
  201. package/src/generators/upgrade/schema.d.ts +0 -3
  202. package/src/generators/upgrade/schema.json +7 -17
  203. package/src/generators/upgrade/slice-compositions.d.ts +20 -0
  204. package/src/generators/upgrade/slice-compositions.js +100 -0
  205. package/src/generators/upgrade/slice-upgrade-guidance.d.ts +19 -0
  206. package/src/generators/upgrade/slice-upgrade-guidance.js +50 -0
  207. package/src/generators/upgrade/slice-upgrade.d.ts +4 -0
  208. package/src/generators/upgrade/slice-upgrade.js +231 -0
  209. package/src/generators/upgrade/upgrade-plan.d.ts +49 -0
  210. package/src/generators/upgrade/upgrade-plan.js +242 -0
  211. package/src/generators/upgrade/upgrade-preflight.d.ts +20 -0
  212. package/src/generators/upgrade/upgrade-preflight.js +64 -0
  213. package/src/generators/upgrade/upgrade.d.ts +8 -87
  214. package/src/generators/upgrade/upgrade.js +27 -1909
  215. package/src/generators/workload/schema.json +2 -2
  216. package/src/generators/workload/workload.d.ts +11 -11
  217. package/src/generators/workload/workload.js +167 -1200
  218. package/src/index.d.ts +0 -5
  219. package/src/index.js +0 -5
  220. package/src/local-dev/browser-verification.d.ts +0 -7
  221. package/src/local-dev/browser-verification.js +0 -136
  222. package/src/local-dev/contracts.d.ts +6 -0
  223. package/src/local-dev/contracts.js +17 -9
  224. package/src/local-dev/environment-checks.d.ts +126 -0
  225. package/src/local-dev/environment-checks.js +81 -0
  226. package/src/local-dev/environment-inspector.d.ts +3 -124
  227. package/src/local-dev/environment-inspector.js +9 -148
  228. package/src/local-dev/fleet-process.d.ts +9 -2
  229. package/src/local-dev/fleet-process.js +27 -7
  230. package/src/local-dev/gateway-daemon.d.ts +1 -1
  231. package/src/local-dev/gateway-daemon.js +6 -4
  232. package/src/local-dev/portless.d.ts +5 -0
  233. package/src/local-dev/portless.js +5 -0
  234. package/src/local-dev/private-state.d.ts +1 -0
  235. package/src/local-dev/private-state.js +19 -23
  236. package/src/local-dev/process-group.d.ts +10 -0
  237. package/src/local-dev/process-group.js +33 -0
  238. package/src/local-dev/process-identity.js +4 -2
  239. package/src/local-dev/slice-runner-child.d.ts +37 -0
  240. package/src/local-dev/slice-runner-child.js +127 -0
  241. package/src/local-dev/slice-runner-recovery.d.ts +32 -0
  242. package/src/local-dev/slice-runner-recovery.js +216 -0
  243. package/src/local-dev/slice-runner-state.d.ts +82 -0
  244. package/src/local-dev/slice-runner-state.js +265 -0
  245. package/src/local-dev/slice-runner.d.ts +4 -117
  246. package/src/local-dev/slice-runner.js +59 -594
  247. package/src/local-dev/tls.js +39 -99
  248. package/src/local-dev/trust-store.d.ts +42 -0
  249. package/src/local-dev/trust-store.js +87 -0
  250. package/src/ownership/composition.d.ts +7 -0
  251. package/src/ownership/composition.js +64 -56
  252. package/src/ownership/index.d.ts +2 -0
  253. package/src/ownership/index.js +7 -0
  254. package/src/ownership/pnpm-workspace.d.ts +77 -0
  255. package/src/ownership/pnpm-workspace.js +225 -0
  256. package/src/ownership/record.d.ts +19 -0
  257. package/src/ownership/record.js +26 -2
  258. package/src/ownership/site-record.d.ts +26 -0
  259. package/src/ownership/site-record.js +120 -0
  260. package/src/repository-policy/capacity-migration.d.ts +1 -1
  261. package/src/repository-policy/capacity-migration.js +1 -1
  262. package/src/repository-policy/deployment-plan.d.ts +3 -0
  263. package/src/repository-policy/deployment-plan.js +33 -4
  264. package/src/repository-policy/foundation-router.d.ts +17 -0
  265. package/src/repository-policy/foundation-router.js +44 -0
  266. package/src/repository-policy/index.d.ts +3 -0
  267. package/src/repository-policy/index.js +3 -0
  268. package/src/repository-policy/policy-accounts.d.ts +22 -0
  269. package/src/repository-policy/policy-accounts.js +134 -0
  270. package/src/repository-policy/policy-files.d.ts +8 -0
  271. package/src/repository-policy/policy-files.js +201 -0
  272. package/src/repository-policy/policy-internal.d.ts +2 -0
  273. package/src/repository-policy/policy-internal.js +11 -0
  274. package/src/repository-policy/policy-model.d.ts +95 -0
  275. package/src/repository-policy/policy-model.js +42 -0
  276. package/src/repository-policy/policy-validation.d.ts +4 -0
  277. package/src/repository-policy/policy-validation.js +308 -0
  278. package/src/repository-policy/policy.d.ts +6 -109
  279. package/src/repository-policy/policy.js +52 -626
  280. package/src/repository-policy/public-dns.d.ts +69 -0
  281. package/src/repository-policy/public-dns.js +265 -0
  282. package/src/{generators/repository-policy → repository-policy}/tree-policy.d.ts +1 -1
  283. package/src/{generators/repository-policy → repository-policy}/tree-policy.js +5 -5
  284. package/src/schemas/generated-ownership-v2.json +6 -0
  285. package/src/schemas/repository-policy-v1.json +106 -3
  286. package/src/secrets/index.d.ts +0 -5
  287. package/src/secrets/index.js +0 -5
  288. package/src/slice-infra/index.d.ts +57 -0
  289. package/src/slice-infra/index.js +117 -0
  290. package/src/slice-scripts/build.d.ts +27 -0
  291. package/src/slice-scripts/build.js +120 -0
  292. package/src/slice-scripts/database.d.ts +87 -0
  293. package/src/slice-scripts/database.js +328 -0
  294. package/src/slice-scripts/index.d.ts +11 -0
  295. package/src/slice-scripts/index.js +23 -0
  296. package/src/slice-scripts/root-site-routes.d.ts +11 -0
  297. package/src/slice-scripts/root-site-routes.js +83 -0
  298. package/src/slice-scripts/sql-migration-engine.mjs +180 -0
  299. package/src/workload-roles/effective-policy.d.ts +0 -37
  300. package/src/workload-roles/effective-policy.js +1 -174
  301. package/src/workload-roles/standard-slice.d.ts +2 -19
  302. package/src/workload-roles/standard-slice.js +3 -129
  303. package/src/workspace-deployment/ownership.d.ts +15 -0
  304. package/src/workspace-deployment/ownership.js +19 -3
  305. package/src/api-contract/baseline-update.d.ts +0 -82
  306. package/src/api-contract/baseline-update.js +0 -225
  307. package/src/api-contract/compatibility.d.ts +0 -30
  308. package/src/api-contract/compatibility.js +0 -643
  309. package/src/api-contract/contract-graph.d.ts +0 -35
  310. package/src/api-contract/contract-graph.js +0 -141
  311. package/src/api-contract/evidence.d.ts +0 -23
  312. package/src/api-contract/evidence.js +0 -87
  313. package/src/api-contract/index.d.ts +0 -6
  314. package/src/api-contract/index.js +0 -10
  315. package/src/api-contract/model.d.ts +0 -144
  316. package/src/api-contract/model.js +0 -993
  317. package/src/api-contract/rollout.d.ts +0 -32
  318. package/src/api-contract/rollout.js +0 -88
  319. package/src/authorization/compatibility.d.ts +0 -62
  320. package/src/authorization/compatibility.js +0 -175
  321. package/src/authorization/index.d.ts +0 -1
  322. package/src/authorization/index.js +0 -5
  323. package/src/blueprints/execution.d.ts +0 -55
  324. package/src/blueprints/execution.js +0 -329
  325. package/src/blueprints/external-sandbox.d.ts +0 -53
  326. package/src/blueprints/external-sandbox.js +0 -1194
  327. package/src/blueprints/index.d.ts +0 -5
  328. package/src/blueprints/index.js +0 -9
  329. package/src/blueprints/inputs.d.ts +0 -43
  330. package/src/blueprints/inputs.js +0 -103
  331. package/src/blueprints/manifest.d.ts +0 -281
  332. package/src/blueprints/manifest.js +0 -424
  333. package/src/blueprints/resolver.d.ts +0 -37
  334. package/src/blueprints/resolver.js +0 -387
  335. package/src/blueprints/transitions.d.ts +0 -20
  336. package/src/blueprints/transitions.js +0 -61
  337. package/src/cli/agent-command.d.ts +0 -30
  338. package/src/cli/agent-command.js +0 -204
  339. package/src/cli/agent-runtime.d.ts +0 -25
  340. package/src/cli/agent-runtime.js +0 -498
  341. package/src/cli/blueprint-authority.d.ts +0 -9
  342. package/src/cli/blueprint-authority.js +0 -43
  343. package/src/cli/blueprint-command.d.ts +0 -24
  344. package/src/cli/blueprint-command.js +0 -63
  345. package/src/data-lifecycle/index.d.ts +0 -3
  346. package/src/data-lifecycle/index.js +0 -7
  347. package/src/data-lifecycle/model.d.ts +0 -172
  348. package/src/data-lifecycle/model.js +0 -95
  349. package/src/data-lifecycle/sensitive-artifacts.d.ts +0 -28
  350. package/src/data-lifecycle/sensitive-artifacts.js +0 -146
  351. package/src/data-lifecycle/validation.d.ts +0 -32
  352. package/src/data-lifecycle/validation.js +0 -837
  353. package/src/database-retirement/contract.d.ts +0 -68
  354. package/src/database-retirement/contract.js +0 -166
  355. package/src/database-retirement/index.d.ts +0 -1
  356. package/src/database-retirement/index.js +0 -5
  357. package/src/developer-agent/context.d.ts +0 -57
  358. package/src/developer-agent/context.js +0 -662
  359. package/src/developer-agent/generator-planning.d.ts +0 -34
  360. package/src/developer-agent/generator-planning.js +0 -666
  361. package/src/developer-agent/generator-preview.d.ts +0 -8
  362. package/src/developer-agent/generator-preview.js +0 -650
  363. package/src/developer-agent/git-inspection.d.ts +0 -112
  364. package/src/developer-agent/git-inspection.js +0 -887
  365. package/src/developer-agent/handoff.d.ts +0 -43
  366. package/src/developer-agent/handoff.js +0 -713
  367. package/src/developer-agent/index.d.ts +0 -10
  368. package/src/developer-agent/index.js +0 -14
  369. package/src/developer-agent/model.d.ts +0 -493
  370. package/src/developer-agent/model.js +0 -143
  371. package/src/developer-agent/operation-registry.d.ts +0 -60
  372. package/src/developer-agent/operation-registry.js +0 -1550
  373. package/src/developer-agent/ordering.d.ts +0 -9
  374. package/src/developer-agent/ordering.js +0 -15
  375. package/src/developer-agent/planning.d.ts +0 -25
  376. package/src/developer-agent/planning.js +0 -478
  377. package/src/developer-agent/preview-changes.js +0 -215
  378. package/src/developer-agent/preview-source.d.ts +0 -2
  379. package/src/developer-agent/preview-source.js +0 -19
  380. package/src/developer-agent/validation.d.ts +0 -30
  381. package/src/developer-agent/validation.js +0 -2725
  382. package/src/developer-agent/workspace-inspection.d.ts +0 -20
  383. package/src/developer-agent/workspace-inspection.js +0 -1189
  384. package/src/developer-agent/workspace-path.d.ts +0 -6
  385. package/src/developer-agent/workspace-path.js +0 -22
  386. package/src/executors/blueprint-trust/blueprint-trust.d.ts +0 -29
  387. package/src/executors/blueprint-trust/blueprint-trust.js +0 -121
  388. package/src/executors/blueprint-trust/schema.json +0 -27
  389. package/src/executors/blueprint-verification/blueprint-verification.d.ts +0 -13
  390. package/src/executors/blueprint-verification/blueprint-verification.js +0 -110
  391. package/src/executors/blueprint-verification/schema.json +0 -44
  392. package/src/executors/developer-context/developer-context.d.ts +0 -38
  393. package/src/executors/developer-context/developer-context.js +0 -78
  394. package/src/executors/developer-context/schema.json +0 -87
  395. package/src/executors/foundation-profile-preflight/foundation-profile-preflight.d.ts +0 -19
  396. package/src/executors/foundation-profile-preflight/foundation-profile-preflight.js +0 -105
  397. package/src/executors/foundation-profile-preflight/schema.json +0 -32
  398. package/src/executors/github-bootstrap/github-bootstrap.d.ts +0 -13
  399. package/src/executors/github-bootstrap/github-bootstrap.js +0 -62
  400. package/src/executors/github-bootstrap/schema.json +0 -50
  401. package/src/executors/infrastructure-plan/infrastructure-plan.d.ts +0 -37
  402. package/src/executors/infrastructure-plan/infrastructure-plan.js +0 -268
  403. package/src/executors/infrastructure-plan/schema.json +0 -38
  404. package/src/executors/router-waf-rehearsal/router-waf-rehearsal.d.ts +0 -42
  405. package/src/executors/router-waf-rehearsal/router-waf-rehearsal.js +0 -1229
  406. package/src/executors/router-waf-rehearsal/schema.json +0 -29
  407. package/src/executors/secret-guardrails/schema.json +0 -6
  408. package/src/executors/secret-guardrails/secret-guardrails.d.ts +0 -3
  409. package/src/executors/secret-guardrails/secret-guardrails.js +0 -44
  410. package/src/executors/secret-initialize/schema.json +0 -42
  411. package/src/executors/secret-initialize/secret-initialize.d.ts +0 -34
  412. package/src/executors/secret-initialize/secret-initialize.js +0 -297
  413. package/src/executors/secret-metadata/schema.json +0 -36
  414. package/src/executors/secret-metadata/secret-metadata.d.ts +0 -46
  415. package/src/executors/secret-metadata/secret-metadata.js +0 -230
  416. package/src/executors/sst-lifecycle/generated-secret-retirement.d.ts +0 -53
  417. package/src/executors/sst-lifecycle/generated-secret-retirement.js +0 -192
  418. package/src/executors/sst-lifecycle/logging-preflight.d.ts +0 -22
  419. package/src/executors/sst-lifecycle/logging-preflight.js +0 -206
  420. package/src/executors/sst-lifecycle/secret-preflight.d.ts +0 -27
  421. package/src/executors/sst-lifecycle/secret-preflight.js +0 -125
  422. package/src/executors/work-markers/schema.json +0 -14
  423. package/src/executors/work-markers/work-markers.d.ts +0 -6
  424. package/src/executors/work-markers/work-markers.js +0 -20
  425. package/src/foundation/cost-estimate.d.ts +0 -175
  426. package/src/foundation/cost-estimate.js +0 -706
  427. package/src/foundation/private-smoke-admission.d.ts +0 -45
  428. package/src/foundation/private-smoke-admission.js +0 -180
  429. package/src/foundation/private-smoke-control-plane.d.ts +0 -18
  430. package/src/foundation/private-smoke-control-plane.js +0 -184
  431. package/src/foundation/router-waf-rate-rehearsal.d.ts +0 -97
  432. package/src/foundation/router-waf-rate-rehearsal.js +0 -210
  433. package/src/foundation/router-waf.d.ts +0 -149
  434. package/src/foundation/router-waf.js +0 -809
  435. package/src/frontend-security/index.d.ts +0 -1
  436. package/src/frontend-security/index.js +0 -5
  437. package/src/frontend-security/security-headers.d.ts +0 -50
  438. package/src/frontend-security/security-headers.js +0 -418
  439. package/src/generators/blueprint/blueprint.d.ts +0 -5
  440. package/src/generators/blueprint/blueprint.js +0 -102
  441. package/src/generators/blueprint/files.d.ts +0 -6
  442. package/src/generators/blueprint/files.js +0 -217
  443. package/src/generators/blueprint/schema.d.ts +0 -4
  444. package/src/generators/blueprint/schema.json +0 -18
  445. package/src/generators/feature-registry.d.ts +0 -13
  446. package/src/generators/feature-registry.js +0 -73
  447. package/src/generators/observability-infrastructure.d.ts +0 -2
  448. package/src/generators/observability-infrastructure.js +0 -31
  449. package/src/generators/preset/workspace-files-adopter-skills.d.ts +0 -7
  450. package/src/generators/preset/workspace-files-adopter-skills.js +0 -345
  451. package/src/generators/preset/workspace-files-agent-development.d.ts +0 -9
  452. package/src/generators/preset/workspace-files-agent-development.js +0 -42
  453. package/src/generators/preset/workspace-files-ci-acceptance.d.ts +0 -1
  454. package/src/generators/preset/workspace-files-ci-acceptance.js +0 -791
  455. package/src/generators/preset/workspace-files-ci-install.d.ts +0 -2
  456. package/src/generators/preset/workspace-files-ci-install.js +0 -196
  457. package/src/generators/preset/workspace-files-developer-agent.d.ts +0 -16
  458. package/src/generators/preset/workspace-files-developer-agent.js +0 -638
  459. package/src/generators/preset/workspace-files-ecr-inspector.d.ts +0 -18
  460. package/src/generators/preset/workspace-files-ecr-inspector.js +0 -298
  461. package/src/generators/preset/workspace-files-foundation-workload-roles.d.ts +0 -6
  462. package/src/generators/preset/workspace-files-foundation-workload-roles.js +0 -409
  463. package/src/generators/preset/workspace-files-performance-cost.d.ts +0 -66
  464. package/src/generators/preset/workspace-files-performance-cost.js +0 -866
  465. package/src/generators/preset/workspace-files-performance-load.d.ts +0 -73
  466. package/src/generators/preset/workspace-files-performance-load.js +0 -815
  467. package/src/generators/preset/workspace-files-shared-operation-claims.d.ts +0 -10
  468. package/src/generators/preset/workspace-files-shared-operation-claims.js +0 -59
  469. package/src/generators/preset/workspace-files-stage-authority.d.ts +0 -6
  470. package/src/generators/preset/workspace-files-stage-authority.js +0 -529
  471. package/src/generators/preset/workspace-files-thin-deploy.d.ts +0 -65
  472. package/src/generators/preset/workspace-files-thin-deploy.js +0 -2520
  473. package/src/generators/preset/workspace-files-thin-docs.d.ts +0 -7
  474. package/src/generators/preset/workspace-files-thin-docs.js +0 -358
  475. package/src/generators/preset/workspace-files-thin-release.d.ts +0 -14
  476. package/src/generators/preset/workspace-files-thin-release.js +0 -26
  477. package/src/generators/preset/workspace-files-workload-role-baseline.d.ts +0 -9
  478. package/src/generators/preset/workspace-files-workload-role-baseline.js +0 -1314
  479. package/src/generators/repository-policy/repository-policy.d.ts +0 -4
  480. package/src/generators/repository-policy/repository-policy.js +0 -293
  481. package/src/generators/repository-policy/schema.d.ts +0 -28
  482. package/src/generators/repository-policy/schema.json +0 -122
  483. package/src/generators/slice/built-in-plan-alarm-identity.d.ts +0 -173
  484. package/src/generators/slice/built-in-plan-alarm-identity.js +0 -202
  485. package/src/generators/slice/built-in-plan-api-contract-files.d.ts +0 -2
  486. package/src/generators/slice/built-in-plan-api-contract-files.js +0 -2830
  487. package/src/generators/slice/built-in-plan-async-work-files.d.ts +0 -2
  488. package/src/generators/slice/built-in-plan-async-work-files.js +0 -6100
  489. package/src/generators/slice/built-in-plan-authorization-files.d.ts +0 -2
  490. package/src/generators/slice/built-in-plan-authorization-files.js +0 -2082
  491. package/src/generators/slice/built-in-plan-authorization-infrastructure-files.d.ts +0 -2
  492. package/src/generators/slice/built-in-plan-authorization-infrastructure-files.js +0 -1301
  493. package/src/generators/slice/built-in-plan-authorization-storage.d.ts +0 -3
  494. package/src/generators/slice/built-in-plan-authorization-storage.js +0 -119
  495. package/src/generators/slice/built-in-plan-background-work-files.d.ts +0 -2
  496. package/src/generators/slice/built-in-plan-background-work-files.js +0 -99
  497. package/src/generators/slice/built-in-plan-data-deletion-files.d.ts +0 -2
  498. package/src/generators/slice/built-in-plan-data-deletion-files.js +0 -273
  499. package/src/generators/slice/built-in-plan-data-export-infrastructure-files.d.ts +0 -2
  500. package/src/generators/slice/built-in-plan-data-export-infrastructure-files.js +0 -223
  501. package/src/generators/slice/built-in-plan-data-files.d.ts +0 -2
  502. package/src/generators/slice/built-in-plan-data-files.js +0 -513
  503. package/src/generators/slice/built-in-plan-data-lifecycle-files.d.ts +0 -2
  504. package/src/generators/slice/built-in-plan-data-lifecycle-files.js +0 -775
  505. package/src/generators/slice/built-in-plan-data-lifecycle-runtime-files.d.ts +0 -2
  506. package/src/generators/slice/built-in-plan-data-lifecycle-runtime-files.js +0 -863
  507. package/src/generators/slice/built-in-plan-data-retention-job-files.d.ts +0 -2
  508. package/src/generators/slice/built-in-plan-data-retention-job-files.js +0 -169
  509. package/src/generators/slice/built-in-plan-data-retention-launcher-files.d.ts +0 -2
  510. package/src/generators/slice/built-in-plan-data-retention-launcher-files.js +0 -186
  511. package/src/generators/slice/built-in-plan-data-rights-files.d.ts +0 -2
  512. package/src/generators/slice/built-in-plan-data-rights-files.js +0 -152
  513. package/src/generators/slice/built-in-plan-database-retirement-rehearsal-files.d.ts +0 -2
  514. package/src/generators/slice/built-in-plan-database-retirement-rehearsal-files.js +0 -508
  515. package/src/generators/slice/built-in-plan-event-contract-literal.d.ts +0 -6
  516. package/src/generators/slice/built-in-plan-event-contract-literal.js +0 -52
  517. package/src/generators/slice/built-in-plan-foundation-files.d.ts +0 -3
  518. package/src/generators/slice/built-in-plan-foundation-files.js +0 -205
  519. package/src/generators/slice/built-in-plan-frontend-files.d.ts +0 -2
  520. package/src/generators/slice/built-in-plan-frontend-files.js +0 -2244
  521. package/src/generators/slice/built-in-plan-infrastructure-safety-files.d.ts +0 -2
  522. package/src/generators/slice/built-in-plan-infrastructure-safety-files.js +0 -373
  523. package/src/generators/slice/built-in-plan-key-value-cleanup.d.ts +0 -4
  524. package/src/generators/slice/built-in-plan-key-value-cleanup.js +0 -100
  525. package/src/generators/slice/built-in-plan-key-value-consumer.d.ts +0 -4
  526. package/src/generators/slice/built-in-plan-key-value-consumer.js +0 -151
  527. package/src/generators/slice/built-in-plan-key-value-deletion.d.ts +0 -2
  528. package/src/generators/slice/built-in-plan-key-value-deletion.js +0 -377
  529. package/src/generators/slice/built-in-plan-key-value-delivery.d.ts +0 -2
  530. package/src/generators/slice/built-in-plan-key-value-delivery.js +0 -137
  531. package/src/generators/slice/built-in-plan-key-value-export.d.ts +0 -2
  532. package/src/generators/slice/built-in-plan-key-value-export.js +0 -595
  533. package/src/generators/slice/built-in-plan-key-value-holds.d.ts +0 -2
  534. package/src/generators/slice/built-in-plan-key-value-holds.js +0 -189
  535. package/src/generators/slice/built-in-plan-key-value-infrastructure.d.ts +0 -2
  536. package/src/generators/slice/built-in-plan-key-value-infrastructure.js +0 -102
  537. package/src/generators/slice/built-in-plan-key-value-performance.d.ts +0 -5
  538. package/src/generators/slice/built-in-plan-key-value-performance.js +0 -530
  539. package/src/generators/slice/built-in-plan-key-value-provider.d.ts +0 -4
  540. package/src/generators/slice/built-in-plan-key-value-provider.js +0 -366
  541. package/src/generators/slice/built-in-plan-key-value-records.d.ts +0 -3
  542. package/src/generators/slice/built-in-plan-key-value-records.js +0 -232
  543. package/src/generators/slice/built-in-plan-key-value-retention-infrastructure.d.ts +0 -2
  544. package/src/generators/slice/built-in-plan-key-value-retention-infrastructure.js +0 -103
  545. package/src/generators/slice/built-in-plan-key-value-retention-job-files.d.ts +0 -2
  546. package/src/generators/slice/built-in-plan-key-value-retention-job-files.js +0 -160
  547. package/src/generators/slice/built-in-plan-key-value-retention-maintenance.d.ts +0 -2
  548. package/src/generators/slice/built-in-plan-key-value-retention-maintenance.js +0 -329
  549. package/src/generators/slice/built-in-plan-key-value-retention-worker.d.ts +0 -2
  550. package/src/generators/slice/built-in-plan-key-value-retention-worker.js +0 -477
  551. package/src/generators/slice/built-in-plan-key-value-retention.d.ts +0 -2
  552. package/src/generators/slice/built-in-plan-key-value-retention.js +0 -184
  553. package/src/generators/slice/built-in-plan-metadata-files.d.ts +0 -3
  554. package/src/generators/slice/built-in-plan-metadata-files.js +0 -384
  555. package/src/generators/slice/built-in-plan-native-runtime-authority-files.d.ts +0 -2
  556. package/src/generators/slice/built-in-plan-native-runtime-authority-files.js +0 -324
  557. package/src/generators/slice/built-in-plan-operations-files.d.ts +0 -2
  558. package/src/generators/slice/built-in-plan-operations-files.js +0 -1218
  559. package/src/generators/slice/built-in-plan-performance-files.d.ts +0 -4
  560. package/src/generators/slice/built-in-plan-performance-files.js +0 -2439
  561. package/src/generators/slice/built-in-plan-release-files.d.ts +0 -2
  562. package/src/generators/slice/built-in-plan-release-files.js +0 -6585
  563. package/src/generators/slice/built-in-plan-reliability-files.d.ts +0 -2
  564. package/src/generators/slice/built-in-plan-reliability-files.js +0 -4724
  565. package/src/generators/slice/built-in-plan-secret-runtime-files.d.ts +0 -2
  566. package/src/generators/slice/built-in-plan-secret-runtime-files.js +0 -1015
  567. package/src/generators/slice/built-in-plan-sql-events.d.ts +0 -2
  568. package/src/generators/slice/built-in-plan-sql-events.js +0 -276
  569. package/src/generators/slice/built-in-plan-testing-files.d.ts +0 -2
  570. package/src/generators/slice/built-in-plan-testing-files.js +0 -2575
  571. package/src/generators/slice/built-in-plan-testing-persistence-event-files.d.ts +0 -7
  572. package/src/generators/slice/built-in-plan-testing-persistence-event-files.js +0 -487
  573. package/src/generators/slice/built-in-plan-testing-persistence-files.d.ts +0 -2
  574. package/src/generators/slice/built-in-plan-testing-persistence-files.js +0 -180
  575. package/src/generators/slice/built-in-plan-thin-release-files.d.ts +0 -11
  576. package/src/generators/slice/built-in-plan-thin-release-files.js +0 -162
  577. package/src/generators/slice/built-in-plan-verification-files.d.ts +0 -2
  578. package/src/generators/slice/built-in-plan-verification-files.js +0 -431
  579. package/src/generators/slice/built-in-plan-workload-role-files.d.ts +0 -2
  580. package/src/generators/slice/built-in-plan-workload-role-files.js +0 -2220
  581. package/src/generators/slice/data-policy-review-seed.d.ts +0 -2
  582. package/src/generators/slice/data-policy-review-seed.js +0 -22
  583. package/src/generators/slice/deployed-smoke-readiness.d.ts +0 -2
  584. package/src/generators/slice/deployed-smoke-readiness.js +0 -214
  585. package/src/generators/slice/local-source-identity.d.ts +0 -2
  586. package/src/generators/slice/local-source-identity.js +0 -31
  587. package/src/generators/upgrade/sql-seeded-reconciliation.d.ts +0 -2
  588. package/src/generators/upgrade/sql-seeded-reconciliation.js +0 -170
  589. package/src/generators/workload/performance-registration.d.ts +0 -33
  590. package/src/generators/workload/performance-registration.js +0 -224
  591. package/src/generators/workload/reliability-registration.d.ts +0 -16
  592. package/src/generators/workload/reliability-registration.js +0 -150
  593. package/src/generators/workload/service-performance-files.d.ts +0 -5
  594. package/src/generators/workload/service-performance-files.js +0 -1883
  595. package/src/git-policy/action-pins.d.ts +0 -43
  596. package/src/git-policy/action-pins.js +0 -50
  597. package/src/git-policy/github-bootstrap.d.ts +0 -94
  598. package/src/git-policy/github-bootstrap.js +0 -1248
  599. package/src/git-policy/index.d.ts +0 -3
  600. package/src/git-policy/index.js +0 -7
  601. package/src/git-policy/routing.d.ts +0 -21
  602. package/src/git-policy/routing.js +0 -138
  603. package/src/infrastructure-change/convergence.d.ts +0 -13
  604. package/src/infrastructure-change/convergence.js +0 -85
  605. package/src/infrastructure-change/drift.d.ts +0 -13
  606. package/src/infrastructure-change/drift.js +0 -112
  607. package/src/infrastructure-change/index.d.ts +0 -7
  608. package/src/infrastructure-change/index.js +0 -11
  609. package/src/infrastructure-change/local-capability.d.ts +0 -73
  610. package/src/infrastructure-change/local-capability.js +0 -114
  611. package/src/infrastructure-change/model.d.ts +0 -274
  612. package/src/infrastructure-change/model.js +0 -29
  613. package/src/infrastructure-change/normalize.d.ts +0 -16
  614. package/src/infrastructure-change/normalize.js +0 -285
  615. package/src/infrastructure-change/plan.d.ts +0 -67
  616. package/src/infrastructure-change/plan.js +0 -671
  617. package/src/infrastructure-change/risk.d.ts +0 -9
  618. package/src/infrastructure-change/risk.js +0 -349
  619. package/src/infrastructure-change/summary.d.ts +0 -20
  620. package/src/infrastructure-change/summary.js +0 -130
  621. package/src/performance/cost-collection.d.ts +0 -225
  622. package/src/performance/cost-collection.js +0 -827
  623. package/src/performance/cost-controls.d.ts +0 -135
  624. package/src/performance/cost-controls.js +0 -347
  625. package/src/performance/evidence.d.ts +0 -140
  626. package/src/performance/evidence.js +0 -601
  627. package/src/performance/index.d.ts +0 -10
  628. package/src/performance/index.js +0 -14
  629. package/src/performance/load-safety.d.ts +0 -84
  630. package/src/performance/load-safety.js +0 -348
  631. package/src/performance/model.d.ts +0 -129
  632. package/src/performance/model.js +0 -451
  633. package/src/performance/pr-artifact-budget.d.ts +0 -42
  634. package/src/performance/pr-artifact-budget.js +0 -151
  635. package/src/performance/runner.d.ts +0 -75
  636. package/src/performance/runner.js +0 -227
  637. package/src/performance/scenario-endpoint.d.ts +0 -1
  638. package/src/performance/scenario-endpoint.js +0 -5
  639. package/src/performance/scenario.d.ts +0 -215
  640. package/src/performance/scenario.js +0 -744
  641. package/src/performance/unit-cost.d.ts +0 -105
  642. package/src/performance/unit-cost.js +0 -364
  643. package/src/release/index.d.ts +0 -2
  644. package/src/release/index.js +0 -6
  645. package/src/release/lifecycle.d.ts +0 -132
  646. package/src/release/lifecycle.js +0 -411
  647. package/src/release/manifest.d.ts +0 -148
  648. package/src/release/manifest.js +0 -503
  649. package/src/release/rollout.d.ts +0 -170
  650. package/src/release/rollout.js +0 -578
  651. package/src/release/source-authority.d.ts +0 -19
  652. package/src/release/source-authority.js +0 -212
  653. package/src/schemas/aggregate-count-evidence-v1.json +0 -135
  654. package/src/schemas/api-contract-baseline-v1.json +0 -674
  655. package/src/schemas/api-contract-compatibility-report-v1.json +0 -126
  656. package/src/schemas/aws-billing-actual-evidence-v1.json +0 -407
  657. package/src/schemas/blueprint-input-schema-v1.json +0 -23
  658. package/src/schemas/blueprint-v1.json +0 -188
  659. package/src/schemas/data-lifecycle-policy-v1.json +0 -517
  660. package/src/schemas/performance-policy-v1.json +0 -335
  661. package/src/schemas/testing-evidence-quarantine-v1.json +0 -168
  662. package/src/schemas/testing-evidence-result-v1.json +0 -319
  663. package/src/secrets/aws-control-plane.d.ts +0 -29
  664. package/src/secrets/aws-control-plane.js +0 -322
  665. package/src/secrets/generated-aws-control-plane.d.ts +0 -33
  666. package/src/secrets/generated-aws-control-plane.js +0 -322
  667. package/src/secrets/guardrails.d.ts +0 -26
  668. package/src/secrets/guardrails.js +0 -328
  669. package/src/secrets/metadata.d.ts +0 -48
  670. package/src/secrets/metadata.js +0 -199
  671. package/src/secrets/operator.d.ts +0 -190
  672. package/src/secrets/operator.js +0 -701
  673. package/src/secrets/verification.d.ts +0 -18
  674. package/src/secrets/verification.js +0 -152
  675. package/src/supply-chain/action-pins.d.ts +0 -26
  676. package/src/supply-chain/action-pins.js +0 -262
  677. package/src/supply-chain/blueprint-trust-git.d.ts +0 -130
  678. package/src/supply-chain/blueprint-trust-git.js +0 -1642
  679. package/src/supply-chain/blueprint-trust-process.d.ts +0 -4
  680. package/src/supply-chain/blueprint-trust-process.js +0 -88
  681. package/src/supply-chain/blueprint-trust.d.ts +0 -354
  682. package/src/supply-chain/blueprint-trust.js +0 -1558
  683. package/src/supply-chain/blueprint-verification-authority.d.ts +0 -62
  684. package/src/supply-chain/blueprint-verification-authority.js +0 -661
  685. package/src/supply-chain/blueprint-verification-execution.d.ts +0 -68
  686. package/src/supply-chain/blueprint-verification-execution.js +0 -639
  687. package/src/supply-chain/build-output-bounds.d.ts +0 -2
  688. package/src/supply-chain/build-output-bounds.js +0 -12
  689. package/src/supply-chain/build-output.d.ts +0 -41
  690. package/src/supply-chain/build-output.js +0 -551
  691. package/src/supply-chain/common.d.ts +0 -21
  692. package/src/supply-chain/common.js +0 -107
  693. package/src/supply-chain/container-artifact-contract.d.ts +0 -23
  694. package/src/supply-chain/container-artifact-contract.js +0 -208
  695. package/src/supply-chain/container-release.d.ts +0 -119
  696. package/src/supply-chain/container-release.js +0 -496
  697. package/src/supply-chain/ecr-applicability.d.ts +0 -19
  698. package/src/supply-chain/ecr-applicability.js +0 -103
  699. package/src/supply-chain/ecr-scanning.d.ts +0 -85
  700. package/src/supply-chain/ecr-scanning.js +0 -325
  701. package/src/supply-chain/ecs-deployed-image.d.ts +0 -87
  702. package/src/supply-chain/ecs-deployed-image.js +0 -302
  703. package/src/supply-chain/errors.d.ts +0 -6
  704. package/src/supply-chain/errors.js +0 -15
  705. package/src/supply-chain/generated-blueprint-trust-command.d.ts +0 -4
  706. package/src/supply-chain/generated-blueprint-trust-command.js +0 -1379
  707. package/src/supply-chain/generated-command.d.ts +0 -1
  708. package/src/supply-chain/generated-command.js +0 -775
  709. package/src/supply-chain/generated-container-release-command.d.ts +0 -16
  710. package/src/supply-chain/generated-container-release-command.js +0 -3248
  711. package/src/supply-chain/generated-ecr-collector-command.d.ts +0 -20
  712. package/src/supply-chain/generated-ecr-collector-command.js +0 -1445
  713. package/src/supply-chain/generated-files.d.ts +0 -13
  714. package/src/supply-chain/generated-files.js +0 -421
  715. package/src/supply-chain/generated-scanner-command.d.ts +0 -1
  716. package/src/supply-chain/generated-scanner-command.js +0 -778
  717. package/src/supply-chain/index.d.ts +0 -28
  718. package/src/supply-chain/index.js +0 -36
  719. package/src/supply-chain/inventory.d.ts +0 -96
  720. package/src/supply-chain/inventory.js +0 -828
  721. package/src/supply-chain/license-expression.d.ts +0 -7
  722. package/src/supply-chain/license-expression.js +0 -128
  723. package/src/supply-chain/policy.d.ts +0 -105
  724. package/src/supply-chain/policy.js +0 -304
  725. package/src/supply-chain/publication.d.ts +0 -48
  726. package/src/supply-chain/publication.js +0 -85
  727. package/src/supply-chain/sbom.d.ts +0 -228
  728. package/src/supply-chain/sbom.js +0 -913
  729. package/src/supply-chain/scanner.d.ts +0 -77
  730. package/src/supply-chain/scanner.js +0 -514
  731. package/src/supply-chain/vendored-source.d.ts +0 -95
  732. package/src/supply-chain/vendored-source.js +0 -315
  733. package/src/testing-evidence/fixture-scope.d.ts +0 -53
  734. package/src/testing-evidence/fixture-scope.js +0 -142
  735. package/src/testing-evidence/index.d.ts +0 -5
  736. package/src/testing-evidence/index.js +0 -9
  737. package/src/testing-evidence/quarantine.d.ts +0 -48
  738. package/src/testing-evidence/quarantine.js +0 -253
  739. package/src/testing-evidence/result.d.ts +0 -109
  740. package/src/testing-evidence/result.js +0 -585
  741. package/src/testing-evidence/runner-adapter.d.ts +0 -51
  742. package/src/testing-evidence/runner-adapter.js +0 -288
  743. package/src/testing-evidence/sensitive-artifacts.d.ts +0 -13
  744. package/src/testing-evidence/sensitive-artifacts.js +0 -93
  745. package/src/work-markers/index.d.ts +0 -1
  746. package/src/work-markers/index.js +0 -5
  747. package/src/work-markers/work-markers.d.ts +0 -39
  748. package/src/work-markers/work-markers.js +0 -360
  749. package/src/workload-roles/account-baseline.d.ts +0 -143
  750. package/src/workload-roles/account-baseline.js +0 -980
  751. package/src/workload-roles/authority.d.ts +0 -40
  752. package/src/workload-roles/authority.js +0 -202
  753. package/src/workload-roles/aws-adapter.d.ts +0 -99
  754. package/src/workload-roles/aws-adapter.js +0 -416
  755. package/src/workload-roles/aws-internal-handler.d.ts +0 -27
  756. package/src/workload-roles/aws-internal-handler.js +0 -58
  757. package/src/workload-roles/aws-s3-state.d.ts +0 -52
  758. package/src/workload-roles/aws-s3-state.js +0 -191
  759. package/src/workload-roles/aws-sdk-control-plane.d.ts +0 -12
  760. package/src/workload-roles/aws-sdk-control-plane.js +0 -291
  761. package/src/workload-roles/boundary.d.ts +0 -34
  762. package/src/workload-roles/boundary.js +0 -137
  763. package/src/workload-roles/convergence.d.ts +0 -66
  764. package/src/workload-roles/convergence.js +0 -186
  765. package/src/workload-roles/handler.d.ts +0 -43
  766. package/src/workload-roles/handler.js +0 -158
  767. package/src/workload-roles/history.d.ts +0 -47
  768. package/src/workload-roles/history.js +0 -324
  769. package/src/workload-roles/injection.d.ts +0 -119
  770. package/src/workload-roles/injection.js +0 -495
  771. package/src/workload-roles/manifest.d.ts +0 -54
  772. package/src/workload-roles/manifest.js +0 -343
  773. package/src/workload-roles/provisioner.d.ts +0 -70
  774. package/src/workload-roles/provisioner.js +0 -239
  775. package/src/workload-roles/registration.d.ts +0 -102
  776. package/src/workload-roles/registration.js +0 -462
  777. package/src/workload-roles/stage-boundary.d.ts +0 -31
  778. package/src/workload-roles/stage-boundary.js +0 -208
  779. /package/src/executors/{foundation-profile-preflight → local-deploy}/production-database-safeguard.d.ts +0 -0
  780. /package/src/executors/{foundation-profile-preflight → local-deploy}/production-database-safeguard.js +0 -0
@@ -1,4724 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.renderProductReliabilityFiles = renderProductReliabilityFiles;
4
- const reliability_1 = require("@empire-builder-kit/runtime/reliability");
5
- const deterministic_order_js_1 = require("../../deterministic-order.js");
6
- const built_in_plan_alarm_identity_js_1 = require("./built-in-plan-alarm-identity.js");
7
- const built_in_plan_shared_js_1 = require("./built-in-plan-shared.js");
8
- function reliabilityContract(name, reviewedAt) {
9
- return {
10
- escalationRouteKey: `${name}-on-call`,
11
- objectives: [
12
- {
13
- allowedExclusionPolicyRef: 'docs:reliability/exclusions.md',
14
- burn: { fast: 14.4, slow: 6, warning: 0.5 },
15
- effectiveAt: reviewedAt,
16
- feature: 'operations',
17
- id: 'api-availability',
18
- indicator: {
19
- goodEventDefinition: 'Valid API requests complete without a server failure.',
20
- metricRef: 'operations:metrics/api-availability',
21
- type: 'availability',
22
- validEventDefinition: 'Requests reaching a declared API operation, including authorization denials.',
23
- },
24
- journey: 'api-critical-operation',
25
- lowTraffic: { mode: 'data-insufficient' },
26
- minimumValidEvents: {
27
- diagnosticSample: 100,
28
- fastBurnWindow: 1,
29
- objectiveWindow: 100,
30
- slowBurnWindow: 5,
31
- },
32
- owner: `${name}-product`,
33
- references: {
34
- alarmIds: ['api-fast-burn', 'api-slow-burn'],
35
- dashboardRef: 'dashboard:operations',
36
- runbookRef: 'runbook:api-recovery',
37
- },
38
- target: 0.99,
39
- tier: 'critical',
40
- window: { days: 28, kind: 'rolling' },
41
- },
42
- {
43
- allowedExclusionPolicyRef: 'docs:reliability/exclusions.md',
44
- burn: { fast: 14.4, slow: 6, warning: 0.5 },
45
- effectiveAt: reviewedAt,
46
- feature: 'web',
47
- id: 'web-latency',
48
- indicator: {
49
- goodEventDefinition: 'Valid server-rendered requests complete within 1000 milliseconds.',
50
- metricRef: 'operations:metrics/web-latency',
51
- threshold: 1000,
52
- type: 'latency',
53
- unit: 'Milliseconds',
54
- validEventDefinition: 'Requests reaching the generated web application.',
55
- },
56
- journey: 'web-critical-route',
57
- lowTraffic: { mode: 'data-insufficient' },
58
- minimumValidEvents: {
59
- diagnosticSample: 100,
60
- fastBurnWindow: 1,
61
- objectiveWindow: 100,
62
- slowBurnWindow: 5,
63
- },
64
- owner: `${name}-product`,
65
- references: {
66
- alarmIds: ['web-latency-fast-burn', 'web-latency-slow-burn'],
67
- dashboardRef: 'dashboard:operations',
68
- runbookRef: 'runbook:web-recovery',
69
- },
70
- target: 0.95,
71
- tier: 'important',
72
- window: { days: 28, kind: 'rolling' },
73
- },
74
- {
75
- allowedExclusionPolicyRef: 'docs:reliability/exclusions.md',
76
- burn: { fast: 14.4, slow: 6, warning: 0.5 },
77
- effectiveAt: reviewedAt,
78
- feature: 'async-work',
79
- id: 'async-delivery-deadline',
80
- indicator: {
81
- goodEventDefinition: 'Accepted provider deliveries leave the queue within 900 seconds.',
82
- metricRef: 'operations:metrics/async-delivery-deadline',
83
- threshold: 900,
84
- type: 'deadline',
85
- unit: 'Seconds',
86
- validEventDefinition: 'Provider deliveries durably accepted into the generated queue.',
87
- },
88
- journey: 'provider-delivery',
89
- lowTraffic: { mode: 'data-insufficient' },
90
- minimumValidEvents: {
91
- diagnosticSample: 10,
92
- fastBurnWindow: 1,
93
- objectiveWindow: 10,
94
- slowBurnWindow: 5,
95
- },
96
- owner: `${name}-product`,
97
- references: {
98
- alarmIds: ['provider-queue-age'],
99
- dashboardRef: 'dashboard:operations',
100
- runbookRef: 'runbook:async-recovery',
101
- },
102
- target: 0.99,
103
- tier: 'important',
104
- window: { days: 28, kind: 'rolling' },
105
- },
106
- ],
107
- owner: `${name}-product`,
108
- providerDecision: {
109
- applicationSignalsCoverage: ['lambda', 'next'],
110
- basis: 'Direct CloudWatch metric math covers the generated Lambda, Next.js, queue, Service, Job, and database surfaces without making Application Signals mandatory. Re-evaluate with retained exact-candidate coverage and cost evidence.',
111
- cost: {
112
- currency: 'USD',
113
- monthly: 0,
114
- provenance: 'estimate',
115
- },
116
- directMetricMathCoverage: [
117
- 'lambda',
118
- 'next',
119
- 'queue',
120
- 'service',
121
- 'job',
122
- 'database',
123
- 'alert-delivery',
124
- ],
125
- reviewedAt,
126
- selected: 'direct-cloudwatch-metric-math',
127
- },
128
- schemaVersion: 1,
129
- slice: name,
130
- };
131
- }
132
- function alarmRegistrations(name, sql) {
133
- const common = {
134
- expectedFalseNegativeRisk: 'Low traffic or delayed CloudWatch data can delay detection.',
135
- expectedFalsePositiveRisk: 'A dependency or synthetic client can fail while the application remains healthy.',
136
- missingData: 'missing',
137
- testRef: 'evidence:reliability/failure-recovery',
138
- };
139
- // Symptom, owner, route and runbook come from the shared alarm identity
140
- // table, as every managed emitter's description does.
141
- const registered = (id) => {
142
- const identity = (0, built_in_plan_alarm_identity_js_1.sliceAlarmIdentity)(name, id);
143
- return {
144
- ...common,
145
- businessSymptom: identity.businessSymptom,
146
- escalationRouteKey: identity.route,
147
- id,
148
- owner: identity.owner,
149
- runbookRef: identity.runbookRef,
150
- };
151
- };
152
- const registrations = [
153
- {
154
- ...registered('api-fast-burn'),
155
- condition: 'The API availability objective is consuming budget rapidly.',
156
- dependencyAlarmIds: ['database-capacity'],
157
- severity: 'critical',
158
- },
159
- {
160
- ...registered('api-slow-burn'),
161
- condition: 'The API availability objective is consuming budget slowly.',
162
- dependencyAlarmIds: ['database-capacity'],
163
- severity: 'high',
164
- },
165
- {
166
- ...registered('web-latency-fast-burn'),
167
- condition: 'Web p95 latency exceeds the reviewed threshold.',
168
- dependencyAlarmIds: ['database-capacity'],
169
- severity: 'high',
170
- },
171
- {
172
- ...registered('web-latency-slow-burn'),
173
- condition: 'Web p95 latency remains above the reviewed threshold for the slow window.',
174
- dependencyAlarmIds: ['database-capacity'],
175
- severity: 'high',
176
- },
177
- {
178
- ...registered('provider-queue-age'),
179
- condition: 'Oldest provider-queue work exceeds 900 seconds.',
180
- dependencyAlarmIds: [],
181
- severity: 'high',
182
- },
183
- {
184
- ...registered('database-capacity'),
185
- condition: 'The Slice DynamoDB table or PendingEvents index reports read or write throttling.',
186
- dependencyAlarmIds: [],
187
- severity: 'high',
188
- },
189
- {
190
- ...registered('performance-load-cleanup-backlog'),
191
- condition: 'The bounded performance-load expiry cleanup reports a nonzero backlog.',
192
- dependencyAlarmIds: [],
193
- severity: 'high',
194
- },
195
- {
196
- ...registered('performance-load-cleanup-deadline'),
197
- condition: 'The bounded expiry worker reports residue at least 24 hours past eligible expiry.',
198
- dependencyAlarmIds: ['performance-load-cleanup-backlog'],
199
- severity: 'critical',
200
- },
201
- {
202
- ...registered('data-export-cleanup-failure'),
203
- condition: 'AWS/Lambda reports an error for the exact generated confidential-export cleanup Function.',
204
- dependencyAlarmIds: [],
205
- severity: 'high',
206
- },
207
- {
208
- ...registered('data-export-cleanup-invocation-missing'),
209
- condition: 'AWS/Lambda reports fewer than one invocation across two consecutive hourly periods.',
210
- dependencyAlarmIds: [],
211
- severity: 'critical',
212
- },
213
- {
214
- ...registered('data-export-cleanup-deadline'),
215
- condition: 'The cleanup worker reports an open export at or after its immutable 24-hour cleanup deadline.',
216
- dependencyAlarmIds: [
217
- 'data-export-cleanup-failure',
218
- 'data-export-cleanup-invocation-missing',
219
- ],
220
- severity: 'critical',
221
- },
222
- {
223
- ...registered('function-failure'),
224
- condition: 'AWS/Lambda reports one or more errors in one minute for the exact generated data-export cleanup Function. Event-delivery Functions have their own error alarms.',
225
- dependencyAlarmIds: [],
226
- severity: 'high',
227
- },
228
- {
229
- ...registered('retention-job-failure'),
230
- condition: 'AWS Step Functions reports a failed, timed-out, or aborted execution for the exact retention state machine.',
231
- dependencyAlarmIds: [],
232
- severity: 'high',
233
- },
234
- {
235
- ...registered('alert-delivery-degraded'),
236
- condition: 'SNS reports one or more failed notifications.',
237
- dependencyAlarmIds: [],
238
- severity: 'critical',
239
- },
240
- {
241
- ...registered('data-protection-findings'),
242
- condition: 'CloudWatch Logs reports one or more protected-data findings.',
243
- dependencyAlarmIds: [],
244
- severity: 'critical',
245
- },
246
- {
247
- ...registered('event-dlq-depth'),
248
- condition: 'The event dead-letter queue contains one or more messages.',
249
- dependencyAlarmIds: [],
250
- severity: 'high',
251
- },
252
- {
253
- ...registered('provider-dlq-depth'),
254
- condition: 'The provider-delivery dead-letter queue contains one or more messages.',
255
- dependencyAlarmIds: [],
256
- severity: 'high',
257
- },
258
- {
259
- ...registered('async-target-dlq-depth'),
260
- condition: 'The asynchronous-target dead-letter queue contains one or more messages.',
261
- dependencyAlarmIds: [],
262
- severity: 'high',
263
- },
264
- {
265
- ...registered('outbox-relay-errors'),
266
- condition: 'AWS/Lambda reports one or more errors in five minutes for the generated async/outbox-relay Function, which drains only the isolated performance sink. Domain-event delivery is the key-value stream and reconciliation.',
267
- dependencyAlarmIds: [],
268
- severity: 'high',
269
- },
270
- {
271
- ...registered('inbox-cleanup-errors'),
272
- condition: 'The generated inbox cleanup job reports one or more errors.',
273
- dependencyAlarmIds: [],
274
- severity: 'high',
275
- },
276
- {
277
- ...registered('key-value-stream-delivery-errors'),
278
- condition: 'AWS/Lambda reports one or more errors in five minutes for the exact key-value stream delivery Function: the stream identity or record shape was rejected, or the handler crashed. Per-record publish failures are partial batch failures, not Lambda errors; they surface through key-value-stream-iterator-age while retries hold the shard back, and through outbox-backlog and event-delivery-attempts after the mapping discards them.',
279
- dependencyAlarmIds: [],
280
- severity: 'high',
281
- },
282
- {
283
- ...registered('key-value-stream-iterator-age'),
284
- condition: 'AWS/Lambda reports a stream iterator age of at least ten minutes for the exact key-value stream delivery Function. The mapping discards records older than one hour; reconciliation then recovers their retained intents.',
285
- dependencyAlarmIds: ['key-value-stream-delivery-errors'],
286
- severity: 'high',
287
- },
288
- {
289
- ...registered('key-value-reconciliation-errors'),
290
- condition: 'AWS/Lambda reports one or more errors in five minutes for the exact key-value reconciliation Function. Partial runs do not error; the backlog, rejected-intent, and attempts alarms report them.',
291
- dependencyAlarmIds: [],
292
- severity: 'high',
293
- },
294
- {
295
- ...registered('outbox-backlog'),
296
- condition: 'In two consecutive hours, key-value reconciliation reported one or more due intents it could not deliver (retry-required plus rejected). Each run reads at most one 25-intent page per shard, so the value is a lower bound, not a global count, and excludes intents leased by another delivery owner.',
297
- dependencyAlarmIds: [
298
- 'key-value-reconciliation-errors',
299
- 'key-value-stream-delivery-errors',
300
- ],
301
- expectedFalseNegativeRisk: 'Intents beyond the sampled pages, or behind a paused outbox, are not counted until a later run reaches them. When the configured reconciliation cadence is slower than one hour, some hourly periods have no data and the two-period condition may never be met.',
302
- severity: 'high',
303
- },
304
- {
305
- ...registered('event-intent-rejected'),
306
- condition: 'Within an hour, key-value reconciliation reported one or more retained intents that fail validation. Rejected intents are never dispatched or deleted, so this recurs until an operator investigates.',
307
- dependencyAlarmIds: [],
308
- severity: 'high',
309
- },
310
- {
311
- ...registered('event-delivery-attempts'),
312
- condition: 'Within an hour, key-value reconciliation observed a due intent with at least ten delivery leases (attempts). Attempts are reported only; no intent is capped, dropped, or quarantined.',
313
- dependencyAlarmIds: ['key-value-reconciliation-errors'],
314
- severity: 'high',
315
- },
316
- {
317
- ...registered('inbox-cleanup-backlog'),
318
- condition: 'The terminal inbox cleanup backlog remains nonempty.',
319
- dependencyAlarmIds: ['inbox-cleanup-errors'],
320
- severity: 'high',
321
- },
322
- ...(sql
323
- ? [
324
- {
325
- ...registered('sql-outbox-relay-errors'),
326
- condition: 'AWS/Lambda reports one or more errors in five minutes for the exact SQL outbox relay Function, which fails every run that retains a failed delivery.',
327
- dependencyAlarmIds: [],
328
- severity: 'high',
329
- },
330
- {
331
- ...registered('sql-outbox-backlog'),
332
- condition: 'Every SQL relay run in two consecutive hours ended with one or more unpublished intents (Minimum of a global count). A paused relay reports nothing.',
333
- dependencyAlarmIds: ['sql-outbox-relay-errors'],
334
- expectedFalseNegativeRisk: 'A paused relay reports nothing. When the configured sqlOutboxRecovery cadence is slower than one hour and no notification wakes the relay, some hourly periods have no data and the two-period condition may never be met.',
335
- severity: 'high',
336
- },
337
- {
338
- ...registered('sql-outbox-attempts'),
339
- condition: 'Within an hour, an unpublished SQL intent reached at least ten relay attempts. Attempts are reported only; no intent is capped or dropped.',
340
- dependencyAlarmIds: ['sql-outbox-relay-errors'],
341
- severity: 'high',
342
- },
343
- ]
344
- : []),
345
- ];
346
- return registrations.map((registration) => (0, reliability_1.validateAlarmRegistrationMetadata)(registration));
347
- }
348
- function reliabilityExercises(name) {
349
- const shared = {
350
- cleanupRequired: true,
351
- owner: `${name}-product`,
352
- protectedMutationRequiresApproval: true,
353
- };
354
- return [
355
- {
356
- ...shared,
357
- failure: 'Inject one bounded generated API handler failure.',
358
- id: 'lambda-api-failure',
359
- observation: {
360
- adapter: 'aws-cloudwatch-alarm-history-v1',
361
- alarmIds: ['api-fast-burn'],
362
- dynamicAlarmKind: 'none',
363
- workflowMetadata: 'none',
364
- },
365
- postconditions: [
366
- 'critical API journey succeeds',
367
- 'alarm returns to normal without being disabled',
368
- 'release and configuration identity remain attributable',
369
- ],
370
- recovery: ['retry', 'roll-forward', 'protected-revert'],
371
- workload: 'lambda-api',
372
- },
373
- {
374
- ...shared,
375
- failure: 'Inject a bounded health or dependency failure in an EBK Service.',
376
- id: 'service-failure',
377
- observation: {
378
- adapter: 'aws-cloudwatch-alarm-history-v1',
379
- alarmIds: [],
380
- dynamicAlarmKind: 'service',
381
- workflowMetadata: 'none',
382
- },
383
- postconditions: [
384
- 'service readiness recovers',
385
- 'critical dependency remains protected',
386
- ],
387
- recovery: ['retry', 'roll-forward', 'degraded-mode'],
388
- workload: 'service',
389
- },
390
- {
391
- ...shared,
392
- failure: 'Inject one bounded generated Job failure before completion.',
393
- id: 'job-failure',
394
- observation: {
395
- adapter: 'aws-cloudwatch-alarm-history-v1',
396
- alarmIds: [],
397
- dynamicAlarmKind: 'job',
398
- workflowMetadata: 'none',
399
- },
400
- postconditions: [
401
- 'checkpoint or idempotency state is retained',
402
- 'deadline outcome is verified',
403
- ],
404
- recovery: ['retry', 'roll-forward'],
405
- workload: 'job',
406
- },
407
- {
408
- ...shared,
409
- failure: 'Run the built-in retention state machine with a bounded failing fixture.',
410
- id: 'retention-job-failure',
411
- observation: {
412
- adapter: 'aws-cloudwatch-alarm-history-v1',
413
- alarmIds: ['retention-job-failure'],
414
- dynamicAlarmKind: 'none',
415
- workflowMetadata: 'required',
416
- },
417
- postconditions: [
418
- 'the exact state machine execution reaches a terminal failure',
419
- 'the AWS-native execution alarm fires',
420
- 'the later recovery execution succeeds without weakening retention policy',
421
- ],
422
- recovery: ['retry', 'roll-forward'],
423
- workload: 'built-in-retention-job',
424
- },
425
- {
426
- ...shared,
427
- failure: 'Route a deterministic poison fixture to the generated DLQ.',
428
- id: 'queue-dlq-failure',
429
- observation: {
430
- adapter: 'aws-cloudwatch-alarm-history-v1',
431
- alarmIds: [
432
- 'async-target-dlq-depth',
433
- 'event-dlq-depth',
434
- 'provider-dlq-depth',
435
- ],
436
- dynamicAlarmKind: 'none',
437
- workflowMetadata: 'optional',
438
- },
439
- postconditions: [
440
- 'DLQ alarm fires',
441
- 'bounded redrive converges',
442
- 'no duplicate provider effect occurs',
443
- ],
444
- recovery: ['redrive', 'replay'],
445
- workload: 'queue-dlq',
446
- },
447
- {
448
- ...shared,
449
- failure: 'Inject bounded dependency latency and an availability failure.',
450
- id: 'dependency-failure',
451
- observation: {
452
- adapter: 'aws-cloudwatch-alarm-history-v1',
453
- alarmIds: ['api-fast-burn'],
454
- dynamicAlarmKind: 'none',
455
- workflowMetadata: 'none',
456
- },
457
- postconditions: [
458
- 'retry amplification stays bounded',
459
- 'critical work degrades or queues as declared',
460
- ],
461
- recovery: ['retry', 'degraded-mode', 'roll-forward'],
462
- workload: 'dependency',
463
- },
464
- {
465
- ...shared,
466
- failure: 'Exercise database unavailability or cold-resume latency.',
467
- id: 'database-failure',
468
- observation: {
469
- adapter: 'aws-cloudwatch-alarm-history-v1',
470
- alarmIds: ['database-capacity'],
471
- dynamicAlarmKind: 'none',
472
- workflowMetadata: 'none',
473
- },
474
- postconditions: [
475
- 'data invariants pass',
476
- 'connection concurrency remains bounded',
477
- 'critical journey recovery is verified',
478
- ],
479
- recovery: ['retry', 'restore', 'roll-forward'],
480
- workload: 'database',
481
- },
482
- {
483
- ...shared,
484
- failure: 'Fail the primary alert destination during a bounded proof.',
485
- id: 'alert-delivery-failure',
486
- observation: {
487
- adapter: 'aws-cloudwatch-alarm-history-v1',
488
- alarmIds: ['alert-delivery-degraded'],
489
- dynamicAlarmKind: 'none',
490
- workflowMetadata: 'none',
491
- },
492
- postconditions: [
493
- 'diagnostic degradation is recorded without using the failed route',
494
- 'delivery is unsupported unless an independent provider receipt exists',
495
- ],
496
- recovery: ['roll-forward'],
497
- workload: 'alert-delivery',
498
- },
499
- {
500
- ...shared,
501
- failure: 'Retain one exact deployed-smoke failure artifact before the successful rerun.',
502
- id: 'runtime-smoke-failure',
503
- observation: {
504
- adapter: 'testing-evidence-aggregate-v1',
505
- alarmIds: [],
506
- dynamicAlarmKind: 'none',
507
- workflowMetadata: 'none',
508
- },
509
- postconditions: [
510
- 'the testing-evidence aggregate binds the exact deployment and candidate',
511
- 'the failure remains retained beside the successful rerun',
512
- 'cleanup evidence is complete',
513
- ],
514
- recovery: ['retry', 'roll-forward'],
515
- workload: 'deployed-smoke',
516
- },
517
- ];
518
- }
519
- const ROUTED_INVENTORY_LEADING_KEYS = [
520
- 'actions',
521
- 'comparisonOperator',
522
- 'owner',
523
- 'route',
524
- ];
525
- /**
526
- * One inventory entry with the shared identity's owner, route and runbook,
527
- * the fields the generated verifier compares with the deployed alarm's
528
- * description. Keys keep the seeded order: a routed alarm's actions,
529
- * comparison operator, owner and route first, then the rest sorted.
530
- */
531
- function inventoryAlarmResource(name, resource) {
532
- const identity = (0, built_in_plan_alarm_identity_js_1.sliceAlarmIdentity)(name, resource.id);
533
- const fields = {
534
- ...resource,
535
- owner: identity.owner,
536
- route: identity.route,
537
- runbook: identity.runbook,
538
- };
539
- const leading = resource.actions === 'primary-route' ? ROUTED_INVENTORY_LEADING_KEYS : [];
540
- return Object.fromEntries([
541
- ...leading,
542
- ...Object.keys(fields)
543
- .filter((key) => !leading.includes(key))
544
- .sort(deterministic_order_js_1.compareUtf16),
545
- ].map((key) => [key, fields[key]]));
546
- }
547
- function deployedAlarmResources(name, sql) {
548
- const primary = {
549
- actions: 'primary-route',
550
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
551
- };
552
- const resources = [
553
- {
554
- ...primary,
555
- dimensionNames: ['ApiId'],
556
- evaluationPeriods: 1,
557
- id: 'api-fast-burn',
558
- metricNames: ['5xx', 'Count'],
559
- name: `${name}-{stage}-api-fast-burn`,
560
- namespace: 'AWS/ApiGateway',
561
- objectiveId: 'api-availability',
562
- signal: 'metric-math',
563
- threshold: 14.4,
564
- treatMissingData: 'missing',
565
- },
566
- {
567
- ...primary,
568
- dimensionNames: ['ApiId'],
569
- evaluationPeriods: 1,
570
- id: 'api-slow-burn',
571
- metricNames: ['5xx', 'Count'],
572
- name: `${name}-{stage}-api-slow-burn`,
573
- namespace: 'AWS/ApiGateway',
574
- objectiveId: 'api-availability',
575
- signal: 'metric-math',
576
- threshold: 6,
577
- treatMissingData: 'missing',
578
- },
579
- {
580
- ...primary,
581
- dimensionNames: ['Component', 'Feature', 'Operation', 'Slice', 'Stage'],
582
- dimensionValues: {
583
- Component: 'next-server',
584
- Feature: 'web',
585
- Operation: 'request',
586
- Slice: name,
587
- Stage: '{stage}',
588
- },
589
- evaluationPeriods: 1,
590
- id: 'web-latency-fast-burn',
591
- metricNames: ['OperationGood', 'OperationValid'],
592
- name: `${name}-{stage}-web-latency-fast-burn`,
593
- namespace: `EBK/${name}`,
594
- objectiveId: 'web-latency',
595
- signal: 'metric-math',
596
- threshold: 14.4,
597
- treatMissingData: 'missing',
598
- },
599
- {
600
- ...primary,
601
- dimensionNames: ['Component', 'Feature', 'Operation', 'Slice', 'Stage'],
602
- dimensionValues: {
603
- Component: 'next-server',
604
- Feature: 'web',
605
- Operation: 'request',
606
- Slice: name,
607
- Stage: '{stage}',
608
- },
609
- evaluationPeriods: 1,
610
- id: 'web-latency-slow-burn',
611
- metricNames: ['OperationGood', 'OperationValid'],
612
- name: `${name}-{stage}-web-latency-slow-burn`,
613
- namespace: `EBK/${name}`,
614
- objectiveId: 'web-latency',
615
- signal: 'metric-math',
616
- threshold: 6,
617
- treatMissingData: 'missing',
618
- },
619
- {
620
- ...primary,
621
- dimensionNames: ['QueueName'],
622
- dimensionValues: {
623
- QueueName: `ebk-{stage}-${name}-provider-queue`,
624
- },
625
- evaluationPeriods: 2,
626
- id: 'provider-queue-age',
627
- metricName: 'ApproximateAgeOfOldestMessage',
628
- name: `${name}-{stage}-provider-deadline`,
629
- namespace: 'AWS/SQS',
630
- period: 300,
631
- signal: 'metric',
632
- statistic: 'Maximum',
633
- threshold: 900,
634
- treatMissingData: 'missing',
635
- },
636
- {
637
- ...primary,
638
- dimensionNames: ['GlobalSecondaryIndexName', 'TableName'],
639
- dimensionValues: { GlobalSecondaryIndexName: 'PendingEvents' },
640
- evaluationPeriods: 1,
641
- id: 'database-capacity',
642
- metricNames: ['ReadThrottleEvents', 'WriteThrottleEvents'],
643
- name: `${name}-{stage}-database-capacity`,
644
- namespace: 'AWS/DynamoDB',
645
- period: 60,
646
- signal: 'metric-math',
647
- statistic: 'Sum',
648
- threshold: 1,
649
- treatMissingData: 'notBreaching',
650
- },
651
- {
652
- ...primary,
653
- dimensionNames: ['Component', 'Feature', 'Operation', 'Slice', 'Stage'],
654
- dimensionValues: {
655
- Component: 'performance-load-cleanup',
656
- Feature: 'performance',
657
- Operation: 'expiry-cleanup',
658
- Slice: name,
659
- Stage: '{stage}',
660
- },
661
- evaluationPeriods: 2,
662
- id: 'performance-load-cleanup-backlog',
663
- metricName: 'PerformanceLoadCleanupBacklog',
664
- name: `${name}-{stage}-performance-load-cleanup-backlog`,
665
- namespace: 'EBK/Performance',
666
- period: 3600,
667
- signal: 'metric',
668
- statistic: 'Maximum',
669
- threshold: 1,
670
- treatMissingData: 'notBreaching',
671
- },
672
- {
673
- ...primary,
674
- dimensionNames: ['Component', 'Feature', 'Operation', 'Slice', 'Stage'],
675
- dimensionValues: {
676
- Component: 'performance-load-cleanup',
677
- Feature: 'performance',
678
- Operation: 'expiry-cleanup',
679
- Slice: name,
680
- Stage: '{stage}',
681
- },
682
- evaluationPeriods: 1,
683
- id: 'performance-load-cleanup-deadline',
684
- metricName: 'PerformanceLoadCleanupDeadlineBreaches',
685
- name: `${name}-{stage}-performance-load-cleanup-deadline`,
686
- namespace: 'EBK/Performance',
687
- period: 3600,
688
- signal: 'metric',
689
- statistic: 'Maximum',
690
- threshold: 1,
691
- treatMissingData: 'notBreaching',
692
- },
693
- {
694
- ...primary,
695
- comparisonOperator: 'LessThanThreshold',
696
- dimensionNames: ['FunctionName'],
697
- evaluationPeriods: 2,
698
- id: 'data-export-cleanup-invocation-missing',
699
- metricName: 'Invocations',
700
- name: `${name}-{stage}-data-export-cleanup-invocation-missing`,
701
- namespace: 'AWS/Lambda',
702
- period: 3600,
703
- signal: 'metric',
704
- statistic: 'Sum',
705
- threshold: 1,
706
- treatMissingData: 'breaching',
707
- },
708
- {
709
- ...primary,
710
- dimensionNames: ['FunctionName'],
711
- evaluationPeriods: 1,
712
- id: 'data-export-cleanup-failure',
713
- metricName: 'Errors',
714
- name: `${name}-{stage}-data-export-cleanup-failure`,
715
- namespace: 'AWS/Lambda',
716
- period: 300,
717
- signal: 'metric',
718
- statistic: 'Sum',
719
- threshold: 1,
720
- treatMissingData: 'notBreaching',
721
- },
722
- {
723
- ...primary,
724
- dimensionNames: ['Component', 'Feature', 'Operation', 'Slice', 'Stage'],
725
- dimensionValues: {
726
- Component: 'data-export-cleanup',
727
- Feature: 'data-lifecycle',
728
- Operation: 'expiry-cleanup',
729
- Slice: name,
730
- Stage: '{stage}',
731
- },
732
- evaluationPeriods: 1,
733
- id: 'data-export-cleanup-deadline',
734
- metricName: 'DataExportCleanupDeadlineBreaches',
735
- name: `${name}-{stage}-data-export-cleanup-deadline`,
736
- namespace: 'EBK/DataLifecycle',
737
- period: 3600,
738
- signal: 'metric',
739
- statistic: 'Maximum',
740
- threshold: 1,
741
- treatMissingData: 'notBreaching',
742
- },
743
- {
744
- ...primary,
745
- dimensionNames: ['FunctionName'],
746
- evaluationPeriods: 1,
747
- id: 'function-failure',
748
- metricName: 'Errors',
749
- name: `${name}-{stage}-function-failure`,
750
- namespace: 'AWS/Lambda',
751
- period: 60,
752
- signal: 'metric',
753
- statistic: 'Sum',
754
- threshold: 1,
755
- treatMissingData: 'notBreaching',
756
- },
757
- {
758
- ...primary,
759
- dimensionNames: ['StateMachineArn'],
760
- evaluationPeriods: 1,
761
- id: 'retention-job-failure',
762
- metricNames: [
763
- 'ExecutionsAborted',
764
- 'ExecutionsFailed',
765
- 'ExecutionsTimedOut',
766
- ],
767
- name: `${name}-{stage}-retention-job-failure`,
768
- namespace: 'AWS/States',
769
- signal: 'metric-math',
770
- threshold: 1,
771
- treatMissingData: 'notBreaching',
772
- },
773
- {
774
- ...primary,
775
- dimensionNames: ['QueueName'],
776
- dimensionValues: {
777
- QueueName: `ebk-{stage}-${name}-event-dlq`,
778
- },
779
- evaluationPeriods: 1,
780
- id: 'event-dlq-depth',
781
- metricName: 'ApproximateNumberOfMessagesVisible',
782
- name: `${name}-{stage}-event-dlq-depth`,
783
- namespace: 'AWS/SQS',
784
- period: 300,
785
- signal: 'metric',
786
- statistic: 'Maximum',
787
- threshold: 1,
788
- treatMissingData: 'notBreaching',
789
- },
790
- {
791
- ...primary,
792
- dimensionNames: ['QueueName'],
793
- dimensionValues: {
794
- QueueName: `ebk-{stage}-${name}-provider-dlq`,
795
- },
796
- evaluationPeriods: 1,
797
- id: 'provider-dlq-depth',
798
- metricName: 'ApproximateNumberOfMessagesVisible',
799
- name: `${name}-{stage}-provider-dlq-depth`,
800
- namespace: 'AWS/SQS',
801
- period: 300,
802
- signal: 'metric',
803
- statistic: 'Maximum',
804
- threshold: 1,
805
- treatMissingData: 'notBreaching',
806
- },
807
- {
808
- ...primary,
809
- dimensionNames: ['QueueName'],
810
- dimensionValues: {
811
- QueueName: `ebk-{stage}-${name}-async-target-dlq`,
812
- },
813
- evaluationPeriods: 1,
814
- id: 'async-target-dlq-depth',
815
- metricName: 'ApproximateNumberOfMessagesVisible',
816
- name: `${name}-{stage}-async-target-dlq-depth`,
817
- namespace: 'AWS/SQS',
818
- period: 300,
819
- signal: 'metric',
820
- statistic: 'Maximum',
821
- threshold: 1,
822
- treatMissingData: 'notBreaching',
823
- },
824
- {
825
- ...primary,
826
- dimensionNames: ['FunctionName'],
827
- evaluationPeriods: 1,
828
- id: 'outbox-relay-errors',
829
- metricName: 'Errors',
830
- name: `${name}-{stage}-outbox-relay-errors`,
831
- namespace: 'AWS/Lambda',
832
- period: 300,
833
- signal: 'metric',
834
- statistic: 'Sum',
835
- threshold: 1,
836
- treatMissingData: 'notBreaching',
837
- },
838
- {
839
- ...primary,
840
- dimensionNames: ['FunctionName'],
841
- evaluationPeriods: 1,
842
- id: 'inbox-cleanup-errors',
843
- metricName: 'Errors',
844
- name: `${name}-{stage}-inbox-cleanup-errors`,
845
- namespace: 'AWS/Lambda',
846
- period: 300,
847
- signal: 'metric',
848
- statistic: 'Sum',
849
- threshold: 1,
850
- treatMissingData: 'notBreaching',
851
- },
852
- {
853
- ...primary,
854
- dimensionNames: ['FunctionName'],
855
- evaluationPeriods: 1,
856
- id: 'key-value-stream-delivery-errors',
857
- metricName: 'Errors',
858
- name: `${name}-{stage}-key-value-stream-delivery-errors`,
859
- namespace: 'AWS/Lambda',
860
- period: 300,
861
- signal: 'metric',
862
- statistic: 'Sum',
863
- threshold: 1,
864
- treatMissingData: 'notBreaching',
865
- },
866
- {
867
- ...primary,
868
- dimensionNames: ['FunctionName'],
869
- evaluationPeriods: 1,
870
- id: 'key-value-stream-iterator-age',
871
- metricName: 'IteratorAge',
872
- name: `${name}-{stage}-key-value-stream-iterator-age`,
873
- namespace: 'AWS/Lambda',
874
- period: 300,
875
- signal: 'metric',
876
- statistic: 'Maximum',
877
- threshold: 600_000,
878
- treatMissingData: 'notBreaching',
879
- },
880
- {
881
- ...primary,
882
- dimensionNames: ['FunctionName'],
883
- evaluationPeriods: 1,
884
- id: 'key-value-reconciliation-errors',
885
- metricName: 'Errors',
886
- name: `${name}-{stage}-key-value-reconciliation-errors`,
887
- namespace: 'AWS/Lambda',
888
- period: 300,
889
- signal: 'metric',
890
- statistic: 'Sum',
891
- threshold: 1,
892
- treatMissingData: 'notBreaching',
893
- },
894
- {
895
- ...primary,
896
- dimensionNames: ['Slice', 'Stage'],
897
- dimensionValues: { Slice: name, Stage: '{stage}' },
898
- evaluationPeriods: 2,
899
- id: 'outbox-backlog',
900
- metricName: 'OutboxBacklog',
901
- name: `${name}-{stage}-outbox-backlog`,
902
- namespace: 'EBK/Async',
903
- period: 3600,
904
- signal: 'metric',
905
- statistic: 'Maximum',
906
- threshold: 1,
907
- treatMissingData: 'notBreaching',
908
- },
909
- {
910
- ...primary,
911
- dimensionNames: ['Slice', 'Stage'],
912
- dimensionValues: { Slice: name, Stage: '{stage}' },
913
- evaluationPeriods: 1,
914
- id: 'event-intent-rejected',
915
- metricName: 'EventReconciliationRejected',
916
- name: `${name}-{stage}-event-intent-rejected`,
917
- namespace: 'EBK/Async',
918
- period: 3600,
919
- signal: 'metric',
920
- statistic: 'Maximum',
921
- threshold: 1,
922
- treatMissingData: 'notBreaching',
923
- },
924
- {
925
- ...primary,
926
- dimensionNames: ['Slice', 'Stage'],
927
- dimensionValues: { Slice: name, Stage: '{stage}' },
928
- evaluationPeriods: 1,
929
- id: 'event-delivery-attempts',
930
- metricName: 'EventDeliveryMaxAttempts',
931
- name: `${name}-{stage}-event-delivery-attempts`,
932
- namespace: 'EBK/Async',
933
- period: 3600,
934
- signal: 'metric',
935
- statistic: 'Maximum',
936
- threshold: 10,
937
- treatMissingData: 'notBreaching',
938
- },
939
- ...(sql
940
- ? [
941
- {
942
- ...primary,
943
- dimensionNames: ['FunctionName'],
944
- evaluationPeriods: 1,
945
- id: 'sql-outbox-relay-errors',
946
- metricName: 'Errors',
947
- name: `${name}-{stage}-sql-outbox-relay-errors`,
948
- namespace: 'AWS/Lambda',
949
- period: 300,
950
- signal: 'metric',
951
- statistic: 'Sum',
952
- threshold: 1,
953
- treatMissingData: 'notBreaching',
954
- },
955
- {
956
- ...primary,
957
- dimensionNames: ['Slice', 'Stage'],
958
- dimensionValues: { Slice: name, Stage: '{stage}' },
959
- evaluationPeriods: 2,
960
- id: 'sql-outbox-backlog',
961
- metricName: 'SqlOutboxBacklog',
962
- name: `${name}-{stage}-sql-outbox-backlog`,
963
- namespace: 'EBK/Async',
964
- period: 3600,
965
- signal: 'metric',
966
- statistic: 'Minimum',
967
- threshold: 1,
968
- treatMissingData: 'notBreaching',
969
- },
970
- {
971
- ...primary,
972
- dimensionNames: ['Slice', 'Stage'],
973
- dimensionValues: { Slice: name, Stage: '{stage}' },
974
- evaluationPeriods: 1,
975
- id: 'sql-outbox-attempts',
976
- metricName: 'SqlOutboxMaxAttempts',
977
- name: `${name}-{stage}-sql-outbox-attempts`,
978
- namespace: 'EBK/Async',
979
- period: 3600,
980
- signal: 'metric',
981
- statistic: 'Maximum',
982
- threshold: 10,
983
- treatMissingData: 'notBreaching',
984
- },
985
- ]
986
- : []),
987
- {
988
- ...primary,
989
- dimensionNames: ['Component', 'Feature', 'Operation', 'Slice', 'Stage'],
990
- dimensionValues: {
991
- Component: 'inbox-cleanup',
992
- Feature: 'async-work',
993
- Operation: 'inbox-cleanup',
994
- Slice: name,
995
- Stage: '{stage}',
996
- },
997
- evaluationPeriods: 2,
998
- id: 'inbox-cleanup-backlog',
999
- metricName: 'InboxCleanupBacklog',
1000
- name: `${name}-{stage}-inbox-cleanup-backlog`,
1001
- namespace: 'EBK/Async',
1002
- period: 3600,
1003
- signal: 'metric',
1004
- statistic: 'Maximum',
1005
- threshold: 1,
1006
- treatMissingData: 'notBreaching',
1007
- },
1008
- {
1009
- actions: 'none',
1010
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1011
- dimensionNames: ['TopicName'],
1012
- evaluationPeriods: 1,
1013
- id: 'alert-delivery-degraded',
1014
- metricName: 'NumberOfNotificationsFailed',
1015
- name: `${name}-{stage}-alert-delivery-degraded`,
1016
- namespace: 'AWS/SNS',
1017
- period: 300,
1018
- signal: 'metric',
1019
- statistic: 'Sum',
1020
- threshold: 1,
1021
- treatMissingData: 'notBreaching',
1022
- },
1023
- ];
1024
- return resources.map((resource) => inventoryAlarmResource(name, resource));
1025
- }
1026
- /** @internal */
1027
- function renderProductReliabilityFiles(name, pascalName, reviewedAt, sql = false) {
1028
- const contract = reliabilityContract(name, reviewedAt);
1029
- const alarms = alarmRegistrations(name, sql);
1030
- const exercises = reliabilityExercises(name);
1031
- const ownership = (0, built_in_plan_alarm_identity_js_1.sliceAlarmOwnership)(name);
1032
- return {
1033
- 'docs/reliability/slo.json': (0, built_in_plan_shared_js_1.json)(contract),
1034
- 'docs/reliability/exclusions.md': `# SLO exclusions
1035
-
1036
- This adopter-owned record starts empty. An exclusion must name one generated
1037
- SLO ID, owner, reason, bounded UTC start and end, and review reference. Define
1038
- planned maintenance exclusions before the window where possible. Never add a
1039
- retroactive exclusion merely to make attainment green.
1040
-
1041
- The generated verifier treats this document as the policy authority; managed
1042
- CloudWatch resources do not rewrite it.
1043
- `,
1044
- 'operations/reliability.json': (0, built_in_plan_shared_js_1.json)({
1045
- alarmRegistrations: alarms,
1046
- consoleIndependent: true,
1047
- deployedAlarmResources: deployedAlarmResources(name, sql),
1048
- diagnostic: {
1049
- metadataSources: [
1050
- 'alarm-state',
1051
- 'resource-metadata',
1052
- 'sanitized-signal',
1053
- ],
1054
- protectedSource: 'bounded-log-query',
1055
- runbookRef: 'runbook:reliability-diagnostic',
1056
- },
1057
- alertDelivery: {
1058
- confirmation: 'unsupported-until-independent-route-is-configured',
1059
- mode: 'diagnostic-only',
1060
- states: ['requested', 'confirmed', 'unsupported'],
1061
- },
1062
- dataLifecycleReferences: {
1063
- alarms: [
1064
- 'alarm:data-export-cleanup-deadline',
1065
- 'alarm:data-export-cleanup-failure',
1066
- 'alarm:data-export-cleanup-invocation-missing',
1067
- ],
1068
- status: 'requires-live-evidence',
1069
- },
1070
- incidentTemplateRef: 'operations:incident-template.json',
1071
- performanceReferences: {
1072
- alarms: [
1073
- 'alarm:cost-anomaly',
1074
- 'alarm:performance-load-cleanup-backlog',
1075
- 'alarm:performance-load-cleanup-deadline',
1076
- ],
1077
- capacityControls: [
1078
- 'control:api-lambda-concurrency',
1079
- 'control:async-worker-concurrency',
1080
- 'control:database-connections',
1081
- 'control:service-extension-concurrency',
1082
- ],
1083
- capacitySignals: [
1084
- 'adopter:service-saturation-percent',
1085
- 'database:connection-utilization-percent',
1086
- 'database:protected-async-backlog-utilization-percent',
1087
- 'runtime:nodejs-heap-utilization-percent',
1088
- ],
1089
- status: 'requires-adopter-values-and-live-evidence',
1090
- },
1091
- remediation: {
1092
- adapter: 'protected-async-recovery',
1093
- approvalRequired: true,
1094
- runbookRef: 'runbook:incident-remediation',
1095
- supportedApplyActions: ['redrive', 'replay'],
1096
- },
1097
- schemaVersion: 1,
1098
- slice: name,
1099
- sloRef: 'docs:reliability/slo.json',
1100
- runtimeSmoke: {
1101
- aggregateOwner: 'testing-evidence',
1102
- deployedResourceClass: 'testing-evidence-not-cloudwatch-alarm',
1103
- evidenceKind: 'testing-evidence-result',
1104
- metricOwner: 'not-provisioned-by-reliability',
1105
- reporter: 'testing-evidence-native-not-reliability-exercise-report',
1106
- target: 'smoke-deployed',
1107
- },
1108
- workloadCoverage: [
1109
- { kind: 'lambda-api', registration: 'api-fast-burn' },
1110
- { kind: 'function', registration: 'function-failure' },
1111
- { kind: 'next', registration: 'web-latency-fast-burn' },
1112
- {
1113
- kind: 'service',
1114
- registration: 'required-when-generated-by-ebk-workload-service-health',
1115
- },
1116
- {
1117
- kind: 'job',
1118
- registration: 'required-when-generated-by-ebk-workload-job-failure',
1119
- },
1120
- { kind: 'queue-dlq', registration: 'provider-queue-age' },
1121
- { kind: 'database', registration: 'database-capacity' },
1122
- {
1123
- kind: 'built-in-retention-job',
1124
- registration: 'retention-job-failure',
1125
- },
1126
- {
1127
- kind: 'built-in-data-export-cleanup',
1128
- registration: 'data-export-cleanup-failure',
1129
- },
1130
- {
1131
- kind: 'deployed-smoke',
1132
- registration: 'testing-evidence-aggregate',
1133
- },
1134
- {
1135
- kind: 'alert-delivery',
1136
- registration: 'alert-delivery-degraded',
1137
- },
1138
- ],
1139
- }),
1140
- 'testing/reliability-exercises.json': (0, built_in_plan_shared_js_1.json)({
1141
- exercises,
1142
- schemaVersion: 1,
1143
- slice: name,
1144
- }),
1145
- 'operations/incident-template.json': (0, built_in_plan_shared_js_1.json)({
1146
- affectedJourneyIds: ['api-critical-operation'],
1147
- declaredAt: reviewedAt,
1148
- followUpRefs: ['replace-with-owned-work-reference'],
1149
- id: `${name}-incident-template`,
1150
- impact: 'Replace with confirmed user or operator impact.',
1151
- roles: {
1152
- communicationsOwner: 'unassigned-human',
1153
- incidentCommander: 'unassigned-human',
1154
- scribe: 'unassigned',
1155
- technicalLead: 'unassigned-human',
1156
- },
1157
- severity: 'SEV-4',
1158
- slice: name,
1159
- state: 'declared',
1160
- timeline: [
1161
- {
1162
- actor: 'unassigned-human',
1163
- at: reviewedAt,
1164
- evidenceRefs: ['replace-with-sanitized-evidence-reference'],
1165
- message: 'Template only: confirm impact and explicitly declare the incident.',
1166
- type: 'decision',
1167
- },
1168
- ],
1169
- }),
1170
- 'reliability/contract.ts': `import {
1171
- validateReliabilityContract,
1172
- } from '@empire-builder-kit/runtime/reliability';
1173
- import declaration from '../docs/reliability/slo.json';
1174
-
1175
- export const Reliability = validateReliabilityContract(declaration);
1176
- `,
1177
- 'reliability/metrics.ts': `import {
1178
- createEmfMetricRecord,
1179
- createMetricEmitter,
1180
- createMetricRejectionReporter,
1181
- type BatchedMetricEmitter,
1182
- type EmfMetricObservation,
1183
- type MetricDimensions,
1184
- type MetricEmitter,
1185
- type MetricEmitterOptions,
1186
- type MetricOutcome,
1187
- } from '@empire-builder-kit/runtime/observability';
1188
- import {
1189
- reliabilityMetricDeclarations,
1190
- type ReliabilityMetricDeclaration,
1191
- } from './metric-declarations.js';
1192
-
1193
- export interface ReliabilityOperation {
1194
- component: string;
1195
- durationMilliseconds: number;
1196
- feature: string;
1197
- good?: boolean;
1198
- operation: string;
1199
- outcome: MetricOutcome;
1200
- }
1201
-
1202
- // Managed core declarations grow with generated callers on upgrade. Adopter
1203
- // declarations stay in the seeded extension file, never in request input.
1204
- const coreMetricDeclarations: readonly ReliabilityMetricDeclaration[] = [
1205
- { component: 'next-server', feature: 'web', operation: 'request' },
1206
- ];
1207
- const metricDeclarations: readonly ReliabilityMetricDeclaration[] = Object.freeze(
1208
- [...coreMetricDeclarations, ...reliabilityMetricDeclarations].map((entry) =>
1209
- Object.freeze({ ...entry }),
1210
- ),
1211
- );
1212
- // Deployment identity is fixed when the Lambda/Next module starts, not per request.
1213
- const reliabilityStage = process.env.EBK_STAGE ?? 'development';
1214
-
1215
- export function createReliabilityMetricEmitter(
1216
- options: Omit<MetricEmitterOptions, 'cardinalityPolicy'> = {},
1217
- ): BatchedMetricEmitter {
1218
- const values = (dimension: keyof ReliabilityMetricDeclaration) =>
1219
- [...new Set(metricDeclarations.map((entry) => entry[dimension]))];
1220
- const reportRejected = createMetricRejectionReporter(options.onRejected);
1221
- const emitter = createMetricEmitter({
1222
- ...options,
1223
- onRejected: reportRejected,
1224
- cardinalityPolicy: {
1225
- dimensions: {
1226
- component: values('component'),
1227
- feature: values('feature'),
1228
- operation: values('operation'),
1229
- slice: ['${name}'],
1230
- stage: [reliabilityStage],
1231
- },
1232
- metricNames: ['OperationValid', 'OperationGood', 'OperationDuration'],
1233
- },
1234
- });
1235
- // A declaration owns one tuple, not every Cartesian combination of its labels.
1236
- const tupleKey = (dimensions: MetricDimensions | undefined) => {
1237
- const labels = [dimensions?.component, dimensions?.feature, dimensions?.operation];
1238
- return labels.every((label) => typeof label === 'string')
1239
- ? JSON.stringify(labels.map((label) => label.trim()))
1240
- : undefined;
1241
- };
1242
- const declaredTuples = new Set(metricDeclarations.map((entry) =>
1243
- tupleKey({ ...entry, slice: '${name}', stage: reliabilityStage }),
1244
- ));
1245
- return {
1246
- reportRejected,
1247
- emit(input) {
1248
- if (!declaredTuples.has(tupleKey(input?.dimensions))) {
1249
- reportRejected('undeclared-tuple');
1250
- return undefined;
1251
- }
1252
- return emitter.emit(input);
1253
- },
1254
- emitBatch(input) {
1255
- if (!declaredTuples.has(tupleKey(input?.dimensions))) {
1256
- reportRejected('undeclared-tuple');
1257
- return undefined;
1258
- }
1259
- return emitter.emitBatch(input);
1260
- },
1261
- };
1262
- }
1263
-
1264
- // Invalid declarations fail closed during module initialization and prevent
1265
- // startup. After successful initialization, emission failures stay observational.
1266
- const defaultReliabilityMetricEmitter = createReliabilityMetricEmitter();
1267
-
1268
- export function recordReliabilityOperation(
1269
- input: ReliabilityOperation,
1270
- metrics: MetricEmitter = defaultReliabilityMetricEmitter,
1271
- ) {
1272
- const dimensions = {
1273
- component: input.component,
1274
- feature: input.feature,
1275
- operation: input.operation,
1276
- slice: '${name}',
1277
- stage: reliabilityStage,
1278
- };
1279
- const validObservation = {
1280
- metricName: 'OperationValid', unit: 'Count', value: 1,
1281
- } as const;
1282
- const goodObservation = {
1283
- metricName: 'OperationGood',
1284
- unit: 'Count',
1285
- value: (input.good ?? input.outcome === 'success') ? 1 : 0,
1286
- } as const;
1287
- const latencyObservation = Number.isFinite(input.durationMilliseconds)
1288
- ? {
1289
- metricName: 'OperationDuration',
1290
- unit: 'Milliseconds',
1291
- value: input.durationMilliseconds,
1292
- } as const
1293
- : undefined;
1294
- if (!latencyObservation) {
1295
- try {
1296
- const reportRejected = metrics.reportRejected ?? defaultReliabilityMetricEmitter.reportRejected;
1297
- reportRejected?.('invalid-observation');
1298
- } catch {
1299
- // Custom diagnostic adapters cannot turn completed work into a failed response.
1300
- }
1301
- }
1302
- const observations: readonly EmfMetricObservation[] = [
1303
- validObservation,
1304
- goodObservation,
1305
- ...(latencyObservation ? [latencyObservation] : []),
1306
- ];
1307
- if (metrics.emitBatch) {
1308
- const batch = metrics.emitBatch({ dimensions, metrics: observations });
1309
- // Keep the public per-metric result records while delivering one envelope.
1310
- const result = (observation: EmfMetricObservation | undefined) =>
1311
- batch && observation && createEmfMetricRecord({
1312
- ...observation,
1313
- dimensions,
1314
- now: () => new Date(batch._aws.Timestamp),
1315
- });
1316
- return {
1317
- good: result(goodObservation),
1318
- latency: result(latencyObservation),
1319
- valid: result(validObservation),
1320
- };
1321
- }
1322
- // Existing custom emit-only adapters retain one call per valid observation.
1323
- const valid = metrics.emit({ ...validObservation, dimensions });
1324
- const good = metrics.emit({ ...goodObservation, dimensions });
1325
- const latency = latencyObservation &&
1326
- metrics.emit({ ...latencyObservation, dimensions });
1327
- return { good, latency, valid };
1328
- }
1329
- `,
1330
- 'reliability/metric-declarations.ts': `import type {
1331
- MetricDimensions,
1332
- } from '@empire-builder-kit/runtime/observability';
1333
-
1334
- export type ReliabilityMetricDeclaration = Required<
1335
- Pick<MetricDimensions, 'component' | 'feature' | 'operation'>
1336
- >;
1337
-
1338
- // Seeded extension: declare finite deployment-owned labels for custom features.
1339
- // Never derive declarations from request, user, resource, or correlation IDs.
1340
- // Generated core declarations are added separately by the managed recorder.
1341
- export const reliabilityMetricDeclarations: readonly ReliabilityMetricDeclaration[] = [];
1342
- `,
1343
- 'infra/reliability.ts': `import {
1344
- createSloBurnAlarmPlan,
1345
- } from '@empire-builder-kit/runtime/reliability';
1346
- import { Reliability } from '../reliability/contract.js';
1347
-
1348
- export interface ReliabilityInfrastructureInput {
1349
- alertTopicArn: any;
1350
- alertTopicName: any;
1351
- apiId: any;
1352
- ${' databaseTableName: any;\n'}\
1353
- functionName: any;
1354
- providerQueueName: any;
1355
- }
1356
-
1357
- function alarmDescription(input: {
1358
- businessSymptom: string;
1359
- id: string;
1360
- runbook: string;
1361
- }) {
1362
- return JSON.stringify({
1363
- businessSymptom: input.businessSymptom,
1364
- id: input.id,
1365
- owner: '${ownership.owner}',
1366
- route: '${ownership.route}',
1367
- runbook: input.runbook,
1368
- schemaVersion: 1,
1369
- slice: '${name}',
1370
- });
1371
- }
1372
-
1373
- export function create${pascalName}Reliability(
1374
- input: ReliabilityInfrastructureInput,
1375
- ) {
1376
- const apiObjective = Reliability.objectives.find(
1377
- ({ id }) => id === 'api-availability',
1378
- );
1379
- const webObjective = Reliability.objectives.find(
1380
- ({ id }) => id === 'web-latency',
1381
- );
1382
- if (!apiObjective || !webObjective) {
1383
- throw new Error('Generated reliability objectives are incomplete.');
1384
- }
1385
- const apiBurn = createSloBurnAlarmPlan(apiObjective, {
1386
- bad: {
1387
- dimensions: { ApiId: input.apiId },
1388
- metricName: '5xx',
1389
- namespace: 'AWS/ApiGateway',
1390
- stat: 'Sum',
1391
- },
1392
- valid: {
1393
- dimensions: { ApiId: input.apiId },
1394
- metricName: 'Count',
1395
- namespace: 'AWS/ApiGateway',
1396
- stat: 'Sum',
1397
- },
1398
- });
1399
- const webDimensions = {
1400
- Component: 'next-server',
1401
- Feature: 'web',
1402
- Operation: 'request',
1403
- Slice: '${name}',
1404
- Stage: $app.stage,
1405
- };
1406
- const webBurn = createSloBurnAlarmPlan(webObjective, {
1407
- good: {
1408
- dimensions: webDimensions,
1409
- metricName: 'OperationGood',
1410
- namespace: 'EBK/${name}',
1411
- stat: 'Sum',
1412
- },
1413
- valid: {
1414
- dimensions: webDimensions,
1415
- metricName: 'OperationValid',
1416
- namespace: 'EBK/${name}',
1417
- stat: 'Sum',
1418
- },
1419
- });
1420
- const apiFastBurn = new aws.cloudwatch.MetricAlarm(
1421
- '${pascalName}ApiFastBurn',
1422
- {
1423
- alarmActions: [input.alertTopicArn],
1424
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'api-fast-burn', ' ')}),
1425
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1426
- datapointsToAlarm: 1,
1427
- evaluationPeriods: 1,
1428
- metricQueries: [...apiBurn.fast.metricQueries],
1429
- name: '${name}-' + $app.stage + '-api-fast-burn',
1430
- threshold: apiBurn.fast.burnThreshold,
1431
- treatMissingData: 'missing',
1432
- },
1433
- );
1434
- const apiSlowBurn = new aws.cloudwatch.MetricAlarm(
1435
- '${pascalName}ApiSlowBurn',
1436
- {
1437
- alarmActions: [input.alertTopicArn],
1438
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'api-slow-burn', ' ')}),
1439
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1440
- datapointsToAlarm: 1,
1441
- evaluationPeriods: 1,
1442
- metricQueries: [...apiBurn.slow.metricQueries],
1443
- name: '${name}-' + $app.stage + '-api-slow-burn',
1444
- threshold: apiBurn.slow.burnThreshold,
1445
- treatMissingData: 'missing',
1446
- },
1447
- );
1448
- const webLatency = new aws.cloudwatch.MetricAlarm(
1449
- '${pascalName}WebLatencyBurn',
1450
- {
1451
- alarmActions: [input.alertTopicArn],
1452
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'web-latency-fast-burn', ' ')}),
1453
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1454
- datapointsToAlarm: 1,
1455
- evaluationPeriods: 1,
1456
- metricQueries: [...webBurn.fast.metricQueries],
1457
- name: '${name}-' + $app.stage + '-web-latency-fast-burn',
1458
- threshold: webBurn.fast.burnThreshold,
1459
- treatMissingData: 'missing',
1460
- },
1461
- );
1462
- const webLatencySlow = new aws.cloudwatch.MetricAlarm(
1463
- '${pascalName}WebLatencySlowBurn',
1464
- {
1465
- alarmActions: [input.alertTopicArn],
1466
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'web-latency-slow-burn', ' ')}),
1467
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1468
- datapointsToAlarm: 1,
1469
- evaluationPeriods: 1,
1470
- metricQueries: [...webBurn.slow.metricQueries],
1471
- name: '${name}-' + $app.stage + '-web-latency-slow-burn',
1472
- threshold: webBurn.slow.burnThreshold,
1473
- treatMissingData: 'missing',
1474
- },
1475
- );
1476
- const providerDeadline = new aws.cloudwatch.MetricAlarm(
1477
- '${pascalName}ProviderDeadline',
1478
- {
1479
- alarmActions: [input.alertTopicArn],
1480
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'provider-queue-age', ' ')}),
1481
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1482
- dimensions: { QueueName: input.providerQueueName },
1483
- evaluationPeriods: 2,
1484
- metricName: 'ApproximateAgeOfOldestMessage',
1485
- name: '${name}-' + $app.stage + '-provider-deadline',
1486
- namespace: 'AWS/SQS',
1487
- period: 300,
1488
- statistic: 'Maximum',
1489
- threshold: 900,
1490
- treatMissingData: 'missing',
1491
- },
1492
- );
1493
- const databaseCapacity = new aws.cloudwatch.MetricAlarm(
1494
- '${pascalName}DatabaseCapacity',
1495
- {
1496
- alarmActions: [input.alertTopicArn],
1497
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'database-capacity', ' ')}),
1498
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1499
- ${` evaluationPeriods: 1,
1500
- name: '${name}-' + $app.stage + '-database-capacity',
1501
- threshold: 1,
1502
- treatMissingData: 'notBreaching',
1503
- // AWS publishes throttle-event metrics for the table and each index,
1504
- // unlike ThrottledRequests, which also requires an Operation dimension.
1505
- metricQueries: [
1506
- { id: 'total', expression: 'SUM(METRICS())', returnData: true },
1507
- ...['ReadThrottleEvents', 'WriteThrottleEvents'].flatMap((metricName, kind) =>
1508
- [undefined, 'PendingEvents'].map((index, scope) => ({
1509
- id: 'throttle' + kind + scope, returnData: false,
1510
- metric: { namespace: 'AWS/DynamoDB', metricName, period: 60, stat: 'Sum',
1511
- dimensions: { TableName: input.databaseTableName,
1512
- ...(index ? { GlobalSecondaryIndexName: index } : {}) },
1513
- },
1514
- })),
1515
- ),
1516
- ],
1517
- `}\
1518
- },
1519
- );
1520
- const functionFailure = new aws.cloudwatch.MetricAlarm(
1521
- '${pascalName}FunctionFailure',
1522
- {
1523
- alarmActions: [input.alertTopicArn],
1524
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'function-failure', ' ')}),
1525
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1526
- dimensions: { FunctionName: input.functionName },
1527
- evaluationPeriods: 1,
1528
- metricName: 'Errors',
1529
- name: '${name}-' + $app.stage + '-function-failure',
1530
- namespace: 'AWS/Lambda',
1531
- period: 60,
1532
- statistic: 'Sum',
1533
- threshold: 1,
1534
- treatMissingData: 'notBreaching',
1535
- },
1536
- );
1537
- const alertDelivery = new aws.cloudwatch.MetricAlarm(
1538
- '${pascalName}AlertDelivery',
1539
- {
1540
- alarmDescription: alarmDescription(${(0, built_in_plan_alarm_identity_js_1.renderSliceAlarmDescriptionInput)(name, 'alert-delivery-degraded', ' ')}),
1541
- comparisonOperator: 'GreaterThanOrEqualToThreshold',
1542
- dimensions: { TopicName: input.alertTopicName },
1543
- evaluationPeriods: 1,
1544
- metricName: 'NumberOfNotificationsFailed',
1545
- name: '${name}-' + $app.stage + '-alert-delivery-degraded',
1546
- namespace: 'AWS/SNS',
1547
- okActions: [],
1548
- period: 300,
1549
- statistic: 'Sum',
1550
- threshold: 1,
1551
- treatMissingData: 'notBreaching',
1552
- },
1553
- );
1554
- return {
1555
- alertDelivery,
1556
- apiFastBurn,
1557
- apiSlowBurn,
1558
- databaseCapacity,
1559
- functionFailure,
1560
- providerDeadline,
1561
- webLatency,
1562
- webLatencySlow,
1563
- };
1564
- }
1565
- `,
1566
- 'docs/runbooks/reliability-diagnostic.md': `# Reliability diagnostic
1567
-
1568
- The Standard Slice database-capacity alarm measures DynamoDB
1569
- ReadThrottleEvents and WriteThrottleEvents for its table and PendingEvents
1570
- index (60-second Sum, threshold 1, one evaluation, missing data notBreaching).
1571
- It does not measure Aurora ACUs, even when a user feature declares SQL.
1572
- During a seeded upgrade, reconcile only this database-capacity registration
1573
- against the generated infrastructure; preserve adopter-owned owners, routes
1574
- and other operational decisions. Then run the reliability verification target
1575
- with --deployed against the actual stage. A registry-only check cannot prove
1576
- that an AWS alarm was updated.
1577
-
1578
- The generated diagnostic adapter is defined for exactly three approval-free
1579
- sources: alarm state, sanitized SLO metric signals, and bounded ECS or Step
1580
- Functions resource metadata, but no supported producer currently exists for
1581
- its inputs. In a generated workspace \`reliability-diagnostic\` therefore fails
1582
- closed before any AWS read; do not cite it as an executed diagnostic. Its
1583
- definition follows. It executes read-only \`DescribeAlarms\`,
1584
- \`GetMetricData\`, \`DescribeServices\`, and \`DescribeExecution\` calls
1585
- against one exact target and immutable deployment binding. Dashboard, generic
1586
- health, cost, and runbook lookups are not claimed as executable diagnostic
1587
- sources. The adapter does not accept arbitrary metric expressions or resource
1588
- scans, read application log contents, or unmask data.
1589
-
1590
- Before an AWS read, the adapter requires a protected GitHub Actions context, a
1591
- \`.ebk/evidence/reliability/active-bindings.json\` index whose authority names
1592
- the \`Deployed smoke\` workflow, and matching
1593
- \`EBK_RELIABILITY_AUTHORIZED_*\` run values. Only the retired Deployed smoke and
1594
- Reliability read workflows produced these; the native Deploy workflow does not.
1595
- That index must name the current checked-out source commit and exact
1596
- repository. The adapter then recomputes the binding from the exact
1597
- deployed-smoke, active protected-release, and release-manifest artifact bytes.
1598
- The binding also carries the environment-reviewed alarm, API, ECS, and Step
1599
- Functions resource allowlist. A stale binding or substituted resource fails
1600
- before its service query.
1601
-
1602
- Sanitized metric capture is limited to six hours and produces
1603
- \`reliability-slo-diagnostic-sample\`. It reports the declared objective window
1604
- beside the sampled window but never claims that the sample proves the rolling
1605
- 28-day SLO. The report derives staging or production provenance from the active
1606
- binding; callers cannot label it.
1607
-
1608
- A bounded log query requires a human approval naming the approver, invoking
1609
- human, incident, reason, account, region, stage, Slice, exact log groups, query
1610
- class, time window, and expiry. The invoking human is the person whose session
1611
- runs the query; an agent may prepare the request and run the query inside that
1612
- human's session, and the approver must be a different human. Unmasking remains
1613
- a separate break-glass authority. The approved query window is at most one hour.
1614
- The script returns an authorization plan; the existing protected query runner
1615
- retains attributable evidence. Empty results never prove recovery.
1616
- `,
1617
- 'docs/runbooks/incident-remediation.md': `# Approval-gated incident remediation
1618
-
1619
- Use \`scripts/incident-remediation.mjs\` in report mode first. The report binds
1620
- one action, account, region, stage, Slice, preconditions, stop conditions,
1621
- verification, cleanup, adapter choice, and any adapter evidence through an
1622
- internally computed SHA-256 remediation-plan digest. That digest is distinct
1623
- from the async-recovery report digest consumed by redrive or replay.
1624
-
1625
- Apply requires an unexpired human approval bound to that exact report, action,
1626
- and target plus protected GitHub OIDC on the approved commit. The stable-v1
1627
- adapter supports bounded async redrive or replay through the generated
1628
- protected async-recovery path; its own resource, rate, idempotency, alarm,
1629
- cleanup, and evidence controls still apply. Other remediation paths remain
1630
- report-only until separately implemented. Stop when the active target or
1631
- approved report changes.
1632
- `,
1633
- 'docs/runbooks/api-recovery.md': `# API recovery
1634
-
1635
- Confirm customer impact, API validity classification, recent release and
1636
- configuration identity, database/dependency health, and correlated sanitized
1637
- signals. Prefer a verified roll-forward. A source revert must traverse the
1638
- normal develop-to-staging evidence path before protected production promotion.
1639
- Verify the critical API journey and data invariants before resolution.
1640
- `,
1641
- 'docs/runbooks/web-recovery.md': `# Web recovery
1642
-
1643
- Confirm the server-rendered route, deployed release, configuration digest,
1644
- origin, cache class, and dependency state. Compare cold and warm paths without
1645
- combining their populations. Verify headers, authentication, keyboard/focus,
1646
- responsive layout, reduced motion, and the user journey after recovery.
1647
- `,
1648
- 'docs/runbooks/alert-delivery.md': `# Alert delivery recovery
1649
-
1650
- The generated SNS delivery-failure alarm is diagnostic-only: it deliberately
1651
- has no action on the route whose failure it observes. Record delivery as
1652
- \`requested\` or \`unsupported\`; never promote it to \`confirmed\` without a
1653
- receipt captured from an independently configured provider or route. Do not
1654
- disable customer-impact alarms. Repair or select an approved independent route,
1655
- send one bounded proof, and retain its provider receipt before resolving.
1656
- `,
1657
- 'scripts/reliability-evidence-lib.mjs': `import { createHash } from 'node:crypto';
1658
- import { isBoundedSafeReference } from '@empire-builder-kit/runtime/safe-reference';
1659
- import {
1660
- lstatSync,
1661
- mkdirSync,
1662
- readFileSync,
1663
- writeFileSync,
1664
- } from 'node:fs';
1665
- import { relative, resolve, sep } from 'node:path';
1666
-
1667
- export const MAX_RELIABILITY_ARTIFACT_BYTES = 64 * 1024;
1668
- const DIGEST = /^[a-f0-9]{64}$/;
1669
-
1670
- export function sha256(bytes) {
1671
- return createHash('sha256').update(bytes).digest('hex');
1672
- }
1673
-
1674
- export function exactKeys(value, allowed, label) {
1675
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
1676
- throw new Error(label + ' must be an object.');
1677
- }
1678
- const unexpected = Object.keys(value).filter((key) => !allowed.includes(key));
1679
- if (unexpected.length > 0) {
1680
- throw new Error(label + ' contains unsupported fields: ' + unexpected.sort().join(', ') + '.');
1681
- }
1682
- return value;
1683
- }
1684
-
1685
- export function safeToken(value, label, maximum = 512) {
1686
- if (
1687
- typeof value !== 'string' ||
1688
- value.length < 1 ||
1689
- value.length > maximum ||
1690
- !isBoundedSafeReference(value, 'repository-evidence') ||
1691
- value.includes('..') ||
1692
- value.includes('\\\\')
1693
- ) {
1694
- throw new Error(label + ' is not a bounded sanitized token.');
1695
- }
1696
- return value;
1697
- }
1698
-
1699
- export function digest(value, label) {
1700
- if (typeof value !== 'string' || !DIGEST.test(value)) {
1701
- throw new Error(label + ' must be an exact SHA-256 digest.');
1702
- }
1703
- return value;
1704
- }
1705
-
1706
- export function utc(value, label) {
1707
- if (
1708
- typeof value !== 'string' ||
1709
- value.length > 32 ||
1710
- !value.endsWith('Z') ||
1711
- !Number.isFinite(Date.parse(value))
1712
- ) {
1713
- throw new Error(label + ' must be a bounded UTC timestamp.');
1714
- }
1715
- return value;
1716
- }
1717
-
1718
- export function readBoundedJson(path, label) {
1719
- const bytes = readFileSync(path);
1720
- if (bytes.length === 0 || bytes.length > MAX_RELIABILITY_ARTIFACT_BYTES) {
1721
- throw new Error(label + ' exceeds the reliability artifact size bound.');
1722
- }
1723
- let value;
1724
- try {
1725
- value = JSON.parse(bytes.toString('utf8'));
1726
- } catch {
1727
- throw new Error(label + ' is not valid JSON.');
1728
- }
1729
- return { bytes, value };
1730
- }
1731
-
1732
- export function binding(value, label) {
1733
- const record = exactKeys(
1734
- value,
1735
- [
1736
- 'candidateDigest',
1737
- 'configurationDigest',
1738
- 'deploymentDigest',
1739
- 'releaseDigest',
1740
- 'sourceCommit',
1741
- 'workload',
1742
- ],
1743
- label,
1744
- );
1745
- const sourceCommit = safeToken(
1746
- record.sourceCommit,
1747
- label + '.sourceCommit',
1748
- 40,
1749
- );
1750
- if (!/^[a-f0-9]{40}$/.test(sourceCommit)) {
1751
- throw new Error(label + '.sourceCommit must be an exact git commit.');
1752
- }
1753
- return {
1754
- candidateDigest: digest(record.candidateDigest, label + '.candidateDigest'),
1755
- configurationDigest: digest(
1756
- record.configurationDigest,
1757
- label + '.configurationDigest',
1758
- ),
1759
- deploymentDigest: digest(
1760
- record.deploymentDigest,
1761
- label + '.deploymentDigest',
1762
- ),
1763
- releaseDigest: digest(record.releaseDigest, label + '.releaseDigest'),
1764
- sourceCommit,
1765
- workload: safeToken(record.workload, label + '.workload', 128),
1766
- };
1767
- }
1768
-
1769
- export function sameBinding(left, right) {
1770
- return (
1771
- left.candidateDigest === right.candidateDigest &&
1772
- left.configurationDigest === right.configurationDigest &&
1773
- left.deploymentDigest === right.deploymentDigest &&
1774
- left.releaseDigest === right.releaseDigest &&
1775
- left.sourceCommit === right.sourceCommit &&
1776
- left.workload === right.workload
1777
- );
1778
- }
1779
-
1780
- function artifactReferencePath(value, label) {
1781
- const path = value;
1782
- if (
1783
- typeof path !== 'string' ||
1784
- path.length < 1 ||
1785
- path.length > 1024 ||
1786
- !/^(?:[A-Za-z0-9._-]+\\/)*[A-Za-z0-9._-]+$/.test(path) ||
1787
- path.startsWith('/') ||
1788
- path.split('/').includes('..')
1789
- ) {
1790
- throw new Error(label + ' must remain inside the Slice package.');
1791
- }
1792
- const root = resolve(process.cwd());
1793
- const absolute = resolve(root, path);
1794
- const within = relative(root, absolute);
1795
- if (within.startsWith('..' + sep) || within === '..') {
1796
- throw new Error(label + ' escapes the Slice package.');
1797
- }
1798
- return path;
1799
- }
1800
-
1801
- export function artifactReference(value, label) {
1802
- const record = exactKeys(value, ['digest', 'path'], label);
1803
- const expectedDigest = digest(record.digest, label + '.digest');
1804
- const path = artifactReferencePath(record.path, label + '.path');
1805
- const absolute = resolve(process.cwd(), path);
1806
- const artifact = readBoundedJson(absolute, label);
1807
- const metadata = lstatSync(absolute);
1808
- if (!metadata.isFile() || metadata.isSymbolicLink()) {
1809
- throw new Error(label + ' must be a regular non-symlink artifact.');
1810
- }
1811
- if (sha256(artifact.bytes) !== expectedDigest) {
1812
- throw new Error(label + ' digest does not match its exact artifact bytes.');
1813
- }
1814
- return { ...artifact, digest: expectedDigest, path };
1815
- }
1816
-
1817
- function reliabilityTarget(value, label) {
1818
- const target = exactKeys(
1819
- value,
1820
- ['account', 'region', 'slice', 'stage'],
1821
- label,
1822
- );
1823
- const account = safeToken(target.account, label + '.account', 12);
1824
- if (!/^\\d{12}$/.test(account)) {
1825
- throw new Error(label + '.account must be an exact AWS account ID.');
1826
- }
1827
- const stage = safeToken(target.stage, label + '.stage', 16);
1828
- if (!['staging', 'production'].includes(stage)) {
1829
- throw new Error(label + '.stage must be a protected stage.');
1830
- }
1831
- const slice = safeToken(target.slice, label + '.slice', 128);
1832
- if (slice !== '${name}') {
1833
- throw new Error(label + '.slice escaped the generated Slice.');
1834
- }
1835
- const region = safeToken(target.region, label + '.region', 64);
1836
- if (!/^[a-z]{2}(?:-[a-z]+)+-\\d$/.test(region)) {
1837
- throw new Error(label + '.region must be an exact AWS Region.');
1838
- }
1839
- return {
1840
- account,
1841
- region,
1842
- slice,
1843
- stage,
1844
- };
1845
- }
1846
-
1847
- export function awsPartition(region) {
1848
- if (region.startsWith('cn-')) return 'aws-cn';
1849
- if (region.startsWith('us-gov-')) return 'aws-us-gov';
1850
- if (region.startsWith('us-isob-')) return 'aws-iso-b';
1851
- if (region.startsWith('us-isoe-')) return 'aws-iso-e';
1852
- if (region.startsWith('us-isof-')) return 'aws-iso-f';
1853
- if (region.startsWith('us-iso-')) return 'aws-iso';
1854
- if (region.startsWith('eusc-')) return 'aws-eusc';
1855
- return 'aws';
1856
- }
1857
-
1858
- function reliabilityResources(value, target, label) {
1859
- const resources = exactKeys(
1860
- value,
1861
- ['alarmNames', 'apiId', 'ecsServices', 'stateMachineArns'],
1862
- label,
1863
- );
1864
- if (
1865
- !Array.isArray(resources.alarmNames) ||
1866
- resources.alarmNames.length < 1 ||
1867
- resources.alarmNames.length > 100 ||
1868
- new Set(resources.alarmNames).size !== resources.alarmNames.length
1869
- ) {
1870
- throw new Error(label + '.alarmNames must contain exact unique alarms.');
1871
- }
1872
- const alarmNames = resources.alarmNames
1873
- .map((value, index) =>
1874
- safeToken(value, label + '.alarmNames[' + index + ']', 255),
1875
- )
1876
- .sort();
1877
- if (
1878
- alarmNames.some(
1879
- (value) => !value.startsWith(target.slice + '-' + target.stage + '-'),
1880
- )
1881
- ) {
1882
- throw new Error(label + '.alarmNames escaped the exact Slice and stage.');
1883
- }
1884
- const apiId = safeToken(resources.apiId, label + '.apiId', 128);
1885
- if (!/^[a-z0-9]{1,128}$/.test(apiId)) {
1886
- throw new Error(label + '.apiId must be one exact API Gateway ID.');
1887
- }
1888
- if (
1889
- !Array.isArray(resources.ecsServices) ||
1890
- resources.ecsServices.length > 8
1891
- ) {
1892
- throw new Error(label + '.ecsServices exceeds its eight-cluster bound.');
1893
- }
1894
- const ecsServices = resources.ecsServices
1895
- .map((value, index) => {
1896
- const entry = exactKeys(
1897
- value,
1898
- ['cluster', 'services'],
1899
- label + '.ecsServices[' + index + ']',
1900
- );
1901
- const cluster = safeToken(
1902
- entry.cluster,
1903
- label + '.ecsServices[' + index + '].cluster',
1904
- 512,
1905
- );
1906
- if (
1907
- !Array.isArray(entry.services) ||
1908
- entry.services.length < 1 ||
1909
- entry.services.length > 10 ||
1910
- new Set(entry.services).size !== entry.services.length
1911
- ) {
1912
- throw new Error(
1913
- label + '.ecsServices[' + index + '] has invalid services.',
1914
- );
1915
- }
1916
- const services = entry.services
1917
- .map((service, serviceIndex) =>
1918
- safeToken(
1919
- service,
1920
- label +
1921
- '.ecsServices[' +
1922
- index +
1923
- '].services[' +
1924
- serviceIndex +
1925
- ']',
1926
- 255,
1927
- ),
1928
- )
1929
- .sort();
1930
- const clusterArnPrefix =
1931
- 'arn:' +
1932
- awsPartition(target.region) +
1933
- ':ecs:' +
1934
- target.region +
1935
- ':' +
1936
- target.account +
1937
- ':cluster/';
1938
- if (
1939
- cluster.startsWith('arn:') &&
1940
- !cluster.startsWith(clusterArnPrefix)
1941
- ) {
1942
- throw new Error(
1943
- label + '.ecsServices[' + index + '] escaped the exact target.',
1944
- );
1945
- }
1946
- return { cluster, services };
1947
- })
1948
- .sort((left, right) =>
1949
- left.cluster < right.cluster
1950
- ? -1
1951
- : left.cluster > right.cluster
1952
- ? 1
1953
- : 0,
1954
- );
1955
- if (
1956
- new Set(ecsServices.map(({ cluster }) => cluster)).size !==
1957
- ecsServices.length
1958
- ) {
1959
- throw new Error(label + '.ecsServices repeats an exact cluster.');
1960
- }
1961
- if (
1962
- !Array.isArray(resources.stateMachineArns) ||
1963
- resources.stateMachineArns.length > 8 ||
1964
- new Set(resources.stateMachineArns).size !==
1965
- resources.stateMachineArns.length
1966
- ) {
1967
- throw new Error(
1968
- label + '.stateMachineArns exceeds its exact unique bound.',
1969
- );
1970
- }
1971
- const stateMachinePrefix =
1972
- 'arn:' +
1973
- awsPartition(target.region) +
1974
- ':states:' +
1975
- target.region +
1976
- ':' +
1977
- target.account +
1978
- ':stateMachine:';
1979
- const stateMachineArns = resources.stateMachineArns
1980
- .map((value, index) =>
1981
- safeToken(value, label + '.stateMachineArns[' + index + ']', 512),
1982
- )
1983
- .sort();
1984
- if (
1985
- stateMachineArns.some(
1986
- (value) =>
1987
- !value.startsWith(stateMachinePrefix) ||
1988
- value.length === stateMachinePrefix.length,
1989
- )
1990
- ) {
1991
- throw new Error(label + '.stateMachineArns escaped the exact target.');
1992
- }
1993
- return {
1994
- alarmNames,
1995
- apiId,
1996
- ecsServices,
1997
- stateMachineArns,
1998
- };
1999
- }
2000
-
2001
- export function authorizedExecutionArn(resources, executionArn) {
2002
- return resources.stateMachineArns.some((stateMachineArn) => {
2003
- const separator = ':stateMachine:';
2004
- const position = stateMachineArn.indexOf(separator);
2005
- if (position < 0) return false;
2006
- const executionPrefix =
2007
- stateMachineArn.slice(0, position) +
2008
- ':execution:' +
2009
- stateMachineArn.slice(position + separator.length) +
2010
- ':';
2011
- return executionArn.startsWith(executionPrefix);
2012
- });
2013
- }
2014
-
2015
- function protectedDeploymentSource(reference, target, expectedSmoke) {
2016
- const deploymentReference = artifactReference(
2017
- reference,
2018
- 'sources.deployment',
2019
- );
2020
- const deployment = exactKeys(
2021
- deploymentReference.value,
2022
- [
2023
- 'deployment',
2024
- 'kind',
2025
- 'project',
2026
- 'resources',
2027
- 'schemaVersion',
2028
- 'smoke',
2029
- 'sourceCommit',
2030
- 'stage',
2031
- 'trigger',
2032
- ],
2033
- 'Protected deployment binding',
2034
- );
2035
- const identity = exactKeys(
2036
- deployment.deployment,
2037
- [
2038
- 'conclusion',
2039
- 'event',
2040
- 'headBranch',
2041
- 'headSha',
2042
- 'runAttempt',
2043
- 'runId',
2044
- 'workflow',
2045
- ],
2046
- 'Protected deployment identity',
2047
- );
2048
- const smoke = exactKeys(
2049
- deployment.smoke,
2050
- ['runAttempt', 'runId', 'workflow'],
2051
- 'Protected smoke identity',
2052
- );
2053
- const sourceCommit = safeToken(
2054
- deployment.sourceCommit,
2055
- 'Protected deployment sourceCommit',
2056
- 40,
2057
- );
2058
- const expectedBranch = target.stage === 'production' ? 'main' : 'develop';
2059
- if (
2060
- deployment.kind !== 'ebk-deployed-smoke-binding' ||
2061
- deployment.schemaVersion !== 1 ||
2062
- deployment.project !== '${name}' ||
2063
- deployment.stage !== target.stage ||
2064
- deployment.trigger !== 'deployment' ||
2065
- identity.conclusion !== 'success' ||
2066
- !['push', 'workflow_dispatch'].includes(identity.event) ||
2067
- identity.headBranch !== expectedBranch ||
2068
- identity.headSha !== sourceCommit ||
2069
- identity.workflow !== 'Deploy' ||
2070
- smoke.workflow !== 'Deployed smoke' ||
2071
- String(smoke.runId) !== expectedSmoke.runId ||
2072
- String(smoke.runAttempt) !== expectedSmoke.runAttempt ||
2073
- !/^\\d+$/.test(String(identity.runId ?? '')) ||
2074
- !/^\\d+$/.test(String(identity.runAttempt ?? '')) ||
2075
- !/^[a-f0-9]{40}$/.test(sourceCommit)
2076
- ) {
2077
- throw new Error(
2078
- 'Protected deployment source does not prove the active Slice deployment.',
2079
- );
2080
- }
2081
- return {
2082
- reference: deploymentReference,
2083
- resources: reliabilityResources(
2084
- deployment.resources,
2085
- target,
2086
- 'Protected deployment resources',
2087
- ),
2088
- runAttempt: String(identity.runAttempt),
2089
- runId: String(identity.runId),
2090
- sourceCommit,
2091
- };
2092
- }
2093
-
2094
- function protectedReleaseSource(reference, target, deployment) {
2095
- const releaseReference = artifactReference(
2096
- reference,
2097
- 'sources.release',
2098
- );
2099
- const release = exactKeys(
2100
- releaseReference.value,
2101
- [
2102
- 'candidateDigest',
2103
- 'deploymentCommit',
2104
- 'kind',
2105
- 'manifestDigest',
2106
- 'releaseId',
2107
- 'releaseMaterialDigest',
2108
- 'releaseSourceCommit',
2109
- 'runAttempt',
2110
- 'runId',
2111
- 'schemaVersion',
2112
- 'stage',
2113
- 'workflow',
2114
- ],
2115
- 'Active protected release',
2116
- );
2117
- const releaseSourceCommit = safeToken(
2118
- release.releaseSourceCommit,
2119
- 'Active protected release.releaseSourceCommit',
2120
- 40,
2121
- );
2122
- if (
2123
- release.kind !== 'ebk-active-protected-release-binding' ||
2124
- release.schemaVersion !== 1 ||
2125
- release.stage !== target.stage ||
2126
- release.deploymentCommit !== deployment.sourceCommit ||
2127
- String(release.runId) !== deployment.runId ||
2128
- String(release.runAttempt) !== deployment.runAttempt ||
2129
- release.workflow !== 'Deploy' ||
2130
- !/^[a-f0-9]{40}$/.test(releaseSourceCommit)
2131
- ) {
2132
- throw new Error(
2133
- 'Active release does not match the protected deployment identity.',
2134
- );
2135
- }
2136
- return {
2137
- candidateDigest: digest(
2138
- release.candidateDigest,
2139
- 'Active protected release.candidateDigest',
2140
- ),
2141
- manifestDigest: digest(
2142
- release.manifestDigest,
2143
- 'Active protected release.manifestDigest',
2144
- ),
2145
- reference: releaseReference,
2146
- releaseMaterialDigest: digest(
2147
- release.releaseMaterialDigest,
2148
- 'Active protected release.releaseMaterialDigest',
2149
- ),
2150
- releaseSourceCommit,
2151
- };
2152
- }
2153
-
2154
- function releaseManifestSource(reference, target, sourceCommit) {
2155
- const manifestReference = artifactReference(
2156
- reference,
2157
- 'sources.manifest',
2158
- );
2159
- const manifest = exactKeys(
2160
- manifestReference.value,
2161
- [
2162
- 'artifacts',
2163
- 'blueprints',
2164
- 'build',
2165
- 'builtAt',
2166
- 'configuration',
2167
- 'contracts',
2168
- 'controls',
2169
- 'frameworkCandidate',
2170
- 'infrastructure',
2171
- 'initialLifecycle',
2172
- 'kind',
2173
- 'materialDigest',
2174
- 'migrations',
2175
- 'packageLockDigest',
2176
- 'projects',
2177
- 'releaseId',
2178
- 'requiredTests',
2179
- 'schemaVersion',
2180
- 'secrets',
2181
- 'source',
2182
- 'supplyChain',
2183
- 'toolchain',
2184
- ],
2185
- 'Release manifest',
2186
- );
2187
- const source = exactKeys(
2188
- manifest.source,
2189
- ['commit', 'repository', 'treeDigest'],
2190
- 'Release manifest source',
2191
- );
2192
- const infrastructure = exactKeys(
2193
- manifest.infrastructure,
2194
- [
2195
- 'aggregateRisk',
2196
- 'configurationMetadataDigest',
2197
- 'materialDigest',
2198
- 'policyProfileDigest',
2199
- 'riskClasses',
2200
- 'stage',
2201
- 'tool',
2202
- ],
2203
- 'Release manifest infrastructure',
2204
- );
2205
- if (
2206
- manifest.kind !== 'ebk-release-manifest' ||
2207
- manifest.schemaVersion !== 1 ||
2208
- source.commit !== sourceCommit ||
2209
- infrastructure.stage !== target.stage ||
2210
- !Array.isArray(manifest.projects) ||
2211
- !manifest.projects.includes('${name}') ||
2212
- !Array.isArray(manifest.configuration)
2213
- ) {
2214
- throw new Error(
2215
- 'Release manifest does not match the protected deployment source.',
2216
- );
2217
- }
2218
- digest(manifest.materialDigest, 'Release manifest.materialDigest');
2219
- const configuration = manifest.configuration.filter(
2220
- (entry) => entry?.stage === target.stage,
2221
- );
2222
- if (configuration.length !== 1) {
2223
- throw new Error(
2224
- 'Release manifest must contain one exact protected-stage configuration.',
2225
- );
2226
- }
2227
- const configured = exactKeys(
2228
- configuration[0],
2229
- ['digest', 'stage'],
2230
- 'Release manifest configuration',
2231
- );
2232
- return {
2233
- configurationDigest: digest(
2234
- configured.digest,
2235
- 'Release manifest configuration.digest',
2236
- ),
2237
- reference: manifestReference,
2238
- };
2239
- }
2240
-
2241
- export function createReliabilityDeploymentBinding(
2242
- input,
2243
- expectedTarget,
2244
- expectedSmoke,
2245
- ) {
2246
- const request = exactKeys(
2247
- input,
2248
- ['schemaVersion', 'sources', 'workload'],
2249
- 'Reliability deployment binding input',
2250
- );
2251
- if (request.schemaVersion !== 1) {
2252
- throw new Error('Reliability deployment binding input is incompatible.');
2253
- }
2254
- const target = reliabilityTarget(expectedTarget, 'target');
2255
- const sources = exactKeys(
2256
- request.sources,
2257
- ['deployment', 'manifest', 'release'],
2258
- 'Reliability deployment sources',
2259
- );
2260
- const smoke = exactKeys(
2261
- expectedSmoke,
2262
- ['runAttempt', 'runId'],
2263
- 'expectedSmoke',
2264
- );
2265
- for (const [name, value] of Object.entries(smoke)) {
2266
- if (!/^\\d+$/.test(String(value ?? ''))) {
2267
- throw new Error('expectedSmoke.' + name + ' must be an exact run number.');
2268
- }
2269
- }
2270
- const deployment = protectedDeploymentSource(sources.deployment, target, {
2271
- runAttempt: String(smoke.runAttempt),
2272
- runId: String(smoke.runId),
2273
- });
2274
- const release = protectedReleaseSource(
2275
- sources.release,
2276
- target,
2277
- deployment,
2278
- );
2279
- const manifest = releaseManifestSource(
2280
- sources.manifest,
2281
- target,
2282
- release.releaseSourceCommit,
2283
- );
2284
- if (
2285
- release.manifestDigest !== manifest.reference.digest ||
2286
- release.releaseMaterialDigest !==
2287
- manifest.reference.value.materialDigest
2288
- ) {
2289
- throw new Error(
2290
- 'Active release does not bind the exact release manifest bytes.',
2291
- );
2292
- }
2293
- return {
2294
- binding: {
2295
- candidateDigest: release.candidateDigest,
2296
- configurationDigest: manifest.configurationDigest,
2297
- deploymentDigest: deployment.reference.digest,
2298
- releaseDigest: manifest.reference.digest,
2299
- sourceCommit: release.releaseSourceCommit,
2300
- workload: safeToken(request.workload, 'workload', 128),
2301
- },
2302
- kind: 'reliability-active-deployment-binding',
2303
- resources: deployment.resources,
2304
- schemaVersion: 1,
2305
- slice: '${name}',
2306
- smoke: {
2307
- runAttempt: String(smoke.runAttempt),
2308
- runId: String(smoke.runId),
2309
- },
2310
- sources: {
2311
- deployment: {
2312
- digest: deployment.reference.digest,
2313
- path: deployment.reference.path,
2314
- },
2315
- manifest: {
2316
- digest: manifest.reference.digest,
2317
- path: manifest.reference.path,
2318
- },
2319
- release: {
2320
- digest: release.reference.digest,
2321
- path: release.reference.path,
2322
- },
2323
- },
2324
- target,
2325
- };
2326
- }
2327
-
2328
- export function activeDeploymentBinding(reference, label) {
2329
- if (
2330
- process.env.GITHUB_ACTIONS !== 'true' ||
2331
- process.env.GITHUB_REF_PROTECTED !== 'true'
2332
- ) {
2333
- throw new Error(
2334
- 'AWS reliability access requires one protected GitHub Actions context.',
2335
- );
2336
- }
2337
- const requested = exactKeys(reference, ['digest', 'path'], label);
2338
- const indexPath = '.ebk/evidence/reliability/active-bindings.json';
2339
- const indexAbsolute = resolve(process.cwd(), indexPath);
2340
- const indexArtifact = readBoundedJson(
2341
- indexAbsolute,
2342
- 'Protected reliability binding index',
2343
- );
2344
- const indexMetadata = lstatSync(indexAbsolute);
2345
- if (!indexMetadata.isFile() || indexMetadata.isSymbolicLink()) {
2346
- throw new Error(
2347
- 'Protected reliability binding index must be a regular non-symlink artifact.',
2348
- );
2349
- }
2350
- const index = exactKeys(
2351
- indexArtifact.value,
2352
- [
2353
- 'authority',
2354
- 'bindings',
2355
- 'kind',
2356
- 'schemaVersion',
2357
- 'slice',
2358
- 'stage',
2359
- 'target',
2360
- ],
2361
- 'Protected reliability binding index',
2362
- );
2363
- const authority = exactKeys(
2364
- index.authority,
2365
- [
2366
- 'repository',
2367
- 'runAttempt',
2368
- 'runId',
2369
- 'sourceCommit',
2370
- 'workflow',
2371
- ],
2372
- 'Protected reliability binding authority',
2373
- );
2374
- const sourceCommit = safeToken(
2375
- authority.sourceCommit,
2376
- 'Protected reliability binding authority.sourceCommit',
2377
- 40,
2378
- );
2379
- const repository = safeToken(
2380
- authority.repository,
2381
- 'Protected reliability binding authority.repository',
2382
- 256,
2383
- );
2384
- if (
2385
- index.kind !== 'reliability-active-binding-index' ||
2386
- index.schemaVersion !== 1 ||
2387
- index.slice !== '${name}' ||
2388
- !['staging', 'production'].includes(index.stage) ||
2389
- authority.workflow !== 'Deployed smoke' ||
2390
- !/^\\d+$/.test(String(authority.runId ?? '')) ||
2391
- !/^\\d+$/.test(String(authority.runAttempt ?? '')) ||
2392
- !/^[a-f0-9]{40}$/.test(sourceCommit) ||
2393
- !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/.test(repository) ||
2394
- process.env.EBK_RELIABILITY_AUTHORIZED_SOURCE_COMMIT !== sourceCommit ||
2395
- process.env.EBK_RELIABILITY_AUTHORIZED_SMOKE_RUN_ID !==
2396
- String(authority.runId) ||
2397
- process.env.EBK_RELIABILITY_AUTHORIZED_SMOKE_RUN_ATTEMPT !==
2398
- String(authority.runAttempt) ||
2399
- process.env.GITHUB_REPOSITORY !== repository
2400
- ) {
2401
- throw new Error(
2402
- 'Protected reliability binding index is stale or lacks current workflow authority.',
2403
- );
2404
- }
2405
- const indexTarget = reliabilityTarget(
2406
- {
2407
- ...index.target,
2408
- slice: index.slice,
2409
- stage: index.stage,
2410
- },
2411
- 'Protected reliability binding index target',
2412
- );
2413
- if (
2414
- !Array.isArray(index.bindings) ||
2415
- index.bindings.length < 1 ||
2416
- index.bindings.length > 128
2417
- ) {
2418
- throw new Error(
2419
- 'Protected reliability binding index has invalid workload coverage.',
2420
- );
2421
- }
2422
- const indexedBindings = index.bindings.map((value, entryIndex) => {
2423
- const entry = exactKeys(
2424
- value,
2425
- ['digest', 'path', 'workload'],
2426
- 'Protected reliability binding index.bindings[' +
2427
- entryIndex +
2428
- ']',
2429
- );
2430
- return {
2431
- digest: digest(
2432
- entry.digest,
2433
- 'Protected reliability binding index.bindings.digest',
2434
- ),
2435
- path: artifactReferencePath(
2436
- entry.path,
2437
- 'Protected reliability binding index.bindings.path',
2438
- ),
2439
- workload: safeToken(
2440
- entry.workload,
2441
- 'Protected reliability binding index.bindings.workload',
2442
- 128,
2443
- ),
2444
- };
2445
- });
2446
- if (
2447
- new Set(
2448
- indexedBindings.map(
2449
- ({ digest: artifactDigest, path }) => artifactDigest + ':' + path,
2450
- ),
2451
- ).size !== indexedBindings.length ||
2452
- new Set(indexedBindings.map(({ workload }) => workload)).size !==
2453
- indexedBindings.length
2454
- ) {
2455
- throw new Error(
2456
- 'Protected reliability binding index contains ambiguous bindings.',
2457
- );
2458
- }
2459
- const indexed = indexedBindings.filter(
2460
- ({ digest: artifactDigest, path }) =>
2461
- artifactDigest === requested.digest && path === requested.path,
2462
- );
2463
- if (indexed.length !== 1) {
2464
- throw new Error(
2465
- 'Requested reliability binding is not selected by the protected current index.',
2466
- );
2467
- }
2468
- const active = artifactReference(requested, label);
2469
- const document = exactKeys(
2470
- active.value,
2471
- [
2472
- 'binding',
2473
- 'kind',
2474
- 'resources',
2475
- 'schemaVersion',
2476
- 'slice',
2477
- 'smoke',
2478
- 'sources',
2479
- 'target',
2480
- ],
2481
- 'Active reliability deployment binding',
2482
- );
2483
- const target = reliabilityTarget(
2484
- document.target,
2485
- 'Active reliability deployment binding target',
2486
- );
2487
- const capturedBinding = binding(
2488
- document.binding,
2489
- 'Active reliability deployment binding.binding',
2490
- );
2491
- const expected = createReliabilityDeploymentBinding(
2492
- {
2493
- schemaVersion: 1,
2494
- sources: document.sources,
2495
- workload: capturedBinding.workload,
2496
- },
2497
- target,
2498
- document.smoke,
2499
- );
2500
- if (
2501
- document.kind !== expected.kind ||
2502
- document.schemaVersion !== 1 ||
2503
- document.slice !== '${name}' ||
2504
- capturedBinding.sourceCommit !== sourceCommit ||
2505
- capturedBinding.workload !== indexed[0].workload ||
2506
- target.account !== indexTarget.account ||
2507
- target.region !== indexTarget.region ||
2508
- target.stage !== indexTarget.stage ||
2509
- JSON.stringify(document) !== JSON.stringify(expected)
2510
- ) {
2511
- throw new Error(
2512
- 'Active reliability deployment binding is stale or was substituted.',
2513
- );
2514
- }
2515
- return {
2516
- binding: capturedBinding,
2517
- authorityDigest: sha256(indexArtifact.bytes),
2518
- digest: active.digest,
2519
- document,
2520
- path: active.path,
2521
- resources: reliabilityResources(
2522
- document.resources,
2523
- target,
2524
- 'Active reliability deployment binding.resources',
2525
- ),
2526
- target,
2527
- };
2528
- }
2529
-
2530
- export function writeImmutableArtifact(directory, value) {
2531
- const bytes = Buffer.from(JSON.stringify(value, null, 2) + '\\n');
2532
- if (bytes.length > MAX_RELIABILITY_ARTIFACT_BYTES) {
2533
- throw new Error('Reliability artifact exceeds its output size bound.');
2534
- }
2535
- const artifactDigest = sha256(bytes);
2536
- const relativePath = directory + '/' + artifactDigest + '.json';
2537
- const absolute = resolve(process.cwd(), relativePath);
2538
- mkdirSync(resolve(process.cwd(), directory), {
2539
- mode: 0o700,
2540
- recursive: true,
2541
- });
2542
- try {
2543
- writeFileSync(absolute, bytes, { flag: 'wx', mode: 0o600 });
2544
- } catch (error) {
2545
- if (!readFileSync(absolute).equals(bytes)) throw error;
2546
- }
2547
- return { digest: artifactDigest, path: relativePath };
2548
- }
2549
- `,
2550
- 'scripts/create-reliability-deployment-binding.mjs': `import {
2551
- createReliabilityDeploymentBinding,
2552
- exactKeys,
2553
- readBoundedJson,
2554
- writeImmutableArtifact,
2555
- } from './reliability-evidence-lib.mjs';
2556
-
2557
- const inputPath =
2558
- process.env.EBK_RELIABILITY_BINDING_INPUT_PATH?.trim();
2559
- if (!inputPath) {
2560
- throw new Error('EBK_RELIABILITY_BINDING_INPUT_PATH is required.');
2561
- }
2562
- const required = (name, pattern) => {
2563
- const value = process.env[name]?.trim();
2564
- if (!value || !pattern.test(value)) {
2565
- throw new Error(name + ' is required and outside its exact bound.');
2566
- }
2567
- return value;
2568
- };
2569
- const input = exactKeys(
2570
- readBoundedJson(inputPath, 'Reliability deployment binding input').value,
2571
- ['schemaVersion', 'sources', 'workload'],
2572
- 'Reliability deployment binding input',
2573
- );
2574
- const document = createReliabilityDeploymentBinding(input, {
2575
- account: required('AWS_EXPECTED_ACCOUNT_ID', /^\\d{12}$/),
2576
- region: required('AWS_REGION', /^[a-z]{2}(?:-[a-z]+)+-\\d$/),
2577
- slice: '${name}',
2578
- stage: required('EBK_STAGE', /^(?:staging|production)$/),
2579
- }, {
2580
- runAttempt: required('EBK_SMOKE_RUN_ATTEMPT', /^\\d+$/),
2581
- runId: required('EBK_SMOKE_RUN_ID', /^\\d+$/),
2582
- });
2583
- const reference = writeImmutableArtifact(
2584
- '.ebk/evidence/reliability/bindings',
2585
- document,
2586
- );
2587
- process.stdout.write(
2588
- JSON.stringify({ ...reference, ...document }) + '\\n',
2589
- );
2590
- `,
2591
- 'scripts/verify-reliability.mjs': `import {
2592
- CloudWatchClient,
2593
- DescribeAlarmsCommand,
2594
- } from '@aws-sdk/client-cloudwatch';
2595
- import {
2596
- GetCallerIdentityCommand,
2597
- STSClient,
2598
- } from '@aws-sdk/client-sts';
2599
- import { readFileSync } from 'node:fs';
2600
- import { awsPartition } from './reliability-evidence-lib.mjs';
2601
- import {
2602
- validateAlarmRegistrationMetadata,
2603
- validateIncidentRecord,
2604
- validateReliabilityContract,
2605
- } from '@empire-builder-kit/runtime/reliability';
2606
-
2607
- const slo = JSON.parse(
2608
- readFileSync(new URL('../docs/reliability/slo.json', import.meta.url), 'utf8'),
2609
- );
2610
- const operations = JSON.parse(
2611
- readFileSync(new URL('../operations/reliability.json', import.meta.url), 'utf8'),
2612
- );
2613
- const incident = JSON.parse(
2614
- readFileSync(new URL('../operations/incident-template.json', import.meta.url), 'utf8'),
2615
- );
2616
- const contract = validateReliabilityContract(slo);
2617
- validateIncidentRecord(incident);
2618
- if (
2619
- operations?.schemaVersion !== 1 ||
2620
- operations?.slice !== '${name}' ||
2621
- operations?.sloRef !== 'docs:reliability/slo.json' ||
2622
- operations?.consoleIndependent !== true
2623
- ) {
2624
- throw new Error('Reliability operations registration is incompatible.');
2625
- }
2626
- if (!Array.isArray(operations.alarmRegistrations)) {
2627
- throw new Error('Reliability alarm registrations are absent.');
2628
- }
2629
- const alarmRegistrations = operations.alarmRegistrations.map(
2630
- validateAlarmRegistrationMetadata,
2631
- );
2632
- const registered = new Set(alarmRegistrations.map((alarm) => alarm.id));
2633
- if (registered.size !== alarmRegistrations.length) {
2634
- throw new Error('Reliability alarm registrations contain duplicate IDs.');
2635
- }
2636
- for (const objective of contract.objectives) {
2637
- for (const alarmId of objective.references.alarmIds) {
2638
- if (!registered.has(alarmId)) {
2639
- throw new Error(
2640
- 'SLO objective ' + objective.id + ' references an unregistered alarm.',
2641
- );
2642
- }
2643
- }
2644
- }
2645
- const requiredCoverage = [
2646
- 'alert-delivery',
2647
- 'built-in-retention-job',
2648
- 'deployed-smoke',
2649
- 'function',
2650
- 'job',
2651
- 'service',
2652
- ];
2653
- if (requiredCoverage.some(
2654
- (kind) => !operations.workloadCoverage?.some((entry) => entry.kind === kind),
2655
- )) {
2656
- throw new Error('Reliability workload coverage is incomplete.');
2657
- }
2658
- if (
2659
- operations.alertDelivery?.mode !== 'diagnostic-only' ||
2660
- operations.alertDelivery?.confirmation !==
2661
- 'unsupported-until-independent-route-is-configured' ||
2662
- operations.runtimeSmoke?.aggregateOwner !== 'testing-evidence' ||
2663
- operations.runtimeSmoke?.deployedResourceClass !==
2664
- 'testing-evidence-not-cloudwatch-alarm' ||
2665
- operations.runtimeSmoke?.reporter !==
2666
- 'testing-evidence-native-not-reliability-exercise-report' ||
2667
- operations.runtimeSmoke?.target !== 'smoke-deployed'
2668
- ) {
2669
- throw new Error(
2670
- 'Alert-delivery or deployed-smoke ownership is overstated.',
2671
- );
2672
- }
2673
-
2674
- let deployed = false;
2675
- if (process.argv.includes('--deployed')) {
2676
- const required = (key) => {
2677
- const value = process.env[key]?.trim();
2678
- if (!value || !/^[A-Za-z0-9._:/-]{1,128}$/.test(value)) {
2679
- throw new Error(key + ' is required for deployed verification.');
2680
- }
2681
- return value;
2682
- };
2683
- const account = required('AWS_EXPECTED_ACCOUNT_ID');
2684
- const region = required('AWS_REGION');
2685
- const stage = required('EBK_STAGE');
2686
- const partition = awsPartition(region);
2687
- const identity = await new STSClient({ region }).send(
2688
- new GetCallerIdentityCommand({}),
2689
- );
2690
- if (
2691
- identity.Account !== account ||
2692
- !identity.Arn?.startsWith('arn:' + partition + ':sts::' + account + ':')
2693
- ) {
2694
- throw new Error(
2695
- 'AWS caller identity does not match deployed reliability verification.',
2696
- );
2697
- }
2698
- const expected = operations.deployedAlarmResources?.map((resource) => ({
2699
- ...resource,
2700
- name: resource.name.replace('{stage}', stage),
2701
- }));
2702
- if (
2703
- !Array.isArray(expected) ||
2704
- expected.length < 1 ||
2705
- expected.length > 100 ||
2706
- new Set(expected.map(({ name }) => name)).size !== expected.length ||
2707
- new Set(expected.map(({ id }) => id)).size !== expected.length ||
2708
- expected.some(({ id }) => !registered.has(id))
2709
- ) {
2710
- throw new Error('Deployed alarm resource inventory is invalid.');
2711
- }
2712
- const response = await new CloudWatchClient({ region }).send(
2713
- new DescribeAlarmsCommand({
2714
- AlarmNames: expected.map(({ name }) => name),
2715
- MaxRecords: expected.length,
2716
- }),
2717
- );
2718
- if (response.NextToken) {
2719
- throw new Error('Deployed alarm verification exceeded its one-page bound.');
2720
- }
2721
- const alarms = response.MetricAlarms ?? [];
2722
- if (
2723
- alarms.length !== expected.length ||
2724
- new Set(alarms.map(({ AlarmName }) => AlarmName)).size !== alarms.length
2725
- ) {
2726
- throw new Error('Deployed alarm resource identity is absent or ambiguous.');
2727
- }
2728
- const primaryRouteArns = new Set();
2729
- for (const resource of expected) {
2730
- const alarm = alarms.find(({ AlarmName }) => AlarmName === resource.name);
2731
- const description = JSON.parse(alarm?.AlarmDescription ?? 'null');
2732
- if (
2733
- !alarm ||
2734
- alarm.AlarmArn !==
2735
- 'arn:' +
2736
- partition +
2737
- ':cloudwatch:' +
2738
- region +
2739
- ':' +
2740
- account +
2741
- ':alarm:' +
2742
- resource.name ||
2743
- description?.id !== resource.id ||
2744
- description?.slice !== '${name}' ||
2745
- description?.schemaVersion !== 1 ||
2746
- description?.owner !== resource.owner ||
2747
- description?.route !== resource.route ||
2748
- description?.runbook !== resource.runbook
2749
- ) {
2750
- throw new Error(
2751
- 'Deployed alarm does not match its exact AWS resource identity.',
2752
- );
2753
- }
2754
- if (
2755
- (resource.actions === 'none' && (alarm.AlarmActions?.length ?? 0) !== 0) ||
2756
- (resource.actions === 'primary-route' &&
2757
- (alarm.AlarmActions?.length ?? 0) !== 1)
2758
- ) {
2759
- throw new Error('Deployed alarm action route does not match policy.');
2760
- }
2761
- if (resource.actions === 'primary-route') {
2762
- const action = alarm.AlarmActions[0];
2763
- if (
2764
- typeof action !== 'string' ||
2765
- !action.startsWith(
2766
- 'arn:' + partition + ':sns:' + region + ':' + account + ':',
2767
- )
2768
- ) {
2769
- throw new Error('Deployed alarm action escaped the exact AWS target.');
2770
- }
2771
- primaryRouteArns.add(action);
2772
- }
2773
- const metricDefinitions = [
2774
- ...(alarm.MetricName
2775
- ? [{
2776
- dimensions: alarm.Dimensions ?? [],
2777
- metricName: alarm.MetricName,
2778
- namespace: alarm.Namespace,
2779
- period: alarm.Period,
2780
- statistic: alarm.Statistic,
2781
- }]
2782
- : []),
2783
- ...(alarm.Metrics ?? [])
2784
- .filter(({ MetricStat }) => MetricStat?.Metric)
2785
- .map(({ MetricStat }) => ({
2786
- dimensions: MetricStat.Metric.Dimensions ?? [],
2787
- metricName: MetricStat.Metric.MetricName,
2788
- namespace: MetricStat.Metric.Namespace,
2789
- period: MetricStat.Period,
2790
- statistic: MetricStat.Stat,
2791
- })),
2792
- ];
2793
- const actualDimensionNames = [
2794
- ...new Set(
2795
- metricDefinitions.flatMap(({ dimensions }) =>
2796
- dimensions.map(({ Name }) => Name),
2797
- ),
2798
- ),
2799
- ].sort();
2800
- const dimensionValues = new Map();
2801
- let incompatibleDimensionValue = false;
2802
- for (const { dimensions } of metricDefinitions) {
2803
- for (const { Name, Value } of dimensions) {
2804
- if (
2805
- typeof Name !== 'string' ||
2806
- typeof Value !== 'string' ||
2807
- Value.length < 1 ||
2808
- Value.length > 1024 ||
2809
- (dimensionValues.has(Name) &&
2810
- dimensionValues.get(Name) !== Value)
2811
- ) {
2812
- incompatibleDimensionValue = true;
2813
- }
2814
- dimensionValues.set(Name, Value);
2815
- }
2816
- }
2817
- const expectedDimensionValues = Object.fromEntries(
2818
- Object.entries(resource.dimensionValues ?? {}).map(([key, value]) => [
2819
- key,
2820
- value.replace('{stage}', stage),
2821
- ]),
2822
- );
2823
- const actualMetricNames = [
2824
- ...new Set(metricDefinitions.map(({ metricName }) => metricName)),
2825
- ].sort();
2826
- const actualNamespaces = [
2827
- ...new Set(metricDefinitions.map(({ namespace }) => namespace)),
2828
- ];
2829
- const expectedMetricNames = (
2830
- resource.metricNames ?? [resource.metricName]
2831
- ).slice().sort();
2832
- if (
2833
- JSON.stringify(actualDimensionNames) !==
2834
- JSON.stringify(resource.dimensionNames.slice().sort()) ||
2835
- incompatibleDimensionValue ||
2836
- Object.entries(expectedDimensionValues).some(
2837
- ([key, value]) => dimensionValues.get(key) !== value,
2838
- ) ||
2839
- JSON.stringify(actualMetricNames) !==
2840
- JSON.stringify(expectedMetricNames) ||
2841
- actualNamespaces.length !== 1 ||
2842
- actualNamespaces[0] !== resource.namespace ||
2843
- alarm.ComparisonOperator !== resource.comparisonOperator ||
2844
- alarm.EvaluationPeriods !== resource.evaluationPeriods ||
2845
- alarm.Threshold !== resource.threshold ||
2846
- alarm.TreatMissingData !== resource.treatMissingData ||
2847
- (resource.period !== undefined &&
2848
- metricDefinitions.some(({ period }) => period !== resource.period)) ||
2849
- (resource.statistic !== undefined &&
2850
- metricDefinitions.some(
2851
- ({ statistic }) => statistic !== resource.statistic,
2852
- ))
2853
- ) {
2854
- throw new Error(
2855
- 'Deployed alarm dimensions or AWS signal do not match inventory.',
2856
- );
2857
- }
2858
- if (
2859
- resource.signal === 'metric-math' &&
2860
- (
2861
- !Array.isArray(alarm.Metrics) ||
2862
- alarm.Metrics.filter(({ ReturnData }) => ReturnData).length !== 1 ||
2863
- (resource.objectiveId !== undefined &&
2864
- !alarm.Metrics.some(({ Expression }) => {
2865
- const objective = contract.objectives.find(
2866
- ({ id }) => id === resource.objectiveId,
2867
- );
2868
- const allowedBadFraction = objective
2869
- ? Number((1 - objective.target).toFixed(6)).toString()
2870
- : '';
2871
- return (
2872
- objective &&
2873
- Expression?.includes('IF(v>=') &&
2874
- Expression.includes('/' + allowedBadFraction)
2875
- );
2876
- }))
2877
- )
2878
- ) {
2879
- throw new Error('Deployed metric-math alarm is not executable.');
2880
- }
2881
- }
2882
- if (primaryRouteArns.size !== 1) {
2883
- throw new Error('Deployed alarms do not share one exact primary route.');
2884
- }
2885
- deployed = true;
2886
- }
2887
- process.stdout.write(JSON.stringify({
2888
- deployedAlarmResourcesVerified: deployed,
2889
- kind: 'reliability-contract-verification',
2890
- schemaVersion: 1,
2891
- slice: '${name}',
2892
- }) + '\\n');
2893
- `,
2894
- 'scripts/reliability-report.mjs': `import { readFileSync } from 'node:fs';
2895
- import {
2896
- evaluateSlo,
2897
- validateReliabilityContract,
2898
- } from '@empire-builder-kit/runtime/reliability';
2899
- import {
2900
- activeDeploymentBinding,
2901
- artifactReference,
2902
- binding,
2903
- digest,
2904
- exactKeys,
2905
- readBoundedJson,
2906
- safeToken,
2907
- sameBinding,
2908
- utc,
2909
- writeImmutableArtifact,
2910
- } from './reliability-evidence-lib.mjs';
2911
-
2912
- const inputPath = process.env.EBK_RELIABILITY_EVIDENCE_INPUT_PATH?.trim();
2913
- if (!inputPath) {
2914
- throw new Error('EBK_RELIABILITY_EVIDENCE_INPUT_PATH is required.');
2915
- }
2916
- const inputArtifact = readBoundedJson(inputPath, 'Reliability report input');
2917
- const input = exactKeys(
2918
- inputArtifact.value,
2919
- ['capture', 'objectiveId', 'schemaVersion'],
2920
- 'Reliability report input',
2921
- );
2922
- if (input.schemaVersion !== 1) {
2923
- throw new Error('Reliability report input is incompatible.');
2924
- }
2925
- const objectiveId = safeToken(input.objectiveId, 'objectiveId', 128);
2926
- const captured = artifactReference(input.capture, 'capture');
2927
- const capture = exactKeys(
2928
- captured.value,
2929
- [
2930
- 'binding',
2931
- 'bindingArtifact',
2932
- 'capturedAt',
2933
- 'kind',
2934
- 'metricResults',
2935
- 'objectiveId',
2936
- 'queryDigest',
2937
- 'sampleWindow',
2938
- 'schemaVersion',
2939
- 'slice',
2940
- 'target',
2941
- ],
2942
- 'Captured metric artifact',
2943
- );
2944
- if (
2945
- capture.kind !== 'reliability-metric-capture' ||
2946
- capture.schemaVersion !== 1 ||
2947
- capture.slice !== '${name}' ||
2948
- capture.objectiveId !== objectiveId ||
2949
- !Array.isArray(capture.metricResults)
2950
- ) {
2951
- throw new Error(
2952
- 'Reliability report requires the exact captured AWS metric artifact.',
2953
- );
2954
- }
2955
- const capturedBinding = binding(capture.binding, 'capture.binding');
2956
- const activeBinding = activeDeploymentBinding(
2957
- capture.bindingArtifact,
2958
- 'capture.bindingArtifact',
2959
- );
2960
- const captureTarget = exactKeys(
2961
- capture.target,
2962
- ['account', 'region', 'slice', 'stage'],
2963
- 'capture.target',
2964
- );
2965
- const sampleWindow = exactKeys(
2966
- capture.sampleWindow,
2967
- ['durationSeconds', 'end', 'start'],
2968
- 'capture.sampleWindow',
2969
- );
2970
- const sampleStart = utc(sampleWindow.start, 'capture.sampleWindow.start');
2971
- const sampleEnd = utc(sampleWindow.end, 'capture.sampleWindow.end');
2972
- const sampleDurationSeconds =
2973
- (Date.parse(sampleEnd) - Date.parse(sampleStart)) / 1_000;
2974
- digest(capture.queryDigest, 'capture.queryDigest');
2975
- if (
2976
- !sameBinding(capturedBinding, activeBinding.binding) ||
2977
- ['account', 'region', 'slice', 'stage'].some(
2978
- (key) => captureTarget[key] !== activeBinding.target[key],
2979
- ) ||
2980
- !Number.isSafeInteger(sampleWindow.durationSeconds) ||
2981
- sampleWindow.durationSeconds !== sampleDurationSeconds ||
2982
- sampleDurationSeconds <= 0 ||
2983
- sampleDurationSeconds > 6 * 60 * 60
2984
- ) {
2985
- throw new Error(
2986
- 'Captured metric sample is not bound to the exact active deployment and bounded window.',
2987
- );
2988
- }
2989
- const result = (id, optional = false) => {
2990
- const matches = capture.metricResults.filter((entry) => entry?.id === id);
2991
- if (matches.length === 0 && optional) return 0;
2992
- if (
2993
- matches.length !== 1 ||
2994
- !Array.isArray(matches[0].timestamps) ||
2995
- !Array.isArray(matches[0].values) ||
2996
- matches[0].timestamps.length !== matches[0].values.length ||
2997
- matches[0].values.length > 1008 ||
2998
- matches[0].timestamps.some(
2999
- (value) =>
3000
- typeof value !== 'string' ||
3001
- !Number.isFinite(Date.parse(value)) ||
3002
- Date.parse(value) < Date.parse(sampleStart) ||
3003
- Date.parse(value) > Date.parse(sampleEnd),
3004
- ) ||
3005
- matches[0].values.some(
3006
- (value) => typeof value !== 'number' || !Number.isFinite(value) || value < 0,
3007
- )
3008
- ) {
3009
- throw new Error('Captured metric series ' + id + ' is absent or ambiguous.');
3010
- }
3011
- return matches[0].values.reduce((total, value) => total + value, 0);
3012
- };
3013
- const contract = validateReliabilityContract(
3014
- JSON.parse(
3015
- readFileSync(
3016
- new URL('../docs/reliability/slo.json', import.meta.url),
3017
- 'utf8',
3018
- ),
3019
- ),
3020
- );
3021
- const objective = contract.objectives.find(
3022
- ({ id }) => id === objectiveId,
3023
- );
3024
- if (!objective) throw new Error('Reliability objective is not declared.');
3025
- if (capturedBinding.workload !== objective.journey) {
3026
- throw new Error(
3027
- 'Captured metric workload does not match the declared objective journey.',
3028
- );
3029
- }
3030
- const validEvents = result('valid');
3031
- const goodEvents = result('good');
3032
- const syntheticValid = result(
3033
- 'synthetic-valid',
3034
- objective.lowTraffic.mode === 'data-insufficient',
3035
- );
3036
- const syntheticGood = result(
3037
- 'synthetic-good',
3038
- objective.lowTraffic.mode === 'data-insufficient',
3039
- );
3040
- if (
3041
- !Number.isSafeInteger(validEvents) ||
3042
- !Number.isSafeInteger(goodEvents) ||
3043
- !Number.isSafeInteger(syntheticValid) ||
3044
- !Number.isSafeInteger(syntheticGood) ||
3045
- goodEvents > validEvents ||
3046
- syntheticGood > syntheticValid
3047
- ) {
3048
- throw new Error('Captured metric counts are incompatible.');
3049
- }
3050
- const evaluation = evaluateSlo({
3051
- goodEvents,
3052
- minimumValidEvents: objective.minimumValidEvents.diagnosticSample,
3053
- objective,
3054
- ...(validEvents >= objective.minimumValidEvents.diagnosticSample
3055
- ? {}
3056
- : {
3057
- syntheticSuccess:
3058
- syntheticValid > 0 ? syntheticGood === syntheticValid : undefined,
3059
- }),
3060
- validEvents,
3061
- });
3062
- const report = {
3063
- binding: capturedBinding,
3064
- capturedMetricDigest: captured.digest,
3065
- declaredObjectiveWindow: objective.window,
3066
- kind: 'reliability-slo-diagnostic-sample',
3067
- objectiveId: objective.id,
3068
- provenance: activeBinding.target.stage,
3069
- sampleEvaluation: evaluation,
3070
- sampleWindow: {
3071
- durationSeconds: sampleDurationSeconds,
3072
- end: sampleEnd,
3073
- start: sampleStart,
3074
- },
3075
- schemaVersion: 1,
3076
- scope: 'bounded-diagnostic-sample-not-slo-window-evidence',
3077
- slice: '${name}',
3078
- };
3079
- const reference = writeImmutableArtifact(
3080
- '.ebk/evidence/reliability/slo',
3081
- report,
3082
- );
3083
- process.stdout.write(JSON.stringify({ ...reference, ...report }) + '\\n');
3084
- `,
3085
- 'scripts/collect-reliability-exercise.mjs': `import {
3086
- CloudWatchClient,
3087
- DescribeAlarmHistoryCommand,
3088
- DescribeAlarmsCommand,
3089
- } from '@aws-sdk/client-cloudwatch';
3090
- import {
3091
- DescribeExecutionCommand,
3092
- SFNClient,
3093
- } from '@aws-sdk/client-sfn';
3094
- import {
3095
- GetCallerIdentityCommand,
3096
- STSClient,
3097
- } from '@aws-sdk/client-sts';
3098
- import { readFileSync } from 'node:fs';
3099
- import {
3100
- activeDeploymentBinding,
3101
- awsPartition,
3102
- authorizedExecutionArn,
3103
- exactKeys,
3104
- readBoundedJson,
3105
- safeToken,
3106
- utc,
3107
- writeImmutableArtifact,
3108
- } from './reliability-evidence-lib.mjs';
3109
-
3110
- const inputPath =
3111
- process.env.EBK_RELIABILITY_EXERCISE_COLLECTION_INPUT_PATH?.trim();
3112
- if (!inputPath) {
3113
- throw new Error(
3114
- 'EBK_RELIABILITY_EXERCISE_COLLECTION_INPUT_PATH is required.',
3115
- );
3116
- }
3117
- const input = exactKeys(
3118
- readBoundedJson(
3119
- inputPath,
3120
- 'Reliability exercise collection input',
3121
- ).value,
3122
- [
3123
- 'alarmResourceId',
3124
- 'bindingArtifact',
3125
- 'exerciseId',
3126
- 'schemaVersion',
3127
- 'target',
3128
- 'windowEnd',
3129
- 'windowStart',
3130
- 'workflowExecutions',
3131
- ],
3132
- 'Reliability exercise collection input',
3133
- );
3134
- if (input.schemaVersion !== 1) {
3135
- throw new Error('Reliability exercise collection input is incompatible.');
3136
- }
3137
- const exerciseId = safeToken(input.exerciseId, 'exerciseId', 128);
3138
- const declaration = JSON.parse(
3139
- readFileSync(
3140
- new URL('../testing/reliability-exercises.json', import.meta.url),
3141
- 'utf8',
3142
- ),
3143
- );
3144
- const operations = JSON.parse(
3145
- readFileSync(
3146
- new URL('../operations/reliability.json', import.meta.url),
3147
- 'utf8',
3148
- ),
3149
- );
3150
- const exercise = declaration.exercises?.find(({ id }) => id === exerciseId);
3151
- if (
3152
- !exercise ||
3153
- exercise.observation?.adapter !== 'aws-cloudwatch-alarm-history-v1'
3154
- ) {
3155
- throw new Error(
3156
- 'Reliability exercise has no stable-v1 AWS collection adapter.',
3157
- );
3158
- }
3159
- const alarmResourceId = safeToken(
3160
- input.alarmResourceId,
3161
- 'alarmResourceId',
3162
- 128,
3163
- );
3164
- const alarmResource = operations.deployedAlarmResources?.find(
3165
- ({ id }) => id === alarmResourceId,
3166
- );
3167
- const dynamicMatch =
3168
- (exercise.observation.dynamicAlarmKind === 'service' &&
3169
- /^service-[a-z][a-z0-9-]*-health$/.test(alarmResourceId)) ||
3170
- (exercise.observation.dynamicAlarmKind === 'job' &&
3171
- /^job-[a-z][a-z0-9-]*-failure$/.test(alarmResourceId));
3172
- if (
3173
- !alarmResource ||
3174
- (!exercise.observation.alarmIds.includes(alarmResourceId) && !dynamicMatch)
3175
- ) {
3176
- throw new Error(
3177
- 'Reliability exercise alarm is absent or outside its declared workload.',
3178
- );
3179
- }
3180
- const target = exactKeys(
3181
- input.target,
3182
- ['account', 'region', 'slice', 'stage'],
3183
- 'target',
3184
- );
3185
- for (const key of ['account', 'region', 'slice', 'stage']) {
3186
- safeToken(target[key], 'target.' + key, 128);
3187
- }
3188
- if (target.slice !== '${name}') {
3189
- throw new Error('Reliability collection target escaped the exact Slice.');
3190
- }
3191
- const activeBinding = activeDeploymentBinding(
3192
- input.bindingArtifact,
3193
- 'bindingArtifact',
3194
- );
3195
- const collectedBinding = activeBinding.binding;
3196
- const activeResources = activeBinding.resources;
3197
- const bindingTarget = activeBinding.target;
3198
- if (
3199
- collectedBinding.workload !== exercise.workload ||
3200
- ['account', 'region', 'slice', 'stage'].some(
3201
- (key) => bindingTarget[key] !== target[key],
3202
- )
3203
- ) {
3204
- throw new Error(
3205
- 'Reliability collection deployment binding does not match the exercise target.',
3206
- );
3207
- }
3208
- const identity = await new STSClient({ region: target.region }).send(
3209
- new GetCallerIdentityCommand({}),
3210
- );
3211
- const partition = awsPartition(target.region);
3212
- if (
3213
- identity.Account !== target.account ||
3214
- !identity.Arn?.startsWith(
3215
- 'arn:' + partition + ':sts::' + target.account + ':',
3216
- )
3217
- ) {
3218
- throw new Error(
3219
- 'AWS caller identity does not match the active reliability target.',
3220
- );
3221
- }
3222
- const windowStart = utc(input.windowStart, 'windowStart');
3223
- const windowEnd = utc(input.windowEnd, 'windowEnd');
3224
- const windowMilliseconds = Date.parse(windowEnd) - Date.parse(windowStart);
3225
- if (
3226
- windowMilliseconds <= 0 ||
3227
- windowMilliseconds > 6 * 60 * 60 * 1000
3228
- ) {
3229
- throw new Error(
3230
- 'Reliability collection window must be positive and at most six hours.',
3231
- );
3232
- }
3233
- const alarmName = alarmResource.name.replace('{stage}', target.stage);
3234
- if (
3235
- !alarmName.startsWith('${name}-' + target.stage + '-') ||
3236
- alarmName.includes('{stage}') ||
3237
- !activeResources.alarmNames.includes(alarmName)
3238
- ) {
3239
- throw new Error(
3240
- 'Reliability alarm is not authorized by the protected deployment.',
3241
- );
3242
- }
3243
- const historyRequest = {
3244
- AlarmName: alarmName,
3245
- EndDate: new Date(windowEnd),
3246
- HistoryItemType: 'StateUpdate',
3247
- MaxRecords: 32,
3248
- ScanBy: 'TimestampAscending',
3249
- StartDate: new Date(windowStart),
3250
- };
3251
- const stateRequest = {
3252
- AlarmNames: [alarmName],
3253
- MaxRecords: 1,
3254
- };
3255
- const cloudwatch = new CloudWatchClient({ region: target.region });
3256
- const historyResponse = await cloudwatch.send(
3257
- new DescribeAlarmHistoryCommand(historyRequest),
3258
- );
3259
- const stateResponse = await cloudwatch.send(
3260
- new DescribeAlarmsCommand(stateRequest),
3261
- );
3262
- if (historyResponse.NextToken || stateResponse.NextToken) {
3263
- throw new Error('Reliability alarm collection exceeded its page bound.');
3264
- }
3265
- const boundedText = (value, label, maximum = 2048) => {
3266
- if (
3267
- typeof value !== 'string' ||
3268
- value.length < 1 ||
3269
- value.length > maximum ||
3270
- [...value].some((character) => {
3271
- const code = character.charCodeAt(0);
3272
- return code < 9 || (code > 13 && code < 32) || code === 127;
3273
- })
3274
- ) {
3275
- throw new Error(label + ' is not bounded provider metadata.');
3276
- }
3277
- return value;
3278
- };
3279
- const requestId = safeToken(
3280
- historyResponse.$metadata?.requestId,
3281
- 'alarmHistory.requestId',
3282
- 128,
3283
- );
3284
- const stateRequestId = safeToken(
3285
- stateResponse.$metadata?.requestId,
3286
- 'alarmState.requestId',
3287
- 128,
3288
- );
3289
- const historyItems = (historyResponse.AlarmHistoryItems ?? []).map(
3290
- (item, index) => {
3291
- const historyData = boundedText(
3292
- item.HistoryData,
3293
- 'alarmHistory[' + index + '].historyData',
3294
- 4096,
3295
- );
3296
- let parsed;
3297
- try {
3298
- parsed = JSON.parse(historyData);
3299
- } catch {
3300
- throw new Error('Alarm history state data is not valid JSON.');
3301
- }
3302
- const state = parsed?.newState?.stateValue;
3303
- if (!['ALARM', 'INSUFFICIENT_DATA', 'OK'].includes(state)) {
3304
- throw new Error('Alarm history contains an unsupported state.');
3305
- }
3306
- const timestamp = utc(
3307
- item.Timestamp?.toISOString?.(),
3308
- 'alarmHistory[' + index + '].timestamp',
3309
- );
3310
- if (
3311
- Date.parse(timestamp) < Date.parse(windowStart) ||
3312
- Date.parse(timestamp) > Date.parse(windowEnd) ||
3313
- item.AlarmName !== alarmName ||
3314
- item.HistoryItemType !== 'StateUpdate'
3315
- ) {
3316
- throw new Error('Alarm history escaped the exact collection request.');
3317
- }
3318
- return {
3319
- alarmName,
3320
- historyData,
3321
- historyItemType: item.HistoryItemType,
3322
- historySummary: boundedText(
3323
- item.HistorySummary,
3324
- 'alarmHistory[' + index + '].historySummary',
3325
- ),
3326
- state,
3327
- timestamp,
3328
- };
3329
- },
3330
- );
3331
- const failureIndex = historyItems.findIndex(({ state }) => state === 'ALARM');
3332
- const recoveryIndex = historyItems.findIndex(
3333
- ({ state }, index) => index > failureIndex && state === 'OK',
3334
- );
3335
- if (failureIndex < 0 || recoveryIndex < 0) {
3336
- throw new Error(
3337
- 'Alarm history does not independently prove failure followed by recovery.',
3338
- );
3339
- }
3340
- const alarm = stateResponse.MetricAlarms?.[0];
3341
- const alarmArn =
3342
- 'arn:' +
3343
- partition +
3344
- ':cloudwatch:' +
3345
- target.region +
3346
- ':' +
3347
- target.account +
3348
- ':alarm:' +
3349
- alarmName;
3350
- let description;
3351
- try {
3352
- description = JSON.parse(alarm?.AlarmDescription ?? 'null');
3353
- } catch {
3354
- throw new Error('Reliability alarm description is not valid metadata.');
3355
- }
3356
- if (
3357
- stateResponse.MetricAlarms?.length !== 1 ||
3358
- alarm?.AlarmArn !== alarmArn ||
3359
- alarm?.AlarmName !== alarmName ||
3360
- alarm?.StateValue !== 'OK' ||
3361
- description?.id !== alarmResource.id ||
3362
- description?.slice !== '${name}' ||
3363
- description?.schemaVersion !== 1
3364
- ) {
3365
- throw new Error(
3366
- 'Reliability alarm response does not match the exact declared resource.',
3367
- );
3368
- }
3369
- const workflowInputs = input.workflowExecutions ?? [];
3370
- if (
3371
- !Array.isArray(workflowInputs) ||
3372
- workflowInputs.length > 2 ||
3373
- (exercise.observation.workflowMetadata === 'required' &&
3374
- workflowInputs.length !== 2) ||
3375
- (exercise.observation.workflowMetadata === 'none' &&
3376
- workflowInputs.length !== 0)
3377
- ) {
3378
- throw new Error(
3379
- 'Reliability workflow provenance is absent or outside its declared bound.',
3380
- );
3381
- }
3382
- const workflowExecutions = [];
3383
- for (const [index, workflowInput] of workflowInputs.entries()) {
3384
- const workflow = exactKeys(
3385
- workflowInput,
3386
- ['executionArn', 'role'],
3387
- 'workflowExecutions[' + index + ']',
3388
- );
3389
- if (
3390
- !['failure', 'recovery'].includes(workflow.role) ||
3391
- workflowInputs.filter(({ role }) => role === workflow.role).length !== 1
3392
- ) {
3393
- throw new Error('Reliability workflow roles must be exact and unique.');
3394
- }
3395
- const executionArn = safeToken(
3396
- workflow.executionArn,
3397
- 'workflowExecutions[' + index + '].executionArn',
3398
- 512,
3399
- );
3400
- if (!authorizedExecutionArn(activeResources, executionArn)) {
3401
- throw new Error(
3402
- 'Reliability workflow is not authorized by the protected deployment.',
3403
- );
3404
- }
3405
- const workflowRequest = {
3406
- executionArn,
3407
- includedData: 'METADATA_ONLY',
3408
- };
3409
- const response = await new SFNClient({ region: target.region }).send(
3410
- new DescribeExecutionCommand(workflowRequest),
3411
- );
3412
- const expectedStatuses =
3413
- workflow.role === 'failure'
3414
- ? ['ABORTED', 'FAILED', 'TIMED_OUT']
3415
- : ['SUCCEEDED'];
3416
- if (
3417
- response.executionArn !== executionArn ||
3418
- !activeResources.stateMachineArns.includes(response.stateMachineArn) ||
3419
- !expectedStatuses.includes(response.status)
3420
- ) {
3421
- throw new Error(
3422
- 'Reliability workflow response does not prove the declared outcome.',
3423
- );
3424
- }
3425
- workflowExecutions.push({
3426
- request: workflowRequest,
3427
- response: {
3428
- executionArn: response.executionArn,
3429
- requestId: safeToken(
3430
- response.$metadata?.requestId,
3431
- 'workflow.requestId',
3432
- 128,
3433
- ),
3434
- startDate: utc(
3435
- response.startDate?.toISOString?.(),
3436
- 'workflow.startDate',
3437
- ),
3438
- stateMachineArn: response.stateMachineArn,
3439
- status: response.status,
3440
- stopDate: utc(
3441
- response.stopDate?.toISOString?.(),
3442
- 'workflow.stopDate',
3443
- ),
3444
- },
3445
- role: workflow.role,
3446
- });
3447
- }
3448
- const failure = historyItems[failureIndex];
3449
- const recovery = historyItems[recoveryIndex];
3450
- const collection = {
3451
- alarm: {
3452
- alarmArn,
3453
- alarmName,
3454
- currentState: alarm.StateValue,
3455
- description,
3456
- },
3457
- binding: collectedBinding,
3458
- bindingArtifact: {
3459
- digest: activeBinding.digest,
3460
- path: activeBinding.path,
3461
- },
3462
- exerciseId,
3463
- kind: 'reliability-exercise-aws-collection',
3464
- requests: {
3465
- alarmHistory: {
3466
- ...historyRequest,
3467
- EndDate: windowEnd,
3468
- StartDate: windowStart,
3469
- },
3470
- alarmState: stateRequest,
3471
- },
3472
- responses: {
3473
- alarmHistory: {
3474
- items: historyItems,
3475
- requestId,
3476
- },
3477
- alarmState: {
3478
- requestId: stateRequestId,
3479
- state: alarm.StateValue,
3480
- },
3481
- workflowExecutions,
3482
- },
3483
- schemaVersion: 1,
3484
- slice: '${name}',
3485
- target,
3486
- transitions: {
3487
- failure: { state: failure.state, timestamp: failure.timestamp },
3488
- recovery: { state: recovery.state, timestamp: recovery.timestamp },
3489
- },
3490
- workload: exercise.workload,
3491
- };
3492
- const collectionArtifact = writeImmutableArtifact(
3493
- '.ebk/evidence/reliability/collections',
3494
- collection,
3495
- );
3496
- const observation = (role, transition, status) => ({
3497
- binding: collectedBinding,
3498
- capturedAt: transition.timestamp,
3499
- evidenceId:
3500
- exerciseId + '-' + role + '-' + collectionArtifact.digest.slice(0, 16),
3501
- exerciseId,
3502
- kind: 'reliability-exercise-' + role,
3503
- producer: {
3504
- adapter: 'aws-cloudwatch-alarm-history-v1',
3505
- collectionArtifact,
3506
- requestId,
3507
- resource: alarmArn,
3508
- },
3509
- schemaVersion: 1,
3510
- slice: '${name}',
3511
- status,
3512
- workload: exercise.workload,
3513
- });
3514
- const failureArtifact = writeImmutableArtifact(
3515
- '.ebk/evidence/reliability/exercise-inputs',
3516
- observation('failure', failure, 'observed'),
3517
- );
3518
- const recoveryArtifact = writeImmutableArtifact(
3519
- '.ebk/evidence/reliability/exercise-inputs',
3520
- observation(
3521
- 'recovery',
3522
- recovery,
3523
- exercise.workload === 'alert-delivery' ? 'unsupported' : 'verified',
3524
- ),
3525
- );
3526
- process.stdout.write(
3527
- JSON.stringify({
3528
- collection: collectionArtifact,
3529
- failure: failureArtifact,
3530
- kind: 'reliability-exercise-collection-result',
3531
- recovery: recoveryArtifact,
3532
- schemaVersion: 1,
3533
- }) + '\\n',
3534
- );
3535
- `,
3536
- 'scripts/reliability-exercise-report.mjs': `import { readFileSync } from 'node:fs';
3537
- import {
3538
- activeDeploymentBinding,
3539
- artifactReference,
3540
- binding,
3541
- exactKeys,
3542
- readBoundedJson,
3543
- safeToken,
3544
- sameBinding,
3545
- utc,
3546
- writeImmutableArtifact,
3547
- } from './reliability-evidence-lib.mjs';
3548
-
3549
- const inputPath = process.env.EBK_RELIABILITY_EXERCISE_INPUT_PATH?.trim();
3550
- if (!inputPath) {
3551
- throw new Error('EBK_RELIABILITY_EXERCISE_INPUT_PATH is required.');
3552
- }
3553
- const inputArtifact = readBoundedJson(
3554
- inputPath,
3555
- 'Reliability exercise report input',
3556
- );
3557
- const input = exactKeys(
3558
- inputArtifact.value,
3559
- ['artifacts', 'binding', 'exerciseId', 'schemaVersion'],
3560
- 'Reliability exercise report input',
3561
- );
3562
- const declaration = JSON.parse(
3563
- readFileSync(
3564
- new URL('../testing/reliability-exercises.json', import.meta.url),
3565
- 'utf8',
3566
- ),
3567
- );
3568
- if (input.schemaVersion !== 1) {
3569
- throw new Error('Reliability exercise report input is incompatible.');
3570
- }
3571
- const exerciseId = safeToken(input.exerciseId, 'exerciseId', 128);
3572
- const exercise = declaration.exercises?.find(
3573
- ({ id }) => id === exerciseId,
3574
- );
3575
- if (!exercise) {
3576
- throw new Error('Reliability exercise is undeclared or incomplete.');
3577
- }
3578
- const reportBinding = binding(input.binding, 'binding');
3579
- if (reportBinding.workload !== exercise.workload) {
3580
- throw new Error('Reliability exercise workload binding does not match.');
3581
- }
3582
- const references = exactKeys(
3583
- input.artifacts,
3584
- ['cleanup', 'failure', 'postconditions', 'recovery'],
3585
- 'artifacts',
3586
- );
3587
- const roles = ['failure', 'recovery', 'postconditions', 'cleanup'];
3588
- const statuses = {
3589
- cleanup: 'complete',
3590
- failure: 'observed',
3591
- postconditions: 'passed',
3592
- recovery:
3593
- exercise.workload === 'alert-delivery' ? 'unsupported' : 'verified',
3594
- };
3595
- const evidence = {};
3596
- const collectionDigests = [];
3597
- let protectedStage;
3598
- let previous = 0;
3599
- for (const role of roles) {
3600
- const reference = artifactReference(references[role], 'artifacts.' + role);
3601
- const artifact = exactKeys(
3602
- reference.value,
3603
- [
3604
- 'binding',
3605
- 'capturedAt',
3606
- 'checks',
3607
- 'evidenceId',
3608
- 'exerciseId',
3609
- 'kind',
3610
- 'producer',
3611
- 'schemaVersion',
3612
- 'slice',
3613
- 'status',
3614
- 'workload',
3615
- ],
3616
- role + ' artifact',
3617
- );
3618
- const artifactBinding = binding(artifact.binding, role + '.binding');
3619
- const producer = exactKeys(
3620
- artifact.producer,
3621
- role === 'failure' || role === 'recovery'
3622
- ? ['adapter', 'collectionArtifact', 'requestId', 'resource']
3623
- : ['kind', 'requestId', 'resource'],
3624
- role + '.producer',
3625
- );
3626
- const capturedAt = Date.parse(utc(artifact.capturedAt, role + '.capturedAt'));
3627
- if (
3628
- artifact.schemaVersion !== 1 ||
3629
- artifact.kind !== 'reliability-exercise-' + role ||
3630
- artifact.exerciseId !== exercise.id ||
3631
- artifact.slice !== '${name}' ||
3632
- artifact.workload !== exercise.workload ||
3633
- !sameBinding(reportBinding, artifactBinding) ||
3634
- capturedAt < previous ||
3635
- !safeToken(artifact.evidenceId, role + '.evidenceId', 128) ||
3636
- !safeToken(producer.requestId, role + '.producer.requestId', 128) ||
3637
- !safeToken(producer.resource, role + '.producer.resource', 512)
3638
- ) {
3639
- throw new Error(
3640
- 'Reliability exercise artifact is fabricated, cross-paired, or unsanitized.',
3641
- );
3642
- }
3643
- previous = capturedAt;
3644
- if (role === 'failure' || role === 'recovery') {
3645
- if (producer.adapter !== 'aws-cloudwatch-alarm-history-v1') {
3646
- throw new Error(
3647
- 'Failure and recovery require the generated AWS collection adapter.',
3648
- );
3649
- }
3650
- const collectionReference = artifactReference(
3651
- producer.collectionArtifact,
3652
- role + '.producer.collectionArtifact',
3653
- );
3654
- const collection = exactKeys(
3655
- collectionReference.value,
3656
- [
3657
- 'alarm',
3658
- 'binding',
3659
- 'bindingArtifact',
3660
- 'exerciseId',
3661
- 'kind',
3662
- 'requests',
3663
- 'responses',
3664
- 'schemaVersion',
3665
- 'slice',
3666
- 'target',
3667
- 'transitions',
3668
- 'workload',
3669
- ],
3670
- role + ' collection',
3671
- );
3672
- const collectionBinding = binding(
3673
- collection.binding,
3674
- role + '.collection.binding',
3675
- );
3676
- const collectionActiveBinding = activeDeploymentBinding(
3677
- collection.bindingArtifact,
3678
- role + '.collection.bindingArtifact',
3679
- );
3680
- const alarm = exactKeys(
3681
- collection.alarm,
3682
- ['alarmArn', 'alarmName', 'currentState', 'description'],
3683
- role + '.collection.alarm',
3684
- );
3685
- const requests = exactKeys(
3686
- collection.requests,
3687
- ['alarmHistory', 'alarmState'],
3688
- role + '.collection.requests',
3689
- );
3690
- const responses = exactKeys(
3691
- collection.responses,
3692
- ['alarmHistory', 'alarmState', 'workflowExecutions'],
3693
- role + '.collection.responses',
3694
- );
3695
- const alarmHistoryRequest = exactKeys(
3696
- requests.alarmHistory,
3697
- [
3698
- 'AlarmName',
3699
- 'EndDate',
3700
- 'HistoryItemType',
3701
- 'MaxRecords',
3702
- 'ScanBy',
3703
- 'StartDate',
3704
- ],
3705
- role + '.collection.requests.alarmHistory',
3706
- );
3707
- const alarmStateRequest = exactKeys(
3708
- requests.alarmState,
3709
- ['AlarmNames', 'MaxRecords'],
3710
- role + '.collection.requests.alarmState',
3711
- );
3712
- const alarmHistoryResponse = exactKeys(
3713
- responses.alarmHistory,
3714
- ['items', 'requestId'],
3715
- role + '.collection.responses.alarmHistory',
3716
- );
3717
- const alarmStateResponse = exactKeys(
3718
- responses.alarmState,
3719
- ['requestId', 'state'],
3720
- role + '.collection.responses.alarmState',
3721
- );
3722
- const collectionTarget = exactKeys(
3723
- collection.target,
3724
- ['account', 'region', 'slice', 'stage'],
3725
- role + '.collection.target',
3726
- );
3727
- const transitions = exactKeys(
3728
- collection.transitions,
3729
- ['failure', 'recovery'],
3730
- role + '.collection.transitions',
3731
- );
3732
- const transition = exactKeys(
3733
- transitions[role],
3734
- ['state', 'timestamp'],
3735
- role + '.collection.transitions.' + role,
3736
- );
3737
- if (
3738
- !Array.isArray(alarmHistoryResponse.items) ||
3739
- !Array.isArray(responses.workflowExecutions)
3740
- ) {
3741
- throw new Error(
3742
- 'Reliability collection responses are outside their bounded shape.',
3743
- );
3744
- }
3745
- const historyStates = alarmHistoryResponse.items.map((item, index) => {
3746
- const historyItem = exactKeys(
3747
- item,
3748
- [
3749
- 'alarmName',
3750
- 'historyData',
3751
- 'historyItemType',
3752
- 'historySummary',
3753
- 'state',
3754
- 'timestamp',
3755
- ],
3756
- role + '.collection.responses.alarmHistory.items[' + index + ']',
3757
- );
3758
- if (
3759
- historyItem.alarmName !== alarm.alarmName ||
3760
- historyItem.historyItemType !== 'StateUpdate' ||
3761
- !['ALARM', 'INSUFFICIENT_DATA', 'OK'].includes(historyItem.state) ||
3762
- !utc(
3763
- historyItem.timestamp,
3764
- role + '.collection.responses.alarmHistory.items.timestamp',
3765
- ) ||
3766
- typeof historyItem.historyData !== 'string' ||
3767
- historyItem.historyData.length > 4096 ||
3768
- typeof historyItem.historySummary !== 'string' ||
3769
- historyItem.historySummary.length > 2048
3770
- ) {
3771
- throw new Error(
3772
- 'Reliability collection contains incompatible alarm history.',
3773
- );
3774
- }
3775
- return {
3776
- state: historyItem.state,
3777
- timestamp: historyItem.timestamp,
3778
- };
3779
- });
3780
- const failureHistoryIndex = historyStates.findIndex(
3781
- ({ state }) => state === 'ALARM',
3782
- );
3783
- const recoveryHistoryIndex = historyStates.findIndex(
3784
- ({ state }, index) =>
3785
- index > failureHistoryIndex && state === 'OK',
3786
- );
3787
- for (const [index, workflowEntry] of
3788
- responses.workflowExecutions.entries()) {
3789
- const workflow = exactKeys(
3790
- workflowEntry,
3791
- ['request', 'response', 'role'],
3792
- role + '.collection.responses.workflowExecutions[' + index + ']',
3793
- );
3794
- const workflowRequest = exactKeys(
3795
- workflow.request,
3796
- ['executionArn', 'includedData'],
3797
- role + '.collection.responses.workflowExecutions.request',
3798
- );
3799
- const workflowResponse = exactKeys(
3800
- workflow.response,
3801
- [
3802
- 'executionArn',
3803
- 'requestId',
3804
- 'startDate',
3805
- 'stateMachineArn',
3806
- 'status',
3807
- 'stopDate',
3808
- ],
3809
- role + '.collection.responses.workflowExecutions.response',
3810
- );
3811
- if (
3812
- !['failure', 'recovery'].includes(workflow.role) ||
3813
- workflowRequest.includedData !== 'METADATA_ONLY' ||
3814
- workflowRequest.executionArn !== workflowResponse.executionArn ||
3815
- !safeToken(
3816
- workflowResponse.requestId,
3817
- role + '.collection.responses.workflow.requestId',
3818
- 128,
3819
- ) ||
3820
- (workflow.role === 'failure'
3821
- ? !['ABORTED', 'FAILED', 'TIMED_OUT'].includes(
3822
- workflowResponse.status,
3823
- )
3824
- : workflowResponse.status !== 'SUCCEEDED')
3825
- ) {
3826
- throw new Error(
3827
- 'Reliability collection workflow provenance is incompatible.',
3828
- );
3829
- }
3830
- }
3831
- if (
3832
- collection.kind !== 'reliability-exercise-aws-collection' ||
3833
- collection.schemaVersion !== 1 ||
3834
- collection.exerciseId !== exercise.id ||
3835
- collection.slice !== '${name}' ||
3836
- collection.workload !== exercise.workload ||
3837
- !sameBinding(reportBinding, collectionBinding) ||
3838
- !sameBinding(collectionBinding, collectionActiveBinding.binding) ||
3839
- alarm.currentState !== 'OK' ||
3840
- alarmStateResponse.state !== 'OK' ||
3841
- !safeToken(
3842
- alarmStateResponse.requestId,
3843
- role + '.collection.responses.alarmState.requestId',
3844
- 128,
3845
- ) ||
3846
- alarm.alarmArn !== producer.resource ||
3847
- collectionTarget.slice !== '${name}' ||
3848
- ['account', 'region', 'slice', 'stage'].some(
3849
- (key) =>
3850
- collectionTarget[key] !==
3851
- collectionActiveBinding.target[key],
3852
- ) ||
3853
- !safeToken(
3854
- collectionTarget.account,
3855
- role + '.collection.target.account',
3856
- 128,
3857
- ) ||
3858
- !safeToken(
3859
- collectionTarget.region,
3860
- role + '.collection.target.region',
3861
- 128,
3862
- ) ||
3863
- !safeToken(
3864
- collectionTarget.stage,
3865
- role + '.collection.target.stage',
3866
- 128,
3867
- ) ||
3868
- alarmHistoryRequest.AlarmName !== alarm.alarmName ||
3869
- alarmHistoryRequest.HistoryItemType !== 'StateUpdate' ||
3870
- alarmHistoryRequest.MaxRecords !== 32 ||
3871
- alarmHistoryRequest.ScanBy !== 'TimestampAscending' ||
3872
- !Array.isArray(alarmStateRequest.AlarmNames) ||
3873
- alarmStateRequest.AlarmNames.length !== 1 ||
3874
- alarmStateRequest.AlarmNames[0] !== alarm.alarmName ||
3875
- alarmStateRequest.MaxRecords !== 1 ||
3876
- alarmHistoryResponse.requestId !== producer.requestId ||
3877
- alarmHistoryResponse.items.length < 2 ||
3878
- failureHistoryIndex < 0 ||
3879
- recoveryHistoryIndex < 0 ||
3880
- transitions.failure.timestamp !==
3881
- historyStates[failureHistoryIndex].timestamp ||
3882
- transitions.recovery.timestamp !==
3883
- historyStates[recoveryHistoryIndex].timestamp ||
3884
- transition.timestamp !== artifact.capturedAt ||
3885
- transition.state !== (role === 'failure' ? 'ALARM' : 'OK')
3886
- ) {
3887
- throw new Error(
3888
- 'Reliability collection request, response, resource, or transition is cross-paired.',
3889
- );
3890
- }
3891
- if (
3892
- protectedStage !== undefined &&
3893
- protectedStage !== collectionActiveBinding.target.stage
3894
- ) {
3895
- throw new Error(
3896
- 'Reliability exercise collections crossed protected stages.',
3897
- );
3898
- }
3899
- protectedStage = collectionActiveBinding.target.stage;
3900
- collectionDigests.push(collectionReference.digest);
3901
- } else if (producer.kind !== 'testing-evidence') {
3902
- throw new Error(
3903
- 'Postconditions and cleanup require testing-evidence provenance.',
3904
- );
3905
- }
3906
- if (artifact.status !== statuses[role]) {
3907
- throw new Error('Reliability exercise artifact status is incompatible.');
3908
- }
3909
- if (role === 'postconditions') {
3910
- if (
3911
- !Array.isArray(artifact.checks) ||
3912
- artifact.checks.length !== exercise.postconditions.length ||
3913
- artifact.checks.some(
3914
- (check, index) =>
3915
- check !== 'postcondition-' + String(index + 1) + '-passed',
3916
- )
3917
- ) {
3918
- throw new Error(
3919
- 'Reliability exercise postcondition artifact is incomplete.',
3920
- );
3921
- }
3922
- } else if (artifact.checks !== undefined) {
3923
- throw new Error('Only the postcondition artifact may contain checks.');
3924
- }
3925
- evidence[role] = reference.digest;
3926
- }
3927
- if (
3928
- collectionDigests.length !== 2 ||
3929
- new Set(collectionDigests).size !== 1 ||
3930
- !['staging', 'production'].includes(protectedStage)
3931
- ) {
3932
- throw new Error(
3933
- 'Failure and recovery must come from one independently collected AWS transition chain.',
3934
- );
3935
- }
3936
- if (new Set(Object.values(evidence)).size !== roles.length) {
3937
- throw new Error('Reliability exercise artifacts must be independently captured.');
3938
- }
3939
- const report = {
3940
- artifacts: evidence,
3941
- binding: reportBinding,
3942
- ...(exercise.workload === 'alert-delivery'
3943
- ? { alertDelivery: { state: artifactReference(
3944
- references.recovery,
3945
- 'artifacts.recovery',
3946
- ).value.status } }
3947
- : {}),
3948
- exerciseId: exercise.id,
3949
- kind: 'reliability-failure-recovery-evidence',
3950
- provenance: protectedStage,
3951
- schemaVersion: 1,
3952
- slice: '${name}',
3953
- workload: exercise.workload,
3954
- };
3955
- const reference = writeImmutableArtifact(
3956
- '.ebk/evidence/reliability/exercises',
3957
- report,
3958
- );
3959
- process.stdout.write(JSON.stringify({ ...reference, ...report }) + '\\n');
3960
- `,
3961
- 'scripts/reliability-diagnostic.mjs': `import {
3962
- CloudWatchClient,
3963
- DescribeAlarmsCommand,
3964
- GetMetricDataCommand,
3965
- } from '@aws-sdk/client-cloudwatch';
3966
- import {
3967
- DescribeServicesCommand,
3968
- ECSClient,
3969
- } from '@aws-sdk/client-ecs';
3970
- import {
3971
- DescribeExecutionCommand,
3972
- SFNClient,
3973
- } from '@aws-sdk/client-sfn';
3974
- import {
3975
- GetCallerIdentityCommand,
3976
- STSClient,
3977
- } from '@aws-sdk/client-sts';
3978
- import { readFileSync } from 'node:fs';
3979
- import {
3980
- authorizeDiagnostic,
3981
- validateReliabilityContract,
3982
- } from '@empire-builder-kit/runtime/reliability';
3983
- import {
3984
- activeDeploymentBinding,
3985
- awsPartition,
3986
- authorizedExecutionArn,
3987
- exactKeys,
3988
- readBoundedJson,
3989
- safeToken,
3990
- sha256,
3991
- utc,
3992
- writeImmutableArtifact,
3993
- } from './reliability-evidence-lib.mjs';
3994
-
3995
- const inputPath = process.env.EBK_RELIABILITY_DIAGNOSTIC_INPUT_PATH?.trim();
3996
- if (!inputPath) {
3997
- throw new Error('EBK_RELIABILITY_DIAGNOSTIC_INPUT_PATH is required.');
3998
- }
3999
- const requestInput = readBoundedJson(inputPath, 'Reliability diagnostic input');
4000
- const request = exactKeys(
4001
- requestInput.value,
4002
- ['approval', 'bindingArtifact', 'query', 'source', 'target'],
4003
- 'Reliability diagnostic input',
4004
- );
4005
- const plan = authorizeDiagnostic({
4006
- ...(request.approval === undefined ? {} : { approval: request.approval }),
4007
- source: request.source,
4008
- target: request.target,
4009
- });
4010
- if (plan.approvalRequired) {
4011
- process.stdout.write(JSON.stringify({
4012
- approvalRequired: true,
4013
- expiresAt: plan.expiresAt,
4014
- queryClass: plan.queryClass,
4015
- source: plan.source,
4016
- target: plan.target,
4017
- }) + '\\n');
4018
- process.exit(0);
4019
- }
4020
- const activeBinding = activeDeploymentBinding(
4021
- request.bindingArtifact,
4022
- 'bindingArtifact',
4023
- );
4024
- const capturedBinding = activeBinding.binding;
4025
- const activeResources = activeBinding.resources;
4026
- const bindingTarget = activeBinding.target;
4027
- if (
4028
- bindingTarget.account !== plan.target.account ||
4029
- bindingTarget.region !== plan.target.region ||
4030
- bindingTarget.slice !== plan.target.slice ||
4031
- bindingTarget.stage !== plan.target.stage
4032
- ) {
4033
- throw new Error(
4034
- 'Reliability diagnostic deployment binding does not match the exact target.',
4035
- );
4036
- }
4037
- if (plan.source === 'alarm-state') {
4038
- const query = exactKeys(request.query, ['alarmNames'], 'alarm-state query');
4039
- if (
4040
- !Array.isArray(query.alarmNames) ||
4041
- query.alarmNames.some(
4042
- (value) =>
4043
- !activeResources.alarmNames.includes(
4044
- safeToken(value, 'alarm-state alarm', 255),
4045
- ),
4046
- )
4047
- ) {
4048
- throw new Error(
4049
- 'Alarm-state query is not authorized by the protected deployment.',
4050
- );
4051
- }
4052
- }
4053
- if (
4054
- plan.source === 'sanitized-signal' &&
4055
- request.query?.apiId !== undefined &&
4056
- safeToken(request.query.apiId, 'apiId', 128) !== activeResources.apiId
4057
- ) {
4058
- throw new Error(
4059
- 'Metric query API is not authorized by the protected deployment.',
4060
- );
4061
- }
4062
- if (plan.source === 'resource-metadata') {
4063
- const query = exactKeys(
4064
- request.query,
4065
- ['ecsServices', 'executions'],
4066
- 'resource-metadata query',
4067
- );
4068
- if (!Array.isArray(query.ecsServices) || !Array.isArray(query.executions)) {
4069
- throw new Error(
4070
- 'Resource query is not authorized by the protected deployment.',
4071
- );
4072
- }
4073
- for (const [index, value] of query.ecsServices.entries()) {
4074
- const requested = exactKeys(
4075
- value,
4076
- ['cluster', 'services'],
4077
- 'ecsServices[' + index + ']',
4078
- );
4079
- const cluster = safeToken(
4080
- requested.cluster,
4081
- 'ecsServices[' + index + '].cluster',
4082
- 512,
4083
- );
4084
- const authorized = activeResources.ecsServices.find(
4085
- (entry) => entry.cluster === cluster,
4086
- );
4087
- if (
4088
- !authorized ||
4089
- !Array.isArray(requested.services) ||
4090
- requested.services.some(
4091
- (service) =>
4092
- !authorized.services.includes(
4093
- safeToken(service, 'ecsServices.service', 255),
4094
- ),
4095
- )
4096
- ) {
4097
- throw new Error(
4098
- 'ECS query is not authorized by the protected deployment.',
4099
- );
4100
- }
4101
- }
4102
- for (const [index, value] of query.executions.entries()) {
4103
- const executionArn = safeToken(value, 'executions[' + index + ']', 512);
4104
- if (!authorizedExecutionArn(activeResources, executionArn)) {
4105
- throw new Error(
4106
- 'Step Functions query is not authorized by the protected deployment.',
4107
- );
4108
- }
4109
- }
4110
- }
4111
- const region = plan.target.region;
4112
- const partition = awsPartition(region);
4113
- const identity = await new STSClient({ region }).send(
4114
- new GetCallerIdentityCommand({}),
4115
- );
4116
- if (
4117
- identity.Account !== plan.target.account ||
4118
- !identity.Arn?.startsWith(
4119
- 'arn:' + partition + ':sts::' + plan.target.account + ':',
4120
- )
4121
- ) {
4122
- throw new Error(
4123
- 'AWS caller identity does not match the active reliability target.',
4124
- );
4125
- }
4126
- const capture = async (value, directory) => {
4127
- const reference = writeImmutableArtifact(directory, value);
4128
- process.stdout.write(JSON.stringify({ ...reference, ...value }) + '\\n');
4129
- };
4130
- if (plan.source === 'alarm-state') {
4131
- const query = exactKeys(request.query, ['alarmNames'], 'alarm-state query');
4132
- if (
4133
- !Array.isArray(query.alarmNames) ||
4134
- query.alarmNames.length < 1 ||
4135
- query.alarmNames.length > 32 ||
4136
- new Set(query.alarmNames).size !== query.alarmNames.length
4137
- ) {
4138
- throw new Error('Alarm-state query must name one to 32 exact alarms.');
4139
- }
4140
- const alarmNames = query.alarmNames.map((value, index) =>
4141
- safeToken(value, 'alarmNames[' + index + ']', 255),
4142
- );
4143
- if (
4144
- alarmNames.some(
4145
- (value) => !value.startsWith('${name}-' + plan.target.stage + '-'),
4146
- )
4147
- ) {
4148
- throw new Error('Alarm-state query escaped the exact Slice and stage.');
4149
- }
4150
- const response = await new CloudWatchClient({ region }).send(
4151
- new DescribeAlarmsCommand({
4152
- AlarmNames: alarmNames,
4153
- MaxRecords: alarmNames.length,
4154
- }),
4155
- );
4156
- if (response.NextToken) {
4157
- throw new Error('Alarm-state query exceeded its one-page bound.');
4158
- }
4159
- const alarms = (response.MetricAlarms ?? []).map((alarm) => ({
4160
- actionsEnabled: alarm.ActionsEnabled ?? null,
4161
- alarmArn: alarm.AlarmArn ?? null,
4162
- alarmName: alarm.AlarmName ?? null,
4163
- stateUpdatedTimestamp:
4164
- alarm.StateUpdatedTimestamp?.toISOString?.() ?? null,
4165
- stateValue: alarm.StateValue ?? null,
4166
- }));
4167
- if (
4168
- alarms.length !== alarmNames.length ||
4169
- new Set(alarms.map(({ alarmName }) => alarmName)).size !== alarms.length ||
4170
- alarms.some(
4171
- ({ alarmArn, alarmName }) =>
4172
- !alarmNames.includes(alarmName) ||
4173
- !alarmArn?.startsWith(
4174
- 'arn:' +
4175
- partition +
4176
- ':cloudwatch:' +
4177
- region +
4178
- ':' +
4179
- plan.target.account +
4180
- ':alarm:',
4181
- ),
4182
- )
4183
- ) {
4184
- throw new Error('AWS alarm response did not match the exact query target.');
4185
- }
4186
- await capture(
4187
- {
4188
- alarms,
4189
- binding: capturedBinding,
4190
- bindingDigest: activeBinding.digest,
4191
- capturedAt: new Date().toISOString(),
4192
- kind: 'reliability-alarm-capture',
4193
- schemaVersion: 1,
4194
- slice: '${name}',
4195
- target: plan.target,
4196
- },
4197
- '.ebk/evidence/reliability/diagnostics',
4198
- );
4199
- process.exit(0);
4200
- }
4201
- if (plan.source === 'sanitized-signal') {
4202
- const query = exactKeys(
4203
- request.query,
4204
- ['apiId', 'endTime', 'objectiveId', 'startTime'],
4205
- 'sanitized-signal query',
4206
- );
4207
- const objectiveId = safeToken(query.objectiveId, 'objectiveId', 128);
4208
- const contract = validateReliabilityContract(
4209
- JSON.parse(
4210
- readFileSync(
4211
- new URL('../docs/reliability/slo.json', import.meta.url),
4212
- 'utf8',
4213
- ),
4214
- ),
4215
- );
4216
- const objective = contract.objectives.find(({ id }) => id === objectiveId);
4217
- if (!objective || capturedBinding.workload !== objective.journey) {
4218
- throw new Error(
4219
- 'Metric query workload does not match the exact objective journey.',
4220
- );
4221
- }
4222
- const startTime = utc(query.startTime, 'startTime');
4223
- const endTime = utc(query.endTime, 'endTime');
4224
- const elapsed = Date.parse(endTime) - Date.parse(startTime);
4225
- if (elapsed <= 0 || elapsed > 6 * 60 * 60 * 1000) {
4226
- throw new Error('Metric query window must be positive and at most six hours.');
4227
- }
4228
- const dimensions = [
4229
- { Name: 'Component', Value: 'next-server' },
4230
- { Name: 'Feature', Value: objective.feature },
4231
- { Name: 'Operation', Value: 'request' },
4232
- { Name: 'Slice', Value: '${name}' },
4233
- { Name: 'Stage', Value: plan.target.stage },
4234
- ];
4235
- const metric = (id, metricName, metricDimensions = dimensions) => ({
4236
- Id: id,
4237
- MetricStat: {
4238
- Metric: {
4239
- Dimensions: metricDimensions,
4240
- MetricName: metricName,
4241
- Namespace:
4242
- objective.id === 'api-availability' &&
4243
- metricName !== 'SyntheticGood' &&
4244
- metricName !== 'SyntheticValid'
4245
- ? 'AWS/ApiGateway'
4246
- : 'EBK/${name}',
4247
- },
4248
- Period: 60,
4249
- Stat: 'Sum',
4250
- },
4251
- ReturnData: true,
4252
- });
4253
- const syntheticDimensions = [
4254
- { Name: 'Component', Value: 'synthetic' },
4255
- { Name: 'Feature', Value: 'operations' },
4256
- {
4257
- Name: 'Operation',
4258
- Value:
4259
- objective.id === 'api-availability'
4260
- ? 'api-health'
4261
- : 'web-critical-route',
4262
- },
4263
- { Name: 'Slice', Value: '${name}' },
4264
- { Name: 'Stage', Value: plan.target.stage },
4265
- ];
4266
- const syntheticQueries =
4267
- objective.lowTraffic.mode === 'synthetic'
4268
- ? [
4269
- metric('synthetic_valid', 'SyntheticValid', syntheticDimensions),
4270
- metric('synthetic_good', 'SyntheticGood', syntheticDimensions),
4271
- ]
4272
- : [];
4273
- let metricDataQueries;
4274
- if (objective.id === 'api-availability') {
4275
- const apiId = safeToken(query.apiId, 'apiId', 128);
4276
- if (apiId !== activeResources.apiId) {
4277
- throw new Error(
4278
- 'Metric query API is not authorized by the protected deployment.',
4279
- );
4280
- }
4281
- const apiDimensions = [{ Name: 'ApiId', Value: apiId }];
4282
- metricDataQueries = [
4283
- metric('valid', 'Count', apiDimensions),
4284
- { ...metric('bad', '5xx', apiDimensions), ReturnData: false },
4285
- {
4286
- Expression: 'valid-bad',
4287
- Id: 'good',
4288
- Label: 'Good API events',
4289
- ReturnData: true,
4290
- },
4291
- ...syntheticQueries,
4292
- ];
4293
- } else if (objective.id === 'web-latency') {
4294
- if (query.apiId !== undefined) {
4295
- throw new Error('Web metric capture must not accept an API identity.');
4296
- }
4297
- metricDataQueries = [
4298
- metric('valid', 'OperationValid'),
4299
- metric('good', 'OperationGood'),
4300
- ...syntheticQueries,
4301
- ];
4302
- } else {
4303
- throw new Error(
4304
- 'This objective has no stable-v1 AWS metric capture adapter.',
4305
- );
4306
- }
4307
- const response = await new CloudWatchClient({ region }).send(
4308
- new GetMetricDataCommand({
4309
- EndTime: new Date(endTime),
4310
- MaxDatapoints: 1008,
4311
- MetricDataQueries: metricDataQueries,
4312
- ScanBy: 'TimestampDescending',
4313
- StartTime: new Date(startTime),
4314
- }),
4315
- );
4316
- if (response.NextToken) {
4317
- throw new Error('Metric query exceeded its one-page data-point bound.');
4318
- }
4319
- const idMap = {
4320
- good: 'good',
4321
- synthetic_good: 'synthetic-good',
4322
- synthetic_valid: 'synthetic-valid',
4323
- valid: 'valid',
4324
- };
4325
- const metricResults = (response.MetricDataResults ?? [])
4326
- .filter(({ Id }) => idMap[Id])
4327
- .map((result) => ({
4328
- id: idMap[result.Id],
4329
- status: result.StatusCode ?? null,
4330
- timestamps: (result.Timestamps ?? []).map((value) => value.toISOString()),
4331
- values: result.Values ?? [],
4332
- }));
4333
- if (
4334
- metricResults.length !==
4335
- (objective.lowTraffic.mode === 'synthetic' ? 4 : 2) ||
4336
- new Set(metricResults.map(({ id }) => id)).size !== metricResults.length ||
4337
- !metricResults.some(({ id }) => id === 'valid') ||
4338
- !metricResults.some(({ id }) => id === 'good') ||
4339
- metricResults.some(
4340
- ({ status, timestamps, values }) =>
4341
- status !== 'Complete' ||
4342
- timestamps.length !== values.length ||
4343
- values.length > 1008 ||
4344
- timestamps.some(
4345
- (value) =>
4346
- !Number.isFinite(Date.parse(value)) ||
4347
- Date.parse(value) < Date.parse(startTime) ||
4348
- Date.parse(value) > Date.parse(endTime),
4349
- ) ||
4350
- values.some((value) => !Number.isFinite(value) || value < 0),
4351
- )
4352
- ) {
4353
- throw new Error('AWS metric response is incomplete or outside its bound.');
4354
- }
4355
- const queryDigest = sha256(
4356
- Buffer.from(JSON.stringify({
4357
- endTime,
4358
- metricDataQueries,
4359
- startTime,
4360
- target: plan.target,
4361
- })),
4362
- );
4363
- await capture(
4364
- {
4365
- binding: capturedBinding,
4366
- bindingArtifact: {
4367
- digest: activeBinding.digest,
4368
- path: activeBinding.path,
4369
- },
4370
- capturedAt: new Date().toISOString(),
4371
- kind: 'reliability-metric-capture',
4372
- metricResults,
4373
- objectiveId,
4374
- queryDigest,
4375
- sampleWindow: {
4376
- durationSeconds: elapsed / 1_000,
4377
- end: endTime,
4378
- start: startTime,
4379
- },
4380
- schemaVersion: 1,
4381
- slice: '${name}',
4382
- target: plan.target,
4383
- },
4384
- '.ebk/evidence/reliability/captures',
4385
- );
4386
- process.exit(0);
4387
- }
4388
- if (plan.source === 'resource-metadata') {
4389
- const query = exactKeys(
4390
- request.query,
4391
- ['ecsServices', 'executions'],
4392
- 'resource-metadata query',
4393
- );
4394
- const ecsServices = query.ecsServices ?? [];
4395
- const executions = query.executions ?? [];
4396
- if (
4397
- !Array.isArray(ecsServices) ||
4398
- !Array.isArray(executions) ||
4399
- ecsServices.length > 8 ||
4400
- executions.length > 8 ||
4401
- ecsServices.length + executions.length < 1
4402
- ) {
4403
- throw new Error('Resource query is empty or exceeds eight targets per kind.');
4404
- }
4405
- const resources = [];
4406
- for (const [index, input] of ecsServices.entries()) {
4407
- const target = exactKeys(input, ['cluster', 'services'], 'ecsServices[' + index + ']');
4408
- const cluster = safeToken(target.cluster, 'ecsServices.cluster', 512);
4409
- if (
4410
- !Array.isArray(target.services) ||
4411
- target.services.length < 1 ||
4412
- target.services.length > 10
4413
- ) {
4414
- throw new Error('ECS service query is outside its ten-service bound.');
4415
- }
4416
- const services = target.services.map((value) =>
4417
- safeToken(value, 'ecsServices.service', 255),
4418
- );
4419
- const response = await new ECSClient({ region }).send(
4420
- new DescribeServicesCommand({ cluster, services }),
4421
- );
4422
- if ((response.failures?.length ?? 0) > 0) {
4423
- throw new Error('ECS returned an unresolved reliability target.');
4424
- }
4425
- if (
4426
- response.services?.length !== services.length ||
4427
- new Set(
4428
- (response.services ?? []).map(({ serviceArn }) =>
4429
- serviceArn?.slice(serviceArn.lastIndexOf('/') + 1),
4430
- ),
4431
- ).size !== services.length ||
4432
- response.services.some(
4433
- ({ serviceArn }) =>
4434
- !services.includes(serviceArn?.slice(serviceArn.lastIndexOf('/') + 1)),
4435
- )
4436
- ) {
4437
- throw new Error('ECS response escaped the exact diagnostic target.');
4438
- }
4439
- resources.push(...response.services.map((service) => ({
4440
- desiredCount: service.desiredCount ?? null,
4441
- pendingCount: service.pendingCount ?? null,
4442
- runningCount: service.runningCount ?? null,
4443
- serviceArn: service.serviceArn ?? null,
4444
- status: service.status ?? null,
4445
- })));
4446
- }
4447
- for (const [index, value] of executions.entries()) {
4448
- const executionArn = safeToken(value, 'executions[' + index + ']', 512);
4449
- const response = await new SFNClient({ region }).send(
4450
- new DescribeExecutionCommand({
4451
- executionArn,
4452
- includedData: 'METADATA_ONLY',
4453
- }),
4454
- );
4455
- if (
4456
- response.executionArn !== executionArn ||
4457
- !activeResources.stateMachineArns.includes(response.stateMachineArn)
4458
- ) {
4459
- throw new Error(
4460
- 'Step Functions response escaped the exact diagnostic target.',
4461
- );
4462
- }
4463
- resources.push({
4464
- executionArn: response.executionArn ?? null,
4465
- stateMachineArn: response.stateMachineArn ?? null,
4466
- status: response.status ?? null,
4467
- stopDate: response.stopDate?.toISOString?.() ?? null,
4468
- });
4469
- }
4470
- await capture(
4471
- {
4472
- binding: capturedBinding,
4473
- bindingDigest: activeBinding.digest,
4474
- capturedAt: new Date().toISOString(),
4475
- kind: 'reliability-resource-capture',
4476
- resources,
4477
- schemaVersion: 1,
4478
- slice: '${name}',
4479
- target: plan.target,
4480
- },
4481
- '.ebk/evidence/reliability/diagnostics',
4482
- );
4483
- process.exit(0);
4484
- }
4485
- throw new Error(
4486
- 'This diagnostic source has no stable-v1 read-only AWS query adapter.',
4487
- );
4488
- `,
4489
- 'scripts/incident-remediation.mjs': `import { spawnSync } from 'node:child_process';
4490
- import {
4491
- planRemediation,
4492
- } from '@empire-builder-kit/runtime/reliability';
4493
- import {
4494
- readBoundedJson,
4495
- } from './reliability-evidence-lib.mjs';
4496
-
4497
- const inputPath = process.env.EBK_INCIDENT_REMEDIATION_INPUT_PATH?.trim();
4498
- if (!inputPath) {
4499
- throw new Error('EBK_INCIDENT_REMEDIATION_INPUT_PATH is required.');
4500
- }
4501
- const request = readBoundedJson(
4502
- inputPath,
4503
- 'Incident remediation input',
4504
- ).value;
4505
- const plan = planRemediation(request);
4506
- if (plan.mode === 'report') {
4507
- process.stdout.write(JSON.stringify({
4508
- action: plan.action,
4509
- approvalRequired: true,
4510
- authorized: false,
4511
- execution: plan.execution,
4512
- remediationPlanDigest: plan.remediationPlanDigest,
4513
- target: plan.target,
4514
- }) + '\\n');
4515
- process.exit(0);
4516
- }
4517
- const required = (name) => {
4518
- const value = process.env[name]?.trim();
4519
- if (!value) throw new Error(name + ' is required.');
4520
- return value;
4521
- };
4522
- if (
4523
- process.env.GITHUB_ACTIONS !== 'true' ||
4524
- process.env.GITHUB_REF_PROTECTED !== 'true' ||
4525
- process.env.GITHUB_SHA !== process.env.EBK_APPROVED_COMMIT ||
4526
- !process.env.ACTIONS_ID_TOKEN_REQUEST_URL
4527
- ) {
4528
- throw new Error(
4529
- 'Incident remediation apply requires protected GitHub OIDC on the approved commit.',
4530
- );
4531
- }
4532
- if (
4533
- plan.target.account !== required('AWS_EXPECTED_ACCOUNT_ID') ||
4534
- plan.target.region !== required('AWS_REGION') ||
4535
- plan.target.stage !== required('EBK_STAGE') ||
4536
- plan.target.slice !== '${name}'
4537
- ) {
4538
- throw new Error(
4539
- 'Incident remediation approval does not match the effective target.',
4540
- );
4541
- }
4542
- if (
4543
- !['redrive', 'replay'].includes(plan.action) ||
4544
- plan.execution.adapter !== 'protected-async-recovery'
4545
- ) {
4546
- throw new Error(
4547
- 'This remediation action has no stable-v1 executable adapter.',
4548
- );
4549
- }
4550
- if (
4551
- plan.execution.asyncRecoveryReportDigest !==
4552
- required('EBK_ASYNC_REPORT_DIGEST')
4553
- ) {
4554
- throw new Error(
4555
- 'Incident remediation does not match the distinct async-recovery report.',
4556
- );
4557
- }
4558
- const capability =
4559
- plan.action === 'redrive'
4560
- ? 'bounded-selective-redrive'
4561
- : 'event-replay';
4562
- const result = spawnSync(
4563
- process.execPath,
4564
- ['scripts/protected-async-recovery.mjs'],
4565
- {
4566
- env: {
4567
- ...process.env,
4568
- EBK_ASYNC_CAPABILITY: capability,
4569
- EBK_RECOVERY_ACTION: 'apply',
4570
- },
4571
- stdio: 'inherit',
4572
- },
4573
- );
4574
- if (result.error) throw result.error;
4575
- if (result.status !== 0) process.exit(result.status ?? 1);
4576
- `,
4577
- 'reliability/contract.spec.ts': `import { describe, expect, it } from 'vitest';
4578
- import { createAuthenticatedSession } from '@empire-builder-kit/runtime/auth';
4579
- import {
4580
- createApprovalRequest,
4581
- createDirectAuthorizationPrincipal,
4582
- decideApprovalRequest,
4583
- } from '@empire-builder-kit/runtime/authorization';
4584
- import {
4585
- authorizeDiagnostic,
4586
- candidateIncidentSeverity,
4587
- diagnosticApprovalDigestInput,
4588
- evaluateSlo,
4589
- planRemediation,
4590
- RELIABILITY_APPROVAL_POLICY_VERSION,
4591
- remediationApprovalDigestInput,
4592
- } from '@empire-builder-kit/runtime/reliability';
4593
- import { Reliability } from './contract.js';
4594
-
4595
- const human = (id: string) =>
4596
- createDirectAuthorizationPrincipal({
4597
- id,
4598
- kind: 'admin',
4599
- roles: [],
4600
- scopes: [],
4601
- session: createAuthenticatedSession({
4602
- subject: { id, type: 'user' },
4603
- }),
4604
- });
4605
- const approvedAuthorization = <Action extends string>(
4606
- input: {
4607
- action: Action;
4608
- command: unknown;
4609
- resource: { id?: string; type: string };
4610
- },
4611
- ) => {
4612
- const now = Date.now();
4613
- const pending = createApprovalRequest({
4614
- ...input,
4615
- author: human('human-operator'),
4616
- expiresAt: new Date(now + 30 * 60 * 1_000).toISOString(),
4617
- now: new Date(now - 60 * 1_000).toISOString(),
4618
- policyVersion: RELIABILITY_APPROVAL_POLICY_VERSION,
4619
- slice: '${name}',
4620
- });
4621
- return decideApprovalRequest(pending, {
4622
- approver: human('human-reviewer'),
4623
- expectedRequestDigest: pending.requestDigest,
4624
- now: new Date(now - 30 * 1_000).toISOString(),
4625
- outcome: 'approved',
4626
- reasonReference: 'incident-1-review',
4627
- requiredPolicyVersion: RELIABILITY_APPROVAL_POLICY_VERSION,
4628
- }).request;
4629
- };
4630
-
4631
- describe('${name} reliability contract', () => {
4632
- it('binds owned objectives and never auto-declares SEV-1', () => {
4633
- expect(Reliability.slice).toBe('${name}');
4634
- expect(Reliability.objectives.map(({ id }) => id)).toEqual([
4635
- 'api-availability',
4636
- 'web-latency',
4637
- 'async-delivery-deadline',
4638
- ]);
4639
- expect(candidateIncidentSeverity('critical')).toBe('SEV-2');
4640
- });
4641
-
4642
- it('makes low-traffic data sufficiency explicit', () => {
4643
- const objective = Reliability.objectives[0]!;
4644
- expect(
4645
- evaluateSlo({
4646
- goodEvents: 1,
4647
- objective,
4648
- validEvents: 1,
4649
- }).state,
4650
- ).toBe('data-insufficient');
4651
- });
4652
-
4653
- it('rejects cross-target diagnostic and remediation approvals', () => {
4654
- const target = {
4655
- account: '123456789012',
4656
- region: 'us-east-1',
4657
- slice: '${name}',
4658
- stage: 'production',
4659
- };
4660
- const approvalScope = {
4661
- allowedLogGroups: ['/ebk/production/${name}/api-health'],
4662
- incidentRef: 'incident-1',
4663
- queryClass: 'scoped-errors',
4664
- reason: 'Confirm the bounded failure signature.',
4665
- target: { ...target, slice: 'other-slice' },
4666
- windowEnd: '2026-07-29T12:00:00.000Z',
4667
- windowStart: '2026-07-29T11:30:00.000Z',
4668
- };
4669
- const approval = {
4670
- ...approvalScope,
4671
- authorization: approvedAuthorization(
4672
- diagnosticApprovalDigestInput(approvalScope),
4673
- ),
4674
- };
4675
- expect(() =>
4676
- authorizeDiagnostic({
4677
- approval,
4678
- source: 'bounded-log-query',
4679
- target,
4680
- }),
4681
- ).toThrow('does not match');
4682
- const report = planRemediation({
4683
- action: 'replay',
4684
- cleanup: ['Remove test resources.'],
4685
- execution: {
4686
- adapter: 'protected-async-recovery',
4687
- asyncRecoveryReportDigest: 'a'.repeat(64),
4688
- },
4689
- mode: 'report',
4690
- preconditions: ['The target is still active.'],
4691
- stopConditions: ['Stop on target change.'],
4692
- target,
4693
- verification: ['Verify the critical journey.'],
4694
- });
4695
- expect(() =>
4696
- planRemediation({
4697
- action: 'replay',
4698
- approval: {
4699
- authorization: approvedAuthorization(
4700
- remediationApprovalDigestInput({
4701
- incidentRef: 'incident-1',
4702
- plan: report,
4703
- }),
4704
- ),
4705
- incidentRef: 'incident-1',
4706
- },
4707
- cleanup: ['Remove test resources.'],
4708
- execution: {
4709
- adapter: 'protected-async-recovery',
4710
- asyncRecoveryReportDigest: 'a'.repeat(64),
4711
- },
4712
- mode: 'apply',
4713
- preconditions: ['The target is still active.'],
4714
- stopConditions: ['Stop on target change.'],
4715
- target,
4716
- verification: ['Verify a substituted journey.'],
4717
- }),
4718
- ).toThrow('does not match');
4719
- });
4720
- });
4721
- `,
4722
- };
4723
- }
4724
- //# sourceMappingURL=built-in-plan-reliability-files.js.map