@vesviet/agent-skills 5.8.0 → 5.11.0

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 (454) hide show
  1. package/INDEX.md +35 -22
  2. package/README.md +7 -18
  3. package/VERSION +1 -1
  4. package/adapters/antigravity/ANTIGRAVITY.md +40 -142
  5. package/adapters/antigravity/INDEX_TIER1.json +174 -146
  6. package/adapters/antigravity/a2a-config.template.yaml +1 -1
  7. package/adapters/antigravity/antigravity-tools.md +25 -0
  8. package/adapters/antigravity/role-skill-index.json +175 -58
  9. package/adapters/claude/CLAUDE_ADAPTER.md +3 -7
  10. package/adapters/claude/settings.template.json +18 -3
  11. package/adapters/cursor/README.md +1 -5
  12. package/adapters/cursor/hooks.template.json +4 -2
  13. package/core/contracts/README.md +0 -20
  14. package/core/contracts/schemas/compact-working-state.json +42 -1
  15. package/core/contracts/schemas/ui-component-spec.json +28 -2
  16. package/core/policies/README.md +0 -20
  17. package/core/policies/action-boundaries.yaml +10 -1
  18. package/core/policies/execution-sandbox.md +0 -12
  19. package/core/policies/mcp-tool-map.yaml +28 -0
  20. package/core/roles/3d-graphics-engineer.md +144 -208
  21. package/core/roles/README.md +1 -23
  22. package/core/roles/agent-coordinator.md +28 -147
  23. package/core/roles/agent-discovery-engineer.md +46 -39
  24. package/core/roles/ai-systems-engineer.md +2 -0
  25. package/core/roles/backend-developer.md +22 -117
  26. package/core/roles/cloudflare-engineer.md +1 -1
  27. package/core/roles/data-engineer.md +3 -1
  28. package/core/roles/devops-engineer.md +4 -3
  29. package/core/roles/ecommerce-engineer.md +18 -6
  30. package/core/roles/frontend-developer.md +146 -317
  31. package/core/roles/game-developer.md +2 -1
  32. package/core/roles/mobile-engineer.md +18 -204
  33. package/core/roles/product-manager.md +3 -3
  34. package/core/roles/project-manager.md +5 -5
  35. package/core/roles/references/3d-graphics-engineer-review-checklist.md +109 -109
  36. package/core/roles/references/agent-coordinator-responsibilities.md +120 -0
  37. package/core/roles/references/agent-coordinator-review-checklist.md +22 -4
  38. package/core/roles/references/agent-discovery-engineer-review-checklist.md +29 -20
  39. package/core/roles/references/backend-developer-responsibilities.md +47 -0
  40. package/core/roles/references/backend-developer-review-checklist.md +15 -0
  41. package/core/roles/references/business-analyst-responsibilities.md +2 -2
  42. package/core/roles/references/frontend-developer-responsibilities.md +14 -6
  43. package/core/roles/references/frontend-developer-review-checklist.md +13 -6
  44. package/core/roles/references/mobile-engineer-responsibilities.md +137 -0
  45. package/core/roles/references/mobile-engineer-review-checklist.md +63 -0
  46. package/core/roles/references/reviewer-review-checklist.md +54 -0
  47. package/core/roles/references/sdet-review-checklist.md +53 -0
  48. package/core/roles/references/solution-architect-responsibilities.md +134 -0
  49. package/core/roles/references/sre-review-checklist.md +81 -0
  50. package/core/roles/references/system-engineer-responsibilities.md +124 -0
  51. package/core/roles/references/technical-architect-responsibilities.md +192 -0
  52. package/core/roles/references/technical-architect-review-checklist.md +58 -0
  53. package/core/roles/references/technical-lead-review-checklist.md +65 -0
  54. package/core/roles/references/ui-ux-designer-anti-slop-standards.md +61 -35
  55. package/core/roles/references/ui-ux-designer-responsibilities.md +79 -226
  56. package/core/roles/references/ui-ux-designer-review-checklist.md +102 -116
  57. package/core/roles/references/vietnam-accounting-specialist-review-checklist.md +6 -6
  58. package/core/roles/researcher.md +3 -3
  59. package/core/roles/reviewer.md +2 -2
  60. package/core/roles/role-standard.md +79 -205
  61. package/core/roles/sdet.md +5 -6
  62. package/core/roles/security-engineer.md +4 -3
  63. package/core/roles/solution-architect.md +9 -130
  64. package/core/roles/sre.md +1 -0
  65. package/core/roles/system-engineer.md +15 -155
  66. package/core/roles/task-planner.md +1 -1
  67. package/core/roles/technical-architect.md +15 -244
  68. package/core/roles/technical-lead.md +1 -0
  69. package/core/roles/technical-writer.md +3 -3
  70. package/core/roles/ui-ux-designer.md +158 -303
  71. package/core/roles/vietnam-accounting-specialist.md +20 -20
  72. package/core/rules/README.md +0 -22
  73. package/core/rules/code.md +11 -6
  74. package/core/skills/README.md +12 -25
  75. package/core/skills/agent/agent-delegation/SKILL.md +11 -0
  76. package/core/skills/agent/agent-graph-orchestration/SKILL.md +5 -0
  77. package/core/skills/agent/agent-memory-compaction/SKILL.md +79 -82
  78. package/core/skills/agent/agent-memory-compaction/references/anchored-schema-and-compaction-algorithms.md +74 -115
  79. package/core/skills/agent/agent-model-routing/SKILL.md +2 -0
  80. package/core/skills/agent/agent-observability/SKILL.md +12 -6
  81. package/core/skills/agent/agent-observability/references/session-forensics-7-dimensions.md +41 -0
  82. package/core/skills/agent/agent-panel-meeting/SKILL.md +3 -3
  83. package/core/skills/agent/agent-quality-gate/SKILL.md +9 -0
  84. package/core/skills/agent/configure-agent-commerce/SKILL.md +2 -0
  85. package/core/skills/agent/configure-agent-commerce/examples/ucp-commerce-manifest-and-endpoints.json +55 -0
  86. package/core/skills/agent/configure-agent-commerce/references/acp-ucp-agent-commerce-manifest-specs.md +66 -0
  87. package/core/skills/agent/configure-agent-headers/SKILL.md +3 -0
  88. package/core/skills/agent/configure-agent-skills/SKILL.md +4 -4
  89. package/core/skills/agent/configure-oauth-metadata/SKILL.md +10 -7
  90. package/core/skills/agent/manage-agent-identity/SKILL.md +2 -0
  91. package/core/skills/agent/manage-agent-identity/examples/agent-identity-spire-workload.yaml +72 -0
  92. package/core/skills/agent/manage-agent-identity/references/nhi-lifecycle-and-token-rotation.md +45 -0
  93. package/core/skills/ai/deploy-vllm-inference/SKILL.md +2 -0
  94. package/core/skills/ai/deploy-vllm-inference/examples/vllm-production-serve-config.yaml +22 -0
  95. package/core/skills/ai/deploy-vllm-inference/references/vllm-v1-paged-attention-and-kv-tiering.md +20 -0
  96. package/core/skills/ai/openrouter-task/SKILL.md +5 -5
  97. package/core/skills/ai-agent/context-optimization/SKILL.md +2 -0
  98. package/core/skills/ai-agent/context-optimization/examples/context-pruner-and-reorderer.py +85 -0
  99. package/core/skills/ai-agent/context-optimization/references/token-budgeting-and-attention-allocation.md +47 -0
  100. package/core/skills/ai-agent/memory-hygiene/SKILL.md +13 -0
  101. package/core/skills/ai-agent/memory-hygiene/examples/memory-audit-and-compaction-routine.py +90 -0
  102. package/core/skills/ai-agent/memory-hygiene/references/agent-memory-vault-spec.md +137 -0
  103. package/core/skills/ai-agent/memory-hygiene/references/owasp-asi06-and-memory-poisoning-defense.md +38 -0
  104. package/core/skills/backend/add-api-endpoint/SKILL.md +9 -0
  105. package/core/skills/backend/add-api-endpoint/examples/express-zod-rfc9457-endpoint.md +329 -0
  106. package/core/skills/backend/add-api-endpoint/examples/kratos-go-clean-architecture-endpoint.md +405 -0
  107. package/core/skills/backend/add-api-endpoint/references/idempotency-and-rate-limiting.md +116 -0
  108. package/core/skills/backend/add-event-handler/SKILL.md +12 -1
  109. package/core/skills/backend/add-event-handler/examples/go-outbox-skip-locked-relay.go +97 -0
  110. package/core/skills/backend/add-event-handler/references/transactional-outbox-and-cloudevents.md +42 -0
  111. package/core/skills/backend/add-service-client/SKILL.md +2 -0
  112. package/core/skills/backend/add-service-client/examples/ts-circuit-breaker-full-jitter-client.ts +71 -0
  113. package/core/skills/backend/add-service-client/references/resilient-client-circuit-breaker-specs.md +25 -0
  114. package/core/skills/backend/build-mcp-server/SKILL.md +2 -0
  115. package/core/skills/backend/build-mcp-server/examples/ts-stateless-mcp-server-zod.ts +52 -0
  116. package/core/skills/backend/build-mcp-server/references/mcp-2026-stateless-contract-specs.md +21 -0
  117. package/core/skills/backend/design-caching-and-locking/SKILL.md +83 -0
  118. package/core/skills/backend/design-caching-and-locking/examples/redis-lua-atomic-reservation-fencing.lua +30 -0
  119. package/core/skills/backend/design-caching-and-locking/references/redis-lua-fencing-and-stampede-specs.md +25 -0
  120. package/core/skills/backend/design-caching-and-locking/scripts/verify_lua_atomicity.py +68 -0
  121. package/core/skills/backend/implement-auth/SKILL.md +9 -0
  122. package/core/skills/backend/implement-structured-outputs/SKILL.md +2 -0
  123. package/core/skills/backend/implement-structured-outputs/examples/python-pydantic-structured-output.py +65 -0
  124. package/core/skills/backend/implement-structured-outputs/references/constrained-decoding-and-double-validation.md +18 -0
  125. package/core/skills/backend/optimize-postgres/SKILL.md +9 -0
  126. package/core/skills/backend/scaffold-new-service/SKILL.md +2 -1
  127. package/core/skills/backend/scaffold-new-service/references/deep-modules-and-seams.md +43 -0
  128. package/core/skills/business/elicit-requirements/SKILL.md +2 -0
  129. package/core/skills/business/trace-requirements-impact/SKILL.md +1 -0
  130. package/core/skills/business/write-use-cases/SKILL.md +1 -0
  131. package/core/skills/commerce/handle-checkout-flow/SKILL.md +18 -66
  132. package/core/skills/commerce/handle-checkout-flow/examples/production-checkout-orchestrator.ts +185 -0
  133. package/core/skills/commerce/handle-checkout-flow/references/pci-dss-v4-and-agentic-checkout-specs.md +72 -0
  134. package/core/skills/commerce/integrate-payment-gateway/SKILL.md +22 -58
  135. package/core/skills/commerce/integrate-payment-gateway/examples/resilient-webhook-and-mpp-handler.ts +164 -0
  136. package/core/skills/commerce/integrate-payment-gateway/references/mpp-x402-and-webhook-security-specs.md +47 -0
  137. package/core/skills/commerce/manage-order-fulfillment/SKILL.md +17 -50
  138. package/core/skills/commerce/manage-order-fulfillment/examples/temporal-fulfillment-saga.ts +104 -0
  139. package/core/skills/commerce/manage-order-fulfillment/references/event-sourced-fulfillment-and-carrier-webhooks.md +58 -0
  140. package/core/skills/commerce/manage-product-catalog/SKILL.md +5 -1
  141. package/core/skills/commerce/manage-product-catalog/examples/hybrid-search-and-governance-pipeline.ts +120 -0
  142. package/core/skills/commerce/manage-product-catalog/references/semantic-vector-catalog-and-graphrag.md +54 -0
  143. package/core/skills/content/write-article/SKILL.md +1 -1
  144. package/core/skills/document/docx/SKILL.md +1 -0
  145. package/core/skills/document/pdf/SKILL.md +2 -0
  146. package/core/skills/document/pdf/references/pdf-acroforms-and-pdfplumber-specs.md +54 -0
  147. package/core/skills/document/pdf/scripts/check_fillable_fields.py +144 -0
  148. package/core/skills/document/pdf/scripts/fill_fillable_fields.py +145 -0
  149. package/core/skills/document/xlsx/SKILL.md +1 -0
  150. package/core/skills/documentation/configure-llms-txt/SKILL.md +3 -0
  151. package/core/skills/documentation/configure-llms-txt/examples/canonical-llms-txt-and-full-txt.md +45 -0
  152. package/core/skills/documentation/configure-llms-txt/references/llms-txt-and-llms-full-txt-standard.md +37 -0
  153. package/core/skills/documentation/write-documentation/SKILL.md +4 -1
  154. package/core/skills/documentation/write-documentation/examples/microservice-production-readme-and-api-docs.md +70 -0
  155. package/core/skills/documentation/write-documentation/references/diataxis-framework-and-doc-standards.md +62 -0
  156. package/core/skills/documentation/write-tech-radar/SKILL.md +1 -0
  157. package/core/skills/education/create-exercises/SKILL.md +1 -0
  158. package/core/skills/education/design-learning-plan/SKILL.md +1 -0
  159. package/core/skills/education/grade-and-review/SKILL.md +1 -0
  160. package/core/skills/foundation/accessibility-review/SKILL.md +1 -0
  161. package/core/skills/foundation/ai-risk-assessment/SKILL.md +4 -5
  162. package/core/skills/foundation/ai-risk-assessment/examples/genai-system-risk-register.md +67 -0
  163. package/core/skills/foundation/ai-risk-assessment/references/nist-ai-rmf-and-eu-ai-act-taxonomy.md +49 -0
  164. package/core/skills/foundation/combinatorial-testing/SKILL.md +1 -0
  165. package/core/skills/foundation/conduct-research/SKILL.md +2 -2
  166. package/core/skills/foundation/conduct-research/references/ai-era-source-discipline.md +1 -1
  167. package/core/skills/foundation/create-migration/SKILL.md +10 -0
  168. package/core/skills/foundation/design-review/SKILL.md +9 -10
  169. package/core/skills/foundation/design-ux-flow/SKILL.md +9 -7
  170. package/core/skills/foundation/discernment-nudge/SKILL.md +2 -0
  171. package/core/skills/foundation/hostile-component-stress-testing/SKILL.md +1 -0
  172. package/core/skills/foundation/incident-report/SKILL.md +1 -0
  173. package/core/skills/foundation/plan-technical-delivery/SKILL.md +3 -1
  174. package/core/skills/foundation/playwright-evidence-qa/SKILL.md +1 -0
  175. package/core/skills/foundation/refactor-legacy-code/SKILL.md +84 -0
  176. package/core/skills/foundation/refactor-legacy-code/examples/characterization-test-seam-extraction.py +34 -0
  177. package/core/skills/foundation/refactor-legacy-code/references/strangler-fig-seams-and-characterization-tests.md +17 -0
  178. package/core/skills/foundation/refactor-legacy-code/scripts/check_refactor_blast_radius.py +63 -0
  179. package/core/skills/foundation/release-notes/SKILL.md +3 -3
  180. package/core/skills/foundation/release-notes/examples/enterprise-platform-release-notes.md +42 -0
  181. package/core/skills/foundation/release-notes/references/keep-a-changelog-and-semver-governance.md +43 -0
  182. package/core/skills/foundation/systematic-debugging/SKILL.md +15 -0
  183. package/core/skills/foundation/webapp-server-runner/SKILL.md +1 -0
  184. package/core/skills/foundation/write-product-brief/SKILL.md +1 -0
  185. package/core/skills/foundation/write-tests/SKILL.md +9 -0
  186. package/core/skills/foundation/write-tests/examples/anti-tautological-tdd-walkthrough.md +204 -0
  187. package/core/skills/foundation/write-tests/examples/testcontainers-kratos-integration-test.md +186 -0
  188. package/core/skills/foundation/write-tests/references/contract-and-chaos-testing.md +187 -0
  189. package/core/skills/frontend/INDEX.json +16 -0
  190. package/core/skills/frontend/add-page-route/SKILL.md +10 -8
  191. package/core/skills/frontend/add-page-route/examples/streaming-rsc-page-with-view-transition.tsx +133 -0
  192. package/core/skills/frontend/add-page-route/references/rsc-routing-and-view-transitions.md +72 -0
  193. package/core/skills/frontend/add-ui-component/SKILL.md +4 -1
  194. package/core/skills/frontend/add-ui-component/examples/compound-dialog-and-form-actions.tsx +193 -0
  195. package/core/skills/frontend/add-ui-component/references/react19-component-standards-and-anti-slop.md +55 -0
  196. package/core/skills/frontend/component-composition/SKILL.md +12 -1
  197. package/core/skills/frontend/component-composition/examples/headless-combobox-compound-component.tsx +207 -0
  198. package/core/skills/frontend/design-md-specification/SKILL.md +5 -0
  199. package/core/skills/frontend/design-system-engineering/SKILL.md +4 -2
  200. package/core/skills/frontend/frontend-micro-polish/SKILL.md +1 -0
  201. package/core/skills/frontend/frontend-testing/SKILL.md +4 -1
  202. package/core/skills/frontend/frontend-testing/examples/playwright-e2e-with-msw-and-axe.spec.ts +87 -0
  203. package/core/skills/frontend/frontend-testing/references/playwright-msw-and-a11y-testing-standards.md +78 -0
  204. package/core/skills/frontend/implement-ai-disclosure/SKILL.md +119 -0
  205. package/core/skills/frontend/implement-view-transitions/SKILL.md +1 -0
  206. package/core/skills/frontend/implement-webmcp/SKILL.md +7 -4
  207. package/core/skills/frontend/implement-webmcp/examples/webmcp-provider-and-hitl-modal.tsx +163 -0
  208. package/core/skills/frontend/implement-webmcp/references/webmcp-architecture-and-hitl-security.md +48 -0
  209. package/core/skills/frontend/integrate-api-client/SKILL.md +12 -12
  210. package/core/skills/frontend/integrate-api-client/examples/orval-query-and-streaming-mutation.ts +102 -0
  211. package/core/skills/frontend/integrate-api-client/references/orval-tanstack-query-and-streaming-specs.md +57 -0
  212. package/core/skills/frontend/interactive-component-workbench/SKILL.md +1 -0
  213. package/core/skills/frontend/motion-performance-engineering/SKILL.md +1 -0
  214. package/core/skills/frontend/setup-design-system/SKILL.md +6 -3
  215. package/core/skills/frontend/setup-design-system/examples/tailwind-v4-theme-and-dtcg-tokens.css +87 -0
  216. package/core/skills/frontend/setup-design-system/references/tailwind-v4-oklch-and-dtcg-tokens.md +61 -0
  217. package/core/skills/frontend/setup-visual-regression/SKILL.md +8 -5
  218. package/core/skills/frontend/setup-visual-regression/examples/visual-regression-playwright.config.ts +83 -0
  219. package/core/skills/frontend/setup-visual-regression/references/visual-regression-docker-and-masking-specs.md +46 -0
  220. package/core/skills/frontend/ui-ux-designer-anti-slop-standards.md +64 -42
  221. package/core/skills/frontend/web-quality-audit/SKILL.md +1 -0
  222. package/core/skills/gamedev/abstract-input-actions/SKILL.md +2 -0
  223. package/core/skills/gamedev/abstract-input-actions/examples/input-action-manager.ts +85 -0
  224. package/core/skills/gamedev/abstract-input-actions/references/action-mapping-and-analog-deadzones.md +54 -0
  225. package/core/skills/gamedev/architect-ecs-systems/SKILL.md +2 -0
  226. package/core/skills/gamedev/architect-ecs-systems/examples/bevy-flecs-combat-system.rs +73 -0
  227. package/core/skills/gamedev/architect-ecs-systems/references/data-oriented-design-and-archetype-ecs.md +39 -0
  228. package/core/skills/gamedev/author-game-ai/SKILL.md +2 -0
  229. package/core/skills/gamedev/author-game-ai/examples/modular-behavior-tree-ai.ts +98 -0
  230. package/core/skills/gamedev/author-game-ai/references/behavior-trees-and-utility-ai-curves.md +47 -0
  231. package/core/skills/gamedev/configure-physics-collision/SKILL.md +2 -0
  232. package/core/skills/gamedev/configure-physics-collision/examples/kinematic-physics-substepping.cpp +100 -0
  233. package/core/skills/gamedev/configure-physics-collision/references/continuous-collision-detection-and-substepping.md +50 -0
  234. package/core/skills/gamedev/develop-gameplay-systems/SKILL.md +2 -0
  235. package/core/skills/gamedev/develop-gameplay-systems/examples/kinematic-character-controller.gd +86 -0
  236. package/core/skills/gamedev/develop-gameplay-systems/references/deterministic-gameplay-state-machines.md +42 -0
  237. package/core/skills/gamedev/implement-save-persistence/SKILL.md +2 -0
  238. package/core/skills/gamedev/implement-save-persistence/examples/versioned-save-manager.ts +127 -0
  239. package/core/skills/gamedev/implement-save-persistence/references/versioned-save-schemas-and-checksums.md +44 -0
  240. package/core/skills/gamedev/render-webgl-threejs/SKILL.md +14 -10
  241. package/core/skills/gamedev/render-webgl-threejs/examples/production-threejs-webgpu-scene.ts +116 -0
  242. package/core/skills/gamedev/render-webgl-threejs/references/webgpu-threejs-pbr-pipeline.md +72 -0
  243. package/core/skills/legal-compliance/audit-ai-compliance/SKILL.md +1 -0
  244. package/core/skills/legal-compliance/draft-legal-opinion/SKILL.md +1 -0
  245. package/core/skills/legal-compliance/manage-vietnam-legal/SKILL.md +1 -0
  246. package/core/skills/meetings-analysis/analyze-business-requirements/SKILL.md +1 -0
  247. package/core/skills/meetings-analysis/analyze-data/SKILL.md +1 -0
  248. package/core/skills/meetings-analysis/meeting-review/SKILL.md +1 -0
  249. package/core/skills/mmo/analyze-campaign-roi/SKILL.md +2 -0
  250. package/core/skills/mmo/analyze-campaign-roi/examples/campaign-roi-and-roas-dashboard.py +80 -0
  251. package/core/skills/mmo/analyze-campaign-roi/references/multi-touch-attribution-and-cpa-analytics.md +33 -0
  252. package/core/skills/mmo/create-automation-script/SKILL.md +2 -0
  253. package/core/skills/mmo/create-automation-script/examples/stealth-browser-automation-flow.ts +65 -0
  254. package/core/skills/mmo/create-automation-script/references/stealth-cdp-and-behavioral-mimicry.md +37 -0
  255. package/core/skills/mmo/deploy-mmo-infrastructure/SKILL.md +3 -0
  256. package/core/skills/mmo/deploy-mmo-infrastructure/examples/proxy-health-probe-and-rotation-daemon.py +75 -0
  257. package/core/skills/mmo/deploy-mmo-infrastructure/references/proxy-pool-rotation-and-anti-detect-specs.md +45 -0
  258. package/core/skills/mmo/deploy-proxyware-fleet/SKILL.md +3 -0
  259. package/core/skills/mmo/deploy-proxyware-fleet/examples/docker-compose-depin-light-node-fleet.yaml +52 -0
  260. package/core/skills/mmo/deploy-proxyware-fleet/references/depin-bandwidth-monetization-node-specs.md +43 -0
  261. package/core/skills/mmo/generate-mmo-content/SKILL.md +2 -0
  262. package/core/skills/mmo/generate-mmo-content/examples/pseo-programmatic-page-generator.ts +76 -0
  263. package/core/skills/mmo/generate-mmo-content/references/pseo-landing-pages-and-social-video-hooks.md +39 -0
  264. package/core/skills/mmo/manage-mmo-assets/SKILL.md +2 -0
  265. package/core/skills/mmo/manage-mmo-assets/examples/mmo-asset-vault-manager.py +63 -0
  266. package/core/skills/mmo/manage-mmo-assets/references/mmo-asset-rbac-and-vault-isolation.md +38 -0
  267. package/core/skills/mmo/setup-tracking-system/SKILL.md +2 -0
  268. package/core/skills/mmo/setup-tracking-system/examples/meta-capi-s2s-event-dispatcher.ts +79 -0
  269. package/core/skills/mmo/setup-tracking-system/references/server-to-server-postback-and-capi-specs.md +45 -0
  270. package/core/skills/mobile/deploy-mobile-app/SKILL.md +1 -0
  271. package/core/skills/mobile/develop-mobile-app/SKILL.md +1 -0
  272. package/core/skills/platform/add-telemetry-instrumentation/SKILL.md +2 -0
  273. package/core/skills/platform/add-telemetry-instrumentation/examples/kratos-otel-middleware-instrumentation.go +87 -0
  274. package/core/skills/platform/add-telemetry-instrumentation/references/opentelemetry-semantic-conventions-2026.md +37 -0
  275. package/core/skills/platform/agents-sdk/SKILL.md +1 -0
  276. package/core/skills/platform/aws-infrastructure/SKILL.md +2 -0
  277. package/core/skills/platform/aws-infrastructure/examples/opentofu-eks-pod-identity-vpc.tf +101 -0
  278. package/core/skills/platform/aws-infrastructure/references/opentofu-aws-zero-trust-and-irsa.md +40 -0
  279. package/core/skills/platform/cloudflare-email-service/SKILL.md +2 -2
  280. package/core/skills/platform/configure-ci-cd-pipeline/SKILL.md +83 -0
  281. package/core/skills/platform/configure-ci-cd-pipeline/examples/hardened-ci-matrix-workflow.yml +33 -0
  282. package/core/skills/platform/configure-ci-cd-pipeline/references/github-actions-sha-pinning-and-slsa-specs.md +22 -0
  283. package/core/skills/platform/configure-ci-cd-pipeline/scripts/audit_workflow_pinning.py +74 -0
  284. package/core/skills/platform/debug-runtime-platform/SKILL.md +1 -2
  285. package/core/skills/platform/debug-workers-edge/SKILL.md +2 -2
  286. package/core/skills/platform/durable-objects/SKILL.md +1 -0
  287. package/core/skills/platform/orchestrate-chaos-experiment/SKILL.md +1 -0
  288. package/core/skills/platform/sandbox-sdk/SKILL.md +1 -0
  289. package/core/skills/platform/setup-deployment/SKILL.md +6 -2
  290. package/core/skills/platform/setup-deployment/examples/kustomize-production-service-manifests.yaml +123 -0
  291. package/core/skills/platform/setup-deployment/references/interactive-hitl-wizard.md +55 -0
  292. package/core/skills/platform/setup-deployment/references/k8s-gitops-and-kustomize-invariants.md +40 -0
  293. package/core/skills/platform/setup-gpu-finops/SKILL.md +2 -0
  294. package/core/skills/platform/setup-gpu-finops/examples/gpu-finops-prometheus-rules.yaml +23 -0
  295. package/core/skills/platform/setup-gpu-finops/references/dcgm-kubecost-gpu-attribution-specs.md +16 -0
  296. package/core/skills/platform/setup-llm-gateway/SKILL.md +2 -0
  297. package/core/skills/platform/setup-llm-gateway/examples/litellm-gateway-config.yaml +28 -0
  298. package/core/skills/platform/setup-llm-gateway/references/litellm-routing-budget-failover-specs.md +16 -0
  299. package/core/skills/platform/supply-chain-security/SKILL.md +3 -2
  300. package/core/skills/platform/supply-chain-security/examples/github-actions-sbom-cosign.yaml +57 -0
  301. package/core/skills/platform/supply-chain-security/references/slsa-provenance-and-sbom-sigstore.md +60 -0
  302. package/core/skills/platform/turnstile-spin/SKILL.md +2 -2
  303. package/core/skills/platform/web-perf/SKILL.md +2 -2
  304. package/core/skills/platform/workers-best-practices/SKILL.md +1 -0
  305. package/core/skills/platform/wrangler/SKILL.md +1 -0
  306. package/core/skills/product/build-story-map/SKILL.md +3 -0
  307. package/core/skills/product/define-product-strategy/SKILL.md +1 -0
  308. package/core/skills/product/model-saas-metrics/SKILL.md +1 -0
  309. package/core/skills/product/prioritize-roadmap/SKILL.md +1 -0
  310. package/core/skills/repo-ops/commit-code/SKILL.md +1 -0
  311. package/core/skills/repo-ops/navigate-service/SKILL.md +28 -132
  312. package/core/skills/repo-ops/navigate-service/examples/service-boundary-map-example.md +14 -0
  313. package/core/skills/repo-ops/navigate-service/references/service-topology-mapping-guide.md +18 -0
  314. package/core/skills/repo-ops/review-code/SKILL.md +12 -2
  315. package/core/skills/repo-ops/review-code/examples/adversarial-two-axis-pr-review.md +167 -0
  316. package/core/skills/repo-ops/review-code/examples/ai-vibe-slop-remediation.md +220 -0
  317. package/core/skills/repo-ops/review-code/references/supply-chain-and-migration-safety.md +103 -0
  318. package/core/skills/repo-ops/review-service/SKILL.md +4 -1
  319. package/core/skills/repo-ops/review-service/examples/service-release-audit-report.md +21 -0
  320. package/core/skills/repo-ops/review-service/references/release-readiness-audit-rubric.md +21 -0
  321. package/core/skills/repo-ops/troubleshoot-service/SKILL.md +1 -0
  322. package/core/skills/security-data/database-maintenance/SKILL.md +1 -1
  323. package/core/skills/security-data/manage-secrets/SKILL.md +2 -0
  324. package/core/skills/security-data/manage-secrets/examples/external-secrets-vault-crds.yaml +53 -0
  325. package/core/skills/security-data/manage-secrets/references/zero-trust-secret-rotation-and-eso.md +30 -0
  326. package/core/skills/security-data/manage-vietnam-accounting/SKILL.md +8 -7
  327. package/core/skills/security-data/prompt-injection-defense/SKILL.md +2 -0
  328. package/core/skills/security-data/prompt-injection-defense/examples/bounded-tool-execution-wrapper.py +78 -0
  329. package/core/skills/security-data/prompt-injection-defense/references/prompt-injection-taxonomy-and-delimiters.md +37 -0
  330. package/core/skills/security-data/reverse-engineer-binary/SKILL.md +3 -0
  331. package/core/skills/security-data/reverse-engineer-binary/examples/binary-triage-and-vulnerability-dossier.md +58 -0
  332. package/core/skills/security-data/reverse-engineer-binary/references/ghidra-radare2-and-rea-evidence-ledgers.md +43 -0
  333. package/core/skills/security-data/security-audit/SKILL.md +3 -1
  334. package/core/skills/security-data/security-audit/examples/enterprise-service-security-audit-report.md +54 -0
  335. package/core/skills/security-data/security-audit/references/owasp-asi-and-cvss4-threat-modeling.md +39 -0
  336. package/core/skills/security-data/skill-preflight-ast-check/SKILL.md +3 -0
  337. package/core/skills/security-data/skill-preflight-ast-check/references/ast-lethal-trifecta-and-static-vetting.md +38 -0
  338. package/core/skills/security-data/skill-preflight-ast-check/scripts/scan-skill-ast.py +127 -0
  339. package/core/skills/seo/audit-technical-seo/SKILL.md +1 -0
  340. package/core/skills/seo/implement-schema-markup/SKILL.md +1 -0
  341. package/core/workflows/README.md +0 -20
  342. package/overlays/README.md +2 -22
  343. package/overlays/astro-cloudflare/README.md +0 -20
  344. package/overlays/astro-cloudflare/rules/astro-cloudflare-conventions.md +0 -31
  345. package/overlays/b2b-catalog-golf/README.md +0 -20
  346. package/overlays/b2b-catalog-golf/rules/golf-project-rules.md +0 -31
  347. package/overlays/b2b-catalog-golf/skills/develop-b2b-golf-feature/SKILL.md +1 -0
  348. package/overlays/b2b-factory-catalog/README.md +0 -20
  349. package/overlays/b2b-factory-catalog/rules/icm-project-rules.md +0 -31
  350. package/overlays/b2b-factory-catalog/skills/develop-b2b-catalog-feature/SKILL.md +1 -0
  351. package/overlays/b2b-sport-catalog/README.md +0 -20
  352. package/overlays/b2b-sport-catalog/rules/sport-project-rules.md +0 -31
  353. package/overlays/cad-projection/README.md +0 -20
  354. package/overlays/cad-projection/rules/cad-conventions.md +0 -20
  355. package/overlays/cad-projection/skills/isometric-svg-projection/SKILL.md +1 -0
  356. package/overlays/data-analyst-stack/README.md +0 -20
  357. package/overlays/data-analyst-stack/rules/metric-dashboard-templates.md +0 -31
  358. package/overlays/data-analyst-stack/rules/stack-conventions.md +0 -31
  359. package/overlays/data-warehouse/README.md +0 -22
  360. package/overlays/data-warehouse/learning/learning-conventions.md +0 -31
  361. package/overlays/data-warehouse/learning/phase-roadmap.md +0 -31
  362. package/overlays/data-warehouse/rules/amis-accounting-standards.md +0 -33
  363. package/overlays/data-warehouse/rules/duckdb-concurrency.md +0 -37
  364. package/overlays/data-warehouse/rules/pii-scrubbing.md +0 -37
  365. package/overlays/data-warehouse/rules/stocktake-tolerance.md +0 -33
  366. package/overlays/ecommerce-microservices/README.md +22 -35
  367. package/overlays/ecommerce-microservices/config/README.md +3 -1
  368. package/overlays/ecommerce-microservices/rules/README.md +2 -1
  369. package/overlays/ecommerce-microservices/rules/microservices-conventions.md +30 -0
  370. package/overlays/ecommerce-microservices/skills/README.md +1 -1
  371. package/overlays/ecommerce-microservices/workflows/README.md +3 -1
  372. package/overlays/fintech-compliance/README.md +0 -20
  373. package/overlays/fintech-compliance/rules/credit-scorecard-rules.md +0 -20
  374. package/overlays/fintech-compliance/skills/build-credit-scorecard/SKILL.md +1 -0
  375. package/overlays/go-microservices/README.md +1 -21
  376. package/overlays/go-microservices/rules/go-conventions.md +0 -31
  377. package/overlays/hugo-authority-content/README.md +0 -20
  378. package/overlays/hugo-authority-content/roles/README.md +0 -20
  379. package/overlays/hugo-authority-content/rules/content-brand.md +0 -30
  380. package/overlays/hugo-authority-content/rules/link-topology.md +0 -30
  381. package/overlays/hugo-authority-content/rules/seo-authority.md +0 -30
  382. package/overlays/hugo-authority-content/rules/technical-article-2027.md +0 -30
  383. package/overlays/hugo-authority-content/skills/audit-technical-article/SKILL.md +1 -0
  384. package/overlays/hugo-authority-content/skills/write-hugo-twin-content/SKILL.md +1 -0
  385. package/overlays/hugo-authority-content/workflows/README.md +0 -20
  386. package/overlays/hvac-authority-content/README.md +0 -20
  387. package/overlays/hvac-authority-content/config/collections.md +0 -22
  388. package/overlays/hvac-authority-content/rules/content-schema.md +0 -30
  389. package/overlays/hvac-authority-content/rules/hvac-engineering-standards.md +0 -30
  390. package/overlays/hvac-authority-content/rules/silo-linking.md +0 -30
  391. package/overlays/hvac-authority-content/skills/write-hvac-authority-content/SKILL.md +1 -0
  392. package/overlays/hvac-authority-content/workflows/publish-hvac-content.md +0 -22
  393. package/overlays/laravel-ecommerce/README.md +0 -20
  394. package/overlays/laravel-ecommerce/rules/elomus-design-system.md +0 -31
  395. package/overlays/laravel-ecommerce/rules/laravel-ecommerce-rules.md +0 -31
  396. package/overlays/laravel-ecommerce/skills/develop-laravel-ecommerce-feature/SKILL.md +1 -0
  397. package/overlays/laravel-filament/README.md +0 -20
  398. package/overlays/laravel-filament/rules/laravel-conventions.md +0 -31
  399. package/overlays/laravel-filament/skills/develop-laravel-feature/SKILL.md +1 -0
  400. package/overlays/livestream-web/README.md +0 -20
  401. package/overlays/livestream-web/rules/livestream-web-ux-conventions.md +0 -31
  402. package/overlays/obj-configurator/README.md +0 -20
  403. package/overlays/obj-configurator/rules/obj-project-rules.md +0 -31
  404. package/overlays/obj-configurator/skills/develop-obj-feature/SKILL.md +1 -0
  405. package/overlays/r3f-stack/README.md +0 -20
  406. package/overlays/r3f-stack/rules/stub.md +0 -31
  407. package/overlays/r3f-stack/skills/debug-3d-scene/SKILL.md +4 -2
  408. package/overlays/r3f-stack/skills/integrate-r3f-three-legacy/SKILL.md +6 -5
  409. package/overlays/r3f-stack/skills/optimize-3d-assets/SKILL.md +4 -3
  410. package/overlays/real-estate-content/README.md +0 -20
  411. package/overlays/real-estate-content/roles/README.md +0 -20
  412. package/overlays/real-estate-content/rules/affiliate-links.md +0 -31
  413. package/overlays/real-estate-content/rules/content-schema.md +0 -31
  414. package/overlays/real-estate-content/rules/seo-baseline.md +0 -31
  415. package/overlays/real-estate-content/skills/write-real-estate-astro-data/SKILL.md +1 -0
  416. package/overlays/real-estate-content/workflows/README.md +0 -20
  417. package/overlays/security-research/README.md +0 -20
  418. package/overlays/security-research/rules/reverse-engineering-rules.md +0 -20
  419. package/overlays/seo-publishing/README.md +1 -21
  420. package/overlays/seo-publishing/rules/publish-log-conventions.md +0 -31
  421. package/overlays/seo-publishing/rules/publishing-cadence.md +0 -31
  422. package/overlays/seo-publishing/rules/site-mix-and-cannibalization.md +0 -31
  423. package/overlays/seo-publishing/rules/topic-board-template.md +0 -31
  424. package/overlays/ui-design-system/README.md +0 -20
  425. package/overlays/ui-design-system/rules/handoff-conventions.md +0 -31
  426. package/package.json +2 -2
  427. package/packs/README.md +3 -9
  428. package/packs/ecommerce-team/manifest.yaml +1 -1
  429. package/core/skills/commerce/2026_STANDARDS_SUMMARY.md +0 -316
  430. package/core/skills/commerce/handle-checkout-flow/UPGRADE_PLAN_2026.md +0 -99
  431. package/core/skills/commerce/integrate-payment-gateway/UPGRADE_PLAN_2026.md +0 -128
  432. package/core/skills/commerce/manage-order-fulfillment/UPGRADE_PLAN_2026.md +0 -136
  433. package/core/skills/commerce/manage-product-catalog/UPGRADE_PLAN_2026.md +0 -130
  434. package/core/skills/education/2026_STANDARDS_SUMMARY.md +0 -290
  435. package/core/skills/education/create-exercises/UPGRADE_PLAN_2026.md +0 -115
  436. package/core/skills/education/design-learning-plan/UPGRADE_PLAN_2026.md +0 -140
  437. package/core/skills/education/grade-and-review/UPGRADE_PLAN_2026.md +0 -141
  438. package/core/skills/frontend/2026_STANDARDS_SUMMARY.md +0 -345
  439. package/core/skills/frontend/add-page-route/UPGRADE_PLAN_2026.md +0 -102
  440. package/core/skills/frontend/add-ui-component/UPGRADE_PLAN_2026.md +0 -114
  441. package/core/skills/frontend/component-composition/UPGRADE_PLAN_2026.md +0 -103
  442. package/core/skills/frontend/frontend-testing/UPGRADE_PLAN_2026.md +0 -137
  443. package/core/skills/frontend/implement-view-transitions/UPGRADE_PLAN_2026.md +0 -118
  444. package/core/skills/frontend/implement-webmcp/UPGRADE_PLAN_2026.md +0 -108
  445. package/core/skills/frontend/integrate-api-client/UPGRADE_PLAN_2026.md +0 -118
  446. package/core/skills/frontend/setup-design-system/UPGRADE_PLAN_2026.md +0 -123
  447. package/core/skills/frontend/setup-visual-regression/UPGRADE_PLAN_2026.md +0 -121
  448. package/core/skills/meetings-analysis/2026_STANDARDS_SUMMARY.md +0 -236
  449. package/core/skills/meetings-analysis/analyze-business-requirements/UPGRADE_PLAN_2026.md +0 -97
  450. package/core/skills/meetings-analysis/analyze-data/UPGRADE_PLAN_2026.md +0 -143
  451. package/core/skills/meetings-analysis/meeting-review/UPGRADE_PLAN_2026.md +0 -125
  452. package/core/skills/mobile/2026_STANDARDS_SUMMARY.md +0 -209
  453. package/core/skills/mobile/deploy-mobile-app/UPGRADE_PLAN_2026.md +0 -122
  454. package/core/skills/mobile/develop-mobile-app/UPGRADE_PLAN_2026.md +0 -141
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: handle-checkout-flow
3
3
  description: Design and implement the end-to-end checkout flow including cart management, tax and shipping calculation, discount/coupon application, and order confirmation. Use when building or fixing any step in the purchase funnel from cart to payment confirmation.
4
+ version: "1.0.0"
4
5
  allowed-tools: [read_file, write_file, edit_file, create_file, search_code, run_tests, run_linter, run_build, fetch]
5
6
  ---
6
7
 
@@ -79,75 +80,24 @@ Define the full funnel before building:
79
80
  - on failure: release inventory lock, surface payment error, allow retry without re-entering non-payment data
80
81
  - **agentic checkout**: headless execution, structured responses, spending limit enforcement
81
82
 
82
- ## 2026 Agentic Checkout Patterns
83
+ ## Red Flags
83
84
 
84
- ### 2026: Agentic Checkout Architecture (ACP/UCP)
85
-
86
- Agentic Checkout enables AI agents to autonomously execute purchase transactions under the Agentic Commerce Protocol (ACP) and Universal Commerce Protocol (UCP):
87
-
88
- - **ACP** (OpenAI + Stripe, Sep 2025): Agentic Commerce Protocol, Instant Checkout in ChatGPT, cart/feed/orders/auth/MCP support
89
- - **UCP** (Google + partners, Jan 2026): Universal Commerce Protocol, Apache 2.0, compatible with A2A/AP2/MCP, v2026-08-25 multi-vertical/grocery/3DS2/payment schedules/split payments/loyalty
90
- - **Authorization & Limits**: Pre-authorization gates and spending limits per agent session or customer ID
91
- - **Merchant of Record (MoR)**: Clear MoR assignments for fraud liability, chargebacks, regional taxes
92
- - **Programmatic Checkout**: Headless execution without interactive browser sessions, standardized structured responses
93
-
94
- ### 2026: Address Validation Lifecycle (Mandatory)
95
-
96
- Validating the shipping address is a mandatory, isolated step that must occur BEFORE tax calculation or shipping carrier requests:
97
-
98
- - **API Standards**: Google Maps Address Validation, Loqate, Smarty Streets
99
- - **Error Handling**: Precise subcodes for missing apartment number, invalid zip codes
100
- - **Gate**: Reject tax/shipping calls if validation fails
101
-
102
- ### 2026: Stripe Tax Integration and Decision Tree
103
-
104
- Selecting the correct tax calculation service depends on the merchant's scale, transaction volume, and operational context:
105
-
106
- - **Stripe Tax**: Startups/mid-market within Stripe ecosystem, quick integration
107
- - **TaxJar**: Multi-channel merchants (Shopify + Custom Web App), moderate volume, standard ERP
108
- - **Avalara AvaTax**: Enterprise, high volume, complex Nexus, custom ERP, localized tax
109
-
110
- ### 2026: Economic Nexus Threshold Monitoring
111
-
112
- Merchants must actively track regional sales thresholds to ensure compliance with local tax registration laws:
113
-
114
- - **Nexus Monitoring**: Track US state-by-state transaction count and sales volume programmatically
115
- - **Alerting**: Alert at 80% of any state's economic nexus threshold (e.g., 200 transactions or $100,000 sales)
116
- - **Most states**: $100K sales OR 200 transactions (many dropped transaction count)
117
- - **Auto-registration**: Stripe Tax / TaxJar offer automated registration workflows
118
-
119
- ### 2026: Vietnam Decree 248/2026/ND-CP Compliance
120
-
121
- Effective July 1, 2026 (electronic ID verification from Jan 1, 2027):
122
-
123
- - **Seller Verification**: Platform must verify seller identity before allowing transactions
124
- - **Platform Obligations**: Disclose rights/obligations, service standards, pricing, promotions, security, complaints
125
- - **Affiliate Transparency**: All parties disclose roles, links, referral codes, responsibilities
126
- - **Electronic ID Verification**: Sellers and livestream sellers from Jan 1, 2027
85
+ | Rationalization Thought | Reality & Risk | Positive Corrective Action |
86
+ | :--- | :--- | :--- |
87
+ | "Client cart payload already contains discounted total; re-querying is duplicate work." | Trivial request tampering enables \$0.01 purchases by humans or compromised agents. | Recalculate prices, taxes, coupons, and shipping strictly server-side before charge. |
88
+ | "Skip address validation for fast digital/quick-buy paths." | Wrong tax jurisdiction calculation, carrier surcharge fees, and failed deliveries. | Run mandatory address validation before any tax/shipping API call on physical orders. |
89
+ | "Decrement stock at add-to-cart or ignore race locks on coupon usage." | Denial-of-inventory attacks and `SELECT`-then-`UPDATE` coupon over-redemption races. | Use TTL reservations and transactional `SELECT ... FOR UPDATE` / Redis Lua fencing. |
90
+ | "Skip SRI hashes on payment scripts because CSP is already configured." | Violates PCI DSS v4.0.1 Req 6.4.3 / 11.6.1 against Magecart script injection. | Enforce SRI hashes, strict CSP nonces, and automated tamper detection monitoring. |
127
91
 
128
92
  ## Checklist
129
93
 
130
- - [ ] cart totals recalculated server-side before every charge
131
- - [ ] inventory availability re-validated at checkout submission
132
- - [ ] coupon validation is server-side with usage limit enforcement
133
- - [ ] tax and shipping calculated from confirmed shipping address
134
- - [ ] checkout submission is idempotent (double-submit safe)
135
- - [ ] inventory locked before charge, released on failure
136
- - [ ] order confirmation and email sent after successful payment
137
- - [ ] guest and authenticated paths tested independently
138
- - [ ] agentic checkout spending limits and pre-authorization gates enforced
139
- - [ ] Merchant of Record (MoR) assigned for agentic transactions
140
- - [ ] ACP/UCP programmatic checkout supported (headless, structured responses)
141
- - [ ] address validation performed via verified API (Google Maps/Loqate/Smarty) BEFORE tax/shipping
142
- - [ ] address validation errors caught with precise subcodes (missing apartment, invalid ZIP)
143
- - [ ] tax engine selected per decision tree (Stripe Tax / TaxJar / Avalara)
144
- - [ ] economic nexus threshold monitoring at 80% with alerts configured
145
- - [ ] economic nexus auto-registration workflow implemented
146
- - [ ] PCI DSS v4.0.1 req 6.4.3: SRI hashes + CSP nonce on all payment page scripts
147
- - [ ] PCI DSS v4.0.1 req 11.6.1: automated tamper detection (weekly/continuous)
148
- - [ ] Vietnam Decree 248/2026: seller verification gate before transactions
149
- - [ ] Vietnam Decree 248/2026: platform obligations disclosed (rights, standards, pricing, affiliate transparency)
150
- - [ ] Vietnam electronic ID verification for sellers/livestreamers (from Jan 1, 2027)
94
+ - [ ] cart totals, coupons (`SELECT ... FOR UPDATE`), tax, and shipping recalculated server-side after mandatory address validation
95
+ - [ ] checkout submission idempotent (`Idempotency-Key`); atomic two-phase TTL inventory reservation commits on charge / releases on failure
96
+ - [ ] guest checkout secured via HMAC-signed tokens + strict BOLA checks; EMV 3DS 2.3.1 + SCA exemptions wired
97
+ - [ ] agentic checkout (ACP/UCP) enforces pre-authorization limits, MoR declaration, and headless structured responses
98
+ - [ ] tax engine selected per scale (Stripe Tax / TaxJar / Avalara); 80% US economic nexus threshold alerts + auto-registration active
99
+ - [ ] PCI DSS v4.0.1 Req 6.4.3 (SRI + CSP nonce) and Req 11.6.1 (script/header tamper alerts) verified on payment pages
100
+ - [ ] Vietnam Decree 248/2026/ND-CP seller identity verification, disclosures, affiliate rules, and e-ID checks enforced
151
101
 
152
102
  ## Failure Modes
153
103
 
@@ -185,5 +135,7 @@ Skip emission for single-checkout experiments that do not cross a role boundary.
185
135
  - **manage-order-fulfillment**: Hand off the confirmed order for packing and shipping
186
136
  - **add-ui-component**: Build the cart and checkout UI components
187
137
  - **write-tests**: Write integration tests for the purchase funnel
138
+ - Companion reference: `references/pci-dss-v4-and-agentic-checkout-specs.md`
139
+ - Companion example: `examples/production-checkout-orchestrator.ts`
188
140
 
189
- Last updated: 2026-09-25
141
+ Last updated: 2026-11-08
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Production Checkout Orchestrator
3
+ *
4
+ * Implements end-to-end checkout orchestration adhering to:
5
+ * - PCI DSS v4.0.1 Zero-CDE principles
6
+ * - Mandatory address validation lifecycle prior to tax/shipping
7
+ * - Agentic Commerce Protocol (ACP / UCP v2026-08-25) pre-auth gating
8
+ * - Economic Nexus 80% threshold monitoring
9
+ * - Two-phase inventory reservation with TTL
10
+ */
11
+
12
+ export interface Address {
13
+ line1: string;
14
+ line2?: string;
15
+ city: string;
16
+ state: string;
17
+ postalCode: string;
18
+ country: string;
19
+ }
20
+
21
+ export interface AddressValidationResult {
22
+ isValid: boolean;
23
+ normalizedAddress?: Address;
24
+ errorSubcode?: 'MISSING_SECONDARY_UNIT' | 'INVALID_POSTAL_CODE' | 'UNRESOLVED_STREET';
25
+ }
26
+
27
+ export interface CartLineItem {
28
+ sku: string;
29
+ quantity: number;
30
+ unitPriceCents: number;
31
+ }
32
+
33
+ export interface CheckoutSessionRequest {
34
+ sessionId: string;
35
+ customerId: string;
36
+ agentPreAuthToken?: string;
37
+ items: CartLineItem[];
38
+ shippingAddress: Address;
39
+ idempotencyKey: string;
40
+ }
41
+
42
+ export interface TaxCalculationResult {
43
+ taxCents: number;
44
+ effectiveRate: number;
45
+ nexusAlertTriggered: boolean;
46
+ jurisdictionCode: string;
47
+ }
48
+
49
+ export interface ThreeDsContext {
50
+ deviceFingerprint: string;
51
+ ipAddress: string;
52
+ userAgent: string;
53
+ challengePreference: 'no_preference' | 'challenge_mandate';
54
+ scaExemptionRequested?: 'low_value' | 'transaction_risk_analysis';
55
+ }
56
+
57
+ export interface CheckoutFinalizationResult {
58
+ orderId: string;
59
+ status: 'confirmed' | 'requires_3ds_challenge' | 'rejected';
60
+ totalCents: number;
61
+ reservationId: string;
62
+ threeDsPayload?: {
63
+ acsUrl: string;
64
+ cReq: string;
65
+ };
66
+ }
67
+
68
+ export class ProductionCheckoutOrchestrator {
69
+ private readonly nexusTracker: Map<string, { totalRevenueCents: number; count: number }> = new Map();
70
+ private readonly NEXUS_REVENUE_THRESHOLD_CENTS = 10_000_000; // $100,000
71
+ private readonly NEXUS_ALERT_RATIO = 0.8; // 80% alert
72
+
73
+ /**
74
+ * Validates shipping address before any tax or shipping calculation.
75
+ */
76
+ public async validateShippingAddress(address: Address): Promise<AddressValidationResult> {
77
+ if (!address.line1 || !address.postalCode || !address.country) {
78
+ return { isValid: false, errorSubcode: 'UNRESOLVED_STREET' };
79
+ }
80
+ // Simulate postal code check
81
+ if (!/^\d{5}(-\d{4})?$/.test(address.postalCode) && address.country === 'US') {
82
+ return { isValid: false, errorSubcode: 'INVALID_POSTAL_CODE' };
83
+ }
84
+
85
+ return {
86
+ isValid: true,
87
+ normalizedAddress: {
88
+ ...address,
89
+ line1: address.line1.trim().toUpperCase(),
90
+ city: address.city.trim().toUpperCase(),
91
+ state: address.state.trim().toUpperCase(),
92
+ },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Verifies agentic commerce spending bounds under ACP / UCP specifications.
98
+ */
99
+ public verifyAgentSpendingLimit(agentToken: string, proposedAmountCents: number): boolean {
100
+ const MAX_AUTONOMOUS_LIMIT_CENTS = 50_000; // $500 per transaction
101
+ if (!agentToken || proposedAmountCents > MAX_AUTONOMOUS_LIMIT_CENTS) {
102
+ return false;
103
+ }
104
+ return true;
105
+ }
106
+
107
+ /**
108
+ * Computes tax and monitors economic nexus thresholds.
109
+ */
110
+ public calculateTaxAndCheckNexus(state: string, subtotalCents: number): TaxCalculationResult {
111
+ const current = this.nexusTracker.get(state) || { totalRevenueCents: 0, count: 0 };
112
+ const newTotal = current.totalRevenueCents + subtotalCents;
113
+ const newCount = current.count + 1;
114
+ this.nexusTracker.set(state, { totalRevenueCents: newTotal, count: newCount });
115
+
116
+ const nexusAlertTriggered = newTotal >= (this.NEXUS_REVENUE_THRESHOLD_CENTS * this.NEXUS_ALERT_RATIO);
117
+ const taxRate = 0.0825; // Standard 8.25% mock jurisdiction tax
118
+ const taxCents = Math.round(subtotalCents * taxRate);
119
+
120
+ return {
121
+ taxCents,
122
+ effectiveRate: taxRate,
123
+ nexusAlertTriggered,
124
+ jurisdictionCode: `${state}-STATE-SALES`,
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Full checkout lifecycle orchestration.
130
+ */
131
+ public async processCheckout(
132
+ request: CheckoutSessionRequest,
133
+ threeDs: ThreeDsContext
134
+ ): Promise<CheckoutFinalizationResult> {
135
+ // 1. Mandatory Address Validation Gate
136
+ const addressValidation = await this.validateShippingAddress(request.shippingAddress);
137
+ if (!addressValidation.isValid || !addressValidation.normalizedAddress) {
138
+ throw new Error(`Address validation failed with subcode: ${addressValidation.errorSubcode}`);
139
+ }
140
+
141
+ // 2. Compute Item Subtotal Server-Side (Zero Client-Trust)
142
+ const subtotalCents = request.items.reduce(
143
+ (sum, item) => sum + item.quantity * item.unitPriceCents,
144
+ 0
145
+ );
146
+
147
+ // 3. Agentic Spending Gate if operating autonomously
148
+ if (request.agentPreAuthToken) {
149
+ const allowed = this.verifyAgentSpendingLimit(request.agentPreAuthToken, subtotalCents);
150
+ if (!allowed) {
151
+ throw new Error('Agent autonomous spending limit exceeded or invalid pre-auth token');
152
+ }
153
+ }
154
+
155
+ // 4. Tax Engine & Nexus Evaluation
156
+ const tax = this.calculateTaxAndCheckNexus(addressValidation.normalizedAddress.state, subtotalCents);
157
+ const shippingCents = 1200; // $12.00 flat priority rate
158
+ const totalCents = subtotalCents + tax.taxCents + shippingCents;
159
+
160
+ // 5. Two-Phase Inventory Hold (Soft reserve with 15-minute TTL)
161
+ const reservationId = `res_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
162
+
163
+ // 6. EMV 3DS 2.3.1 Evaluation
164
+ const isExempt = subtotalCents < 3000; // €30 / $30 low-value exemption
165
+ if (!isExempt && threeDs.challengePreference === 'challenge_mandate') {
166
+ return {
167
+ orderId: `ord_${request.sessionId}`,
168
+ status: 'requires_3ds_challenge',
169
+ totalCents,
170
+ reservationId,
171
+ threeDsPayload: {
172
+ acsUrl: 'https://acs.bank.example/3ds-auth',
173
+ cReq: Buffer.from(JSON.stringify({ sessionId: request.sessionId, totalCents })).toString('base64'),
174
+ },
175
+ };
176
+ }
177
+
178
+ return {
179
+ orderId: `ord_${request.sessionId}`,
180
+ status: 'confirmed',
181
+ totalCents,
182
+ reservationId,
183
+ };
184
+ }
185
+ }
@@ -0,0 +1,72 @@
1
+ # PCI DSS v4.0.1 and Agentic Checkout Specifications (2026)
2
+
3
+ ## 1. Regulatory & Compliance Architecture
4
+
5
+ ### 1.1 PCI DSS v4.0.1 Core Requirements
6
+ Compliance with Payment Card Industry Data Security Standard (PCI DSS) v4.0.1 is mandatory across all checkout touchpoints:
7
+
8
+ - **Requirement 6.4.3 (Script Integrity on Payment Pages)**:
9
+ - All JavaScript executed within payment contexts (both first-party and third-party) must be explicitly inventoried with legitimate business justification.
10
+ - Scripts must be loaded with **Subresource Integrity (SRI)** hashes (`integrity="sha384-..."`) and cryptographically bound via a per-request strict **Content Security Policy (CSP)** nonce (`script-src 'nonce-<random-b64>' 'strict-dynamic'`).
11
+ - Inline event handlers (`onclick`, `onload`) are strictly prohibited.
12
+ - **Requirement 11.6.1 (Client-Side Tamper Detection)**:
13
+ - Implement continuous or weekly automated integrity checks comparing live script hashes and HTTP headers against canonical deployment baselines.
14
+ - Immediate alerting on unauthorized script injection or DOM tampering (Magecart / digital skimming mitigation).
15
+ - **SAQ A Scope Boundaries**:
16
+ - Entire cardholder data environment (CDE) must be fully outsourced to validated third-party payment processors using hosted fields, iframes, or modal redirects.
17
+ - Zero raw Primary Account Numbers (PAN), CVV/CVC, or track data may enter the merchant runtime, application memory, or logging layer.
18
+
19
+ ---
20
+
21
+ ## 2. Agentic Commerce Protocols (ACP & UCP)
22
+
23
+ ### 2.1 Protocol Topology
24
+ Modern commerce systems support autonomous agent transactions across two interoperable frameworks:
25
+ - **Agentic Commerce Protocol (ACP)** (OpenAI / Stripe): Optimized for headless, tool-driven instant checkout inside conversational runtimes.
26
+ - **Universal Commerce Protocol (UCP v2026-08-25)**: Open standard (Apache 2.0) compatible with Agent-to-Agent (A2A 1.0), AP2 v0.2, and Model Context Protocol (MCP).
27
+
28
+ ### 2.2 Autonomous Payment Gates & Risk Controls
29
+ - **Pre-Authorization Limits**: Each agent session must operate within an explicit credit line or balance authorization token (e.g., maximum $500 per transaction, $2,000 per 24 hours).
30
+ - **Merchant of Record (MoR)**: Explicit declaration of MoR for tax remittance, chargeback liability, and regulatory reporting on agent-initiated sales.
31
+ - **AP2 v0.2 (Human-Not-Present FIDO Token)**: Autonomous checkout uses pre-authorized cryptographic assertions bound to the user's biometric authenticator, bypassing interactive browser challenges.
32
+
33
+ ---
34
+
35
+ ## 3. Risk-Based Authentication & Frictionless 3DS
36
+
37
+ ### 3.1 EMV 3DS 2.3.1 Specification
38
+ - Over 100 contextual attributes transmitted in the 3DS request: device fingerprint, behavioral telemetry, IP velocity, browser plugins, account age, shipping/billing address match.
39
+ - **Strong Customer Authentication (SCA) Exemption Engine**:
40
+ - *Low-Value Transactions*: Transactions < €30 or regional equivalent.
41
+ - *Transaction Risk Analysis (TRA)*: Qualified acquirer exemption for low-fraud merchant tiers.
42
+ - *Trusted Beneficiary / Whitelisting*: Customer-approved merchant exemptions.
43
+
44
+ ---
45
+
46
+ ## 4. Address Validation Lifecycle
47
+
48
+ Address validation must occur as an isolated, mandatory gate **prior** to tax calculation or shipping carrier quotation:
49
+ 1. **Normalization**: Parse street lines, postal codes, and regional subdivisions via Loqate, Google Maps Address Validation, or Smarty Streets.
50
+ 2. **Subcode Resolution**: Evaluate granular API subcodes (`MISSING_SECONDARY_UNIT`, `INVALID_POSTAL_CODE`, `UNCONFIRMED_STREET`). Reject or prompt correction before downstream processing.
51
+ 3. **Delivery Point Validation (DPV)**: Confirm mailable delivery point status (`DPV: Y`).
52
+
53
+ ---
54
+
55
+ ## 5. Tax Engine & Economic Nexus Decision Tree
56
+
57
+ ### 5.1 Tax Engine Selection Matrix
58
+ - **Stripe Tax**: Recommended for digital-native merchants operating entirely on Stripe infrastructure; automated registration and instant calculation.
59
+ - **TaxJar**: Multi-channel retailers (combining custom e-commerce with Shopify/Amazon); automated filing support.
60
+ - **Avalara AvaTax**: Enterprise systems with complex supply chains, custom ERPs (SAP, NetSuite), cross-border VAT/GST, and specialized commodity exemptions.
61
+
62
+ ### 5.2 Economic Nexus 80% Early-Warning System
63
+ - Monitor state-by-state gross receipts and transaction frequencies.
64
+ - Trigger automatic alert and compliance ticket when volume reaches 80% of statutory nexus thresholds (e.g., $80,000 revenue or 160 transactions in $100K/200-transaction jurisdictions).
65
+
66
+ ---
67
+
68
+ ## 6. Vietnam Regulatory Compliance (Decree 248/2026/ND-CP)
69
+
70
+ - **Seller Identity Verification**: Digital identity verification mandatory for all marketplace sellers prior to catalog listing and payout clearance.
71
+ - **Platform Disclosures**: Public display of platform rights, resolution dispute standards, transparent pricing structures, and affiliate partner relationships.
72
+ - **Electronic ID Integration**: Electronic citizen ID verification (VNeID level 2) enforced for commercial sellers and live streamers.
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  name: integrate-payment-gateway
3
3
  description: Integrate or extend a payment gateway (Stripe, VNPay, PayPal, Momo, etc.) into an e-commerce application. Use when adding, replacing, or auditing a payment provider's checkout, refund, or webhook flow.
4
+ version: "1.0.0"
4
5
  allowed-tools: [read_file, write_file, edit_file, create_file, search_code, run_tests, run_linter, run_build, fetch]
5
6
  ---
6
7
 
@@ -31,7 +32,7 @@ Use this skill when a task requires connecting an application to a payment provi
31
32
  - support **HTTP 402 / MPP** programmatic machine payment challenges and off-session `SetupIntents` for autonomous agent checkout flows
32
33
  - handle asynchronous clearing states (A2A bank transfers) via webhook state machine with inventory TTL lock during settlement pending
33
34
  - **MPP Protocol** (Stripe + Tempo, Mar 2026): HTTP 402 flow — Request → 402 with payment requirements → Agent authorizes → Retry with credential → Verify → Return resource; Payment methods: Shared Payment Tokens (SPTs) for cards, stablecoins (USDC on Tempo), x402; Stripe integration: PaymentIntents API, `automatic_payment_methods: { enabled: true }`, off-session SetupIntents with `setup_future_usage: "off_session"`
34
- - **x402 Protocol** (2025-2026): Internet-native HTTP-based payment standard for machine-to-machine; HTTP 402 with `payment-required` header (base64-encoded); Crypto: USDC on Base network, CDP facilitator (Coinbase Developer Platform); Stripe support: `2026-05-27.preview` API, `crypto` payment method, `mode: transaction_verification`; Deposit addresses: `POST /v1/crypto/deposit_addresses` (network=tempo)
35
+ - **x402 Protocol**: Internet-native HTTP-based payment standard for machine-to-machine; HTTP 402 with `payment-required` header (base64-encoded); Crypto: USDC on Base network, CDP facilitator (Coinbase Developer Platform); Stripe support: `2026-05-27.preview` API, `crypto` payment method, `mode: transaction_verification`; Deposit addresses: `POST /v1/crypto/deposit_addresses` (network=tempo)
35
36
  - **BNPL & Subscription BNPL**: Messaging elements on PDP/cart (`stripe-payment-method-messaging`) with dynamic price/currency/country; Subscription BNPL for recurring payments; Flow: Initial installment → BNPL pays merchant → Subsequent payments via bank rails (ACH, A2A) or card rails
36
37
  - **A2A Pay by Bank**: TrueLayer, Plaid, Stripe Pay by Bank; Lower fees than cards; Settlement state machine: `processing` → `pending` → `settled` webhooks; Inventory TTL lock during slow bank settlement
37
38
  - **Stripe 2026 Roadmap**: Dynamic pricing for x402/MPP (Q3 public preview), Session payments for usage-based billing (Q3 public preview), Standalone 3DS (Q3 GA), Multi-account MCP (Q3 private preview), Shared Payment Tokens (Q4 GA US), Wero payments (Q4 private preview)
@@ -78,68 +79,29 @@ Answer before building:
78
79
  - **MPP/x402 errors**: payment verification failure, crypto settlement timeout, facilitator errors
79
80
  - **A2A errors**: settlement timeout, bank rejection, webhook state machine corruption
80
81
 
81
- ### 5. 2026 Modern Payment Paradigms
82
-
83
- #### Stripe Dynamic Payment Methods
84
- - Configure `automatic_payment_methods: { enabled: true }` when creating payment intent. Avoid hardcoded payment method types.
85
- - Allows payment elements UI to render and prioritize available methods (cards, BNPL, bank transfers) dynamically based on client location, currency, dashboard settings.
86
-
87
- #### Buy Now Pay Later (BNPL) Messaging
88
- - Integrate BNPL messaging elements (e.g., `stripe-payment-method-messaging`) early in purchase funnel (PDP, cart pages).
89
- - Pass item price, currency, consumer country dynamically for accurate Klarna/Affirm split calculations (e.g., "4 payments of $25").
90
- - **Subscription BNPL**: Recurring payments beyond retail installments.
91
-
92
- #### Account-to-Account (A2A) Pay by Bank
93
- - Use bank-to-bank direct rails (TrueLayer, Plaid, Stripe Pay by Bank) to lower card processing fees.
94
- - Manage intermediate status webhooks (`processing`, `pending`, `settled`) in DB state machine.
95
- - Keep order state as payment pending; lock inventory with TTL while waiting for bank settlement.
96
-
97
- #### Programmatic Agent Payments (x402 / MPP)
98
- - For machine-to-machine / autonomous AI agent checkouts, avoid interactive frontend redirects.
99
- - Respond to unauthorized agent requests with HTTP 402 Payment Required + payment headers.
100
- - Support programmatic card and A2A billing via Stripe MPP or SetupIntents with `setup_future_usage: "off_session"`.
101
-
102
- #### Stripe 2026 Roadmap Features (Evaluate for Integration)
103
- - **Dynamic pricing for x402/MPP** (Q3 2026 public preview, global): Pay-as-you-go transactions on x402/MPP
104
- - **Session payments** (Q3 2026 public preview, global): Usage-based billing at token consumption/API invocation granularity
105
- - **Standalone 3DS** (Q3 2026 GA, global): Thin event destinations for all Stripe API resources
106
- - **Multi-account MCP** (Q3 2026 private preview): Charge connected accounts for Stripe fees
107
- - **Shared Payment Tokens** (Q4 2026 GA, US): Cross-merchant token sharing
108
- - **Wero payments** (Q4 2026 private preview, global): European instant payment scheme
82
+ ### 5. 2026 Payment Paradigms (Dynamic Methods, BNPL, A2A, MPP/x402)
83
+ - Enable `automatic_payment_methods: { enabled: true }` (no hardcoded method lists) and `stripe-payment-method-messaging` BNPL splits on PDP/cart.
84
+ - Manage A2A Pay by Bank webhooks (`processing` -> `pending` -> `settled`) with inventory TTL locks; answer non-interactive agent calls via HTTP `402` MPP/x402 (`npx mppx@latest validate`) or off-session `SetupIntents`.
109
85
 
110
86
  ### 6. Test and Validate
87
+ - Test against provider sandbox + Stripe CLI / `npx mppx@latest validate`, replay webhooks to prove idempotency, verify A2A/x402 state transitions, and confirm zero PAN/CVV leakage in logs.
88
+
89
+ ## Red Flags
111
90
 
112
- - run against provider sandbox with documented test card numbers
113
- - verify webhook delivery end-to-end (use provider dashboard or Stripe CLI)
114
- - confirm idempotency: replay a webhook event; verify the order is not double-updated
115
- - confirm no sensitive data appears in logs or error responses
116
- - **MPP validation**: `npx mppx@latest validate http://localhost:4242`
117
- - **x402 testing**: Stripe `2026-05-27.preview` API, crypto deposit addresses, facilitator settlement
118
- - **BNPL testing**: messaging element renders correct splits for various price/currency/country combos
119
- - **A2A testing**: settlement state machine transitions, inventory TTL lock/release, webhook replay
91
+ | Rationalization Thought | Reality & Risk | Positive Corrective Action |
92
+ | :--- | :--- | :--- |
93
+ | "Skip HMAC verification in dev/staging webhooks to move faster." | Unsigned handlers ship to prod and allow spoofed `payment_succeeded` events. | Verify raw-body HMAC with constant-time compare and `< 300s` replay window. |
94
+ | "Process fulfillment synchronously inside the webhook HTTP handler." | Gateway timeouts (`> 500ms`) trigger retry storms and duplicate order states. | Persist raw event idempotently, return `200 OK` within `500ms`, offload to queue. |
95
+ | "Retry POST capture automatically without an idempotency key." | Duplicate network attempts double-charge customers during transient blips. | Attach UUID idempotency keys per transaction attempt and DB unique guards. |
96
+ | "Store full PAN temporarily in Redis to help retry flows." | Immediately expands PCI DSS CDE scope and leaks `restricted` cardholder data. | Use hosted SDK tokenization / EMVCo Network Tokens; never touch PAN/CVV. |
120
97
 
121
98
  ## Checklist
122
99
 
123
- - [ ] provider SDK installed and version pinned
124
- - [ ] all credentials in env vars — not in source code
125
- - [ ] idempotency keys used for charge and capture calls
126
- - [ ] webhook signature validation: HMAC over raw payload, constant-time comparison, 300s replay window
127
- - [ ] **queue-first webhook ingestion**: 200 OK within 500ms, async worker offload (Kafka/Cloudflare Queues/RabbitMQ)
128
- - [ ] **dual-write idempotency guard**: unique index on (provider, event_id, event_type) + distributed lock (Redis Redlock/Postgres Advisory Lock)
129
- - [ ] error codes mapped to safe user-facing messages
130
- - [ ] refund flow implemented with audit trail
131
- - [ ] no card numbers, CVV, or PAN in logs or API responses (EMVCo Network Tokens preferred)
132
- - [ ] sandbox tested end-to-end including failure cases
133
- - [ ] webhook replay tested for idempotency
134
- - [ ] dynamic payment methods enabled (`automatic_payment_methods: true`)
135
- - [ ] BNPL messaging elements integrated on PDP and cart pages with dynamic price/currency/country
136
- - [ ] A2A bank settlement webhook states handled (`processing`/`pending`/`settled`) with inventory TTL locks
137
- - [ ] HTTP 402/MPP programmatic checkout path supported and tested for non-interactive agent payments
138
- - [ ] off-session SetupIntents with `setup_future_usage: "off_session"` for stored method charging
139
- - [ ] MPP protocol: HTTP 402 flow, SPTs for cards, stablecoins (USDC on Tempo), x402 support
140
- - [ ] x402 protocol: crypto deposit addresses (USDC on Base/Tempo), CDP facilitator, `2026-05-27.preview` API
141
- - [ ] Stripe 2026 roadmap features evaluated: dynamic pricing, session payments, standalone 3DS, Shared Payment Tokens, Wero
142
- - [ ] MPP validation tested with `npx mppx@latest validate`
100
+ - [ ] official provider SDK pinned, keys stored in env/vault, and `automatic_payment_methods: true` configured
101
+ - [ ] raw-payload HMAC webhook verification (constant-time, 300s replay check), `< 500ms` queue-first `200 OK`, and `(provider, event_id, event_type)` DB unique + distributed lock guard
102
+ - [ ] idempotency keys on all charge/capture calls, safe error mapping, and refund validation against original charge ID
103
+ - [ ] zero PAN/CVV in logs or responses (EMVCo Network Tokens + sandbox replay tested)
104
+ - [ ] BNPL messaging, A2A settlement webhooks + inventory TTL, and HTTP 402 MPP/x402 validated (`npx mppx@latest validate`) + webhook replay tested
143
105
 
144
106
  ## Failure Modes
145
107
 
@@ -179,5 +141,7 @@ Skip emission for local sandbox experiments that do not cross a role boundary.
179
141
  - **security-audit**: Review payment integration for PCI exposure
180
142
  - **add-api-endpoint**: Scaffold the payment and webhook controller endpoints
181
143
  - **configure-agent-commerce**: Implement x402 HTTP billing, MPP endpoints, and agent commerce registration
144
+ - Companion reference: `references/mpp-x402-and-webhook-security-specs.md`
145
+ - Companion example: `examples/resilient-webhook-and-mpp-handler.ts`
182
146
 
183
- Last updated: 2026-09-25
147
+ Last updated: 2026-11-08
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Resilient Webhook and MPP (HTTP 402) Payment Handler
3
+ *
4
+ * Implements:
5
+ * - Constant-time HMAC SHA-256 raw payload signature verification
6
+ * - 300-second replay attack protection window
7
+ * - Fast queue-first response (<500ms) with distributed deduplication
8
+ * - HTTP 402 / x402 programmatic agent negotiation
9
+ */
10
+
11
+ import * as crypto from 'crypto';
12
+
13
+ export interface WebhookEventPayload {
14
+ id: string;
15
+ type: string;
16
+ created: number; // Unix timestamp
17
+ data: {
18
+ object: {
19
+ id: string;
20
+ amount: number;
21
+ currency: string;
22
+ status: string;
23
+ metadata?: Record<string, string>;
24
+ };
25
+ };
26
+ }
27
+
28
+ export interface IngestionQueue {
29
+ enqueue(topic: string, event: WebhookEventPayload): Promise<void>;
30
+ }
31
+
32
+ export interface DistributedLockProvider {
33
+ acquire(key: string, ttlMs: number): Promise<boolean>;
34
+ release(key: string): Promise<void>;
35
+ }
36
+
37
+ export class ResilientPaymentHandler {
38
+ constructor(
39
+ private readonly webhookSecret: string,
40
+ private readonly queue: IngestionQueue,
41
+ private readonly lockProvider: DistributedLockProvider
42
+ ) {}
43
+
44
+ /**
45
+ * Verifies raw payload signature using constant-time HMAC comparison.
46
+ */
47
+ public verifyStripeSignature(rawBody: Buffer, signatureHeader: string): boolean {
48
+ const parts = signatureHeader.split(',');
49
+ let timestamp = '';
50
+ let expectedSignature = '';
51
+
52
+ for (const part of parts) {
53
+ const [key, value] = part.trim().split('=');
54
+ if (key === 't') timestamp = value;
55
+ if (key === 'v1') expectedSignature = value;
56
+ }
57
+
58
+ if (!timestamp || !expectedSignature) {
59
+ return false;
60
+ }
61
+
62
+ // Check 300-second replay window
63
+ const eventTime = parseInt(timestamp, 10);
64
+ const currentTime = Math.floor(Date.now() / 1000);
65
+ if (Math.abs(currentTime - eventTime) > 300) {
66
+ return false; // Replay window exceeded
67
+ }
68
+
69
+ // Compute expected HMAC digest over raw bytes
70
+ const signedPayload = `${timestamp}.${rawBody.toString('utf-8')}`;
71
+ const computedSignature = crypto
72
+ .createHmac('sha256', this.webhookSecret)
73
+ .update(signedPayload)
74
+ .digest('hex');
75
+
76
+ const bufComputed = Buffer.from(computedSignature, 'utf-8');
77
+ const bufExpected = Buffer.from(expectedSignature, 'utf-8');
78
+
79
+ if (bufComputed.length !== bufExpected.length) {
80
+ return false;
81
+ }
82
+
83
+ return crypto.timingSafeEqual(bufComputed, bufExpected);
84
+ }
85
+
86
+ /**
87
+ * Queue-first webhook ingestion endpoint handler.
88
+ */
89
+ public async handleWebhook(
90
+ rawBody: Buffer,
91
+ signatureHeader: string
92
+ ): Promise<{ statusCode: number; message: string }> {
93
+ const startTime = Date.now();
94
+
95
+ // 1. Signature Verification
96
+ const isValid = this.verifyStripeSignature(rawBody, signatureHeader);
97
+ if (!isValid) {
98
+ return { statusCode: 400, message: 'Invalid signature or expired replay window' };
99
+ }
100
+
101
+ // 2. Parse Event JSON safely after signature check
102
+ const event: WebhookEventPayload = JSON.parse(rawBody.toString('utf-8'));
103
+
104
+ // 3. Distributed Deduplication Lock
105
+ const lockKey = `lock:webhook:event:${event.id}`;
106
+ const acquired = await this.lockProvider.acquire(lockKey, 30_000);
107
+ if (!acquired) {
108
+ // Event already being handled concurrently
109
+ return { statusCode: 200, message: 'Event already in processing' };
110
+ }
111
+
112
+ try {
113
+ // 4. Offload to Queue for asynchronous background processing
114
+ await this.queue.enqueue('payment.events', event);
115
+
116
+ const durationMs = Date.now() - startTime;
117
+ if (durationMs > 500) {
118
+ console.warn(`[PERF ALERT] Webhook ingestion took ${durationMs}ms (>500ms SLA)`);
119
+ }
120
+
121
+ return { statusCode: 200, message: 'Enqueued' };
122
+ } finally {
123
+ await this.lockProvider.release(lockKey);
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Generates an HTTP 402 Payment Required response for autonomous agent callers (MPP / x402).
129
+ */
130
+ public generateMppChallenge(
131
+ resourceId: string,
132
+ priceUsdc: number,
133
+ depositAddress: string
134
+ ): {
135
+ statusCode: 402;
136
+ headers: Record<string, string>;
137
+ body: Record<string, unknown>;
138
+ } {
139
+ const challengePayload = {
140
+ version: 'x402-v1',
141
+ resource_id: resourceId,
142
+ accepted_currencies: ['USDC-BASE', 'USDC-TEMPO'],
143
+ amount: priceUsdc,
144
+ deposit_address: depositAddress,
145
+ valid_until: Math.floor(Date.now() / 1000) + 900, // 15 min expiry
146
+ };
147
+
148
+ const encodedChallenge = Buffer.from(JSON.stringify(challengePayload)).toString('base64');
149
+
150
+ return {
151
+ statusCode: 402,
152
+ headers: {
153
+ 'Content-Type': 'application/json',
154
+ 'Payment-Required': encodedChallenge,
155
+ 'WWW-Authenticate': `MPP realm="api", token="${encodedChallenge}"`,
156
+ },
157
+ body: {
158
+ error: 'Payment Required',
159
+ message: 'Resource requires pre-authorized MPP / x402 token or crypto settlement.',
160
+ challenge: challengePayload,
161
+ },
162
+ };
163
+ }
164
+ }