@salesforce/afv-skills 1.68.0 → 1.70.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 (284) hide show
  1. package/package.json +1 -1
  2. package/skills/afcc-setup-coordinate/SKILL.md +348 -0
  3. package/skills/afcc-setup-coordinate/assets/console-app/AFCC_Service_Console.app-meta.xml +19 -0
  4. package/skills/afcc-setup-coordinate/assets/console-app/Admin.profile-meta.xml +8 -0
  5. package/skills/afcc-setup-coordinate/assets/console-app/Standard.profile-meta.xml +8 -0
  6. package/skills/afcc-setup-coordinate/assets/gap_report_template.md +35 -0
  7. package/skills/afcc-setup-coordinate/assets/org_profile_template.json +16 -0
  8. package/skills/afcc-setup-coordinate/references/gotchas.md +22 -0
  9. package/skills/afcc-setup-coordinate/scripts/audit_org.sh +159 -0
  10. package/skills/agentforce-bot-upgrade/SKILL.md +117 -66
  11. package/skills/agentforce-bot-upgrade/assets/_vendored/agent-spec-template.md +139 -0
  12. package/skills/agentforce-bot-upgrade/references/_vendored/agent-design-and-spec-creation.md +1211 -0
  13. package/skills/agentforce-bot-upgrade/references/_vendored/agent-script-core-language.md +1390 -0
  14. package/skills/agentforce-bot-upgrade/references/_vendored/agent-subagent-map-diagrams.md +341 -0
  15. package/skills/agentforce-bot-upgrade/references/_vendored/agent-user-setup.md +672 -0
  16. package/skills/agentforce-bot-upgrade/references/_vendored/agent-validation-and-debugging.md +904 -0
  17. package/skills/agentforce-bot-upgrade/references/_vendored/agentscript-toolchain.md +112 -0
  18. package/skills/agentforce-bot-upgrade/references/_vendored/architecture-patterns.md +277 -0
  19. package/skills/agentforce-bot-upgrade/references/_vendored/common-control-flow-pitfalls.md +255 -0
  20. package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-actions-sequencing.md +198 -0
  21. package/skills/agentforce-bot-upgrade/references/_vendored/control-flow-lifecycle-side-effects.md +87 -0
  22. package/skills/agentforce-bot-upgrade/references/_vendored/data-library-reference.md +891 -0
  23. package/skills/agentforce-bot-upgrade/references/_vendored/instruction-resolution.md +658 -0
  24. package/skills/agentforce-bot-upgrade/references/_vendored/org-setup-for-adl.md +551 -0
  25. package/skills/agentforce-bot-upgrade/references/_vendored/patterns-by-requirement.md +88 -0
  26. package/skills/agentforce-bot-upgrade/references/_vendored/posture-and-determinism.md +215 -0
  27. package/skills/agentforce-bot-upgrade/references/extraction-blueprint.md +11 -4
  28. package/skills/agentforce-bot-upgrade/references/generate-agent-spec.md +19 -3
  29. package/skills/agentforce-bot-upgrade/references/handoff-output-format.md +82 -52
  30. package/skills/agentforce-bot-upgrade/references/input-contract.md +8 -8
  31. package/skills/agentforce-bot-upgrade/references/mapping-rules.md +19 -6
  32. package/skills/agentforce-bot-upgrade/references/post-conversion-enhancements-reference.md +65 -6
  33. package/skills/agentforce-bot-upgrade/references/quality-checklist.md +4 -4
  34. package/skills/agentforce-bot-upgrade/references/sf-cli-bot-reference.md +17 -3
  35. package/skills/agentforce-hyperclassifier-configure/README.md +24 -0
  36. package/skills/agentforce-hyperclassifier-configure/SKILL.md +111 -0
  37. package/skills/agentforce-hyperclassifier-configure/assets/customer-org.env.example +4 -0
  38. package/skills/agentforce-hyperclassifier-configure/assets/sample_descriptions.json +8 -0
  39. package/skills/agentforce-hyperclassifier-configure/assets/sample_evals.csv +17 -0
  40. package/skills/agentforce-hyperclassifier-configure/references/api-contract.md +41 -0
  41. package/skills/agentforce-hyperclassifier-configure/references/authentication.md +35 -0
  42. package/skills/agentforce-hyperclassifier-configure/references/evaluation.md +46 -0
  43. package/skills/agentforce-hyperclassifier-configure/references/installation.md +35 -0
  44. package/skills/agentforce-hyperclassifier-configure/references/onboarding.md +93 -0
  45. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/__init__.py +1 -0
  46. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/client.py +219 -0
  47. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/eca.py +178 -0
  48. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/evaluation.py +207 -0
  49. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/onboarding.py +191 -0
  50. package/skills/agentforce-hyperclassifier-configure/scripts/hcopt/optimizer.py +187 -0
  51. package/skills/agentforce-hyperclassifier-configure/scripts/hyperclassifier.py +111 -0
  52. package/skills/agentforce-hyperclassifier-configure/scripts/report_hyperclassifier.py +149 -0
  53. package/skills/agentforce-hyperclassifier-configure/scripts/setup_hyperclassifier.py +74 -0
  54. package/skills/agentforce-hyperclassifier-configure/scripts/tests/test_hyperclassifier_skill.py +887 -0
  55. package/skills/agentforce-offline-experimentation-run/scripts/btlib/judge.py +23 -31
  56. package/skills/agentforce-offline-experimentation-run/scripts/btlib/messages.py +2 -1
  57. package/skills/agentforce-offline-experimentation-run/scripts/btlib/sfap.py +118 -2
  58. package/skills/agentforce-offline-experimentation-run/scripts/build_report.py +2 -2
  59. package/skills/agentforce-offline-experimentation-run/scripts/resolve-token.sh +9 -2
  60. package/skills/agentforce-offline-experimentation-run/scripts/sfap_replay.py +12 -1
  61. package/skills/commerce-react-storefront-create/SKILL.md +54 -21
  62. package/skills/data360-code-extension-generate/SKILL.md +160 -252
  63. package/skills/data360-code-extension-generate/references/README.md +34 -172
  64. package/skills/data360-code-extension-generate/references/environment-setup.md +198 -0
  65. package/skills/data360-code-extension-generate/references/mcp-integration.md +36 -0
  66. package/skills/data360-code-extension-generate/references/quick-reference.md +132 -202
  67. package/skills/data360-code-extension-generate/references/run-logs.md +31 -0
  68. package/skills/data360-code-extension-generate/references/schema-discovery.md +45 -0
  69. package/skills/data360-code-extension-generate/references/troubleshooting.md +45 -0
  70. package/skills/data360-code-extension-generate/scripts/check_env.sh +197 -0
  71. package/skills/data360-code-extension-generate/scripts/venv_hook.sh +22 -0
  72. package/skills/dx-devops-work-item-manage/SKILL.md +24 -8
  73. package/skills/dx-devops-work-item-manage/examples/common-workflows.md +32 -0
  74. package/skills/dx-devops-work-item-manage/references/review-api.md +95 -0
  75. package/skills/dx-lifecycle-center/SKILL.md +24 -18
  76. package/skills/dx-lifecycle-center/examples/workflows.md +57 -34
  77. package/skills/dx-lifecycle-center/references/connect-api.md +33 -4
  78. package/skills/dx-lifecycle-center/references/connect-org.md +59 -28
  79. package/skills/dx-lifecycle-center/references/deploy.md +3 -3
  80. package/skills/dx-lifecycle-center/references/hub-org.md +19 -3
  81. package/skills/dx-lifecycle-center/references/list-orgs.md +50 -24
  82. package/skills/dx-lifecycle-center/references/troubleshooting.md +22 -1
  83. package/skills/dx-lifecycle-center/scripts/hub-get.sh +41 -0
  84. package/skills/dx-lifecycle-center/scripts/resolve-environment.sh +151 -4
  85. package/skills/dx-org-manage/SKILL.md +12 -12
  86. package/skills/dx-org-manage/examples/scratch-orgs/display_output.json +1 -3
  87. package/skills/dx-org-manage/examples/scratch-orgs/success_shape.json +1 -3
  88. package/skills/dx-org-manage/references/opening-org.md +1 -1
  89. package/skills/dx-org-manage/references/scratch-org-operations.md +15 -20
  90. package/skills/dx-packaging-convert-1gp-to-2gp-create/SKILL.md +63 -0
  91. package/skills/dx-packaging-convert-1gp-to-2gp-create/references/conversion-operations.md +252 -0
  92. package/skills/dx-packaging-move-to-2gp-migrate/SKILL.md +3 -4
  93. package/skills/dx-packaging-move-to-2gp-migrate/references/api-operations.md +10 -7
  94. package/skills/dx-packaging-push-upgrade-configure/README.md +47 -0
  95. package/skills/dx-packaging-push-upgrade-configure/SKILL.md +355 -0
  96. package/skills/dx-packaging-push-upgrade-configure/references/best-practices.md +61 -0
  97. package/skills/dx-packaging-push-upgrade-configure/references/cli-reference.md +148 -0
  98. package/skills/dx-packaging-push-upgrade-configure/references/objects.md +106 -0
  99. package/skills/dx-packaging-push-upgrade-configure/references/soql-recipes.md +144 -0
  100. package/skills/education-cloud-academic-calendar-generate/SKILL.md +2 -2
  101. package/skills/education-cloud-course-catalog-migrate/SKILL.md +1 -1
  102. package/skills/education-cloud-domain-configure/references/domain-features/recruitment-admissions.md +8 -7
  103. package/skills/education-cloud-multi-campus-configure/SKILL.md +1 -0
  104. package/skills/education-cloud-multi-campus-configure/references/error_handling.md +7 -6
  105. package/skills/education-cloud-student-recruitment-agent-configure/SKILL.md +2 -0
  106. package/skills/education-cloud-student-recruitment-agent-configure/references/customer-narration.md +2 -0
  107. package/skills/education-cloud-student-recruitment-agent-configure/references/flows.md +1 -1
  108. package/skills/education-cloud-student-recruitment-agent-configure/references/grounding.md +5 -4
  109. package/skills/education-cloud-student-recruitment-agent-configure/references/permissions.md +1 -1
  110. package/skills/education-cloud-student-recruitment-agent-configure/references/prerequisites.md +1 -1
  111. package/skills/education-cloud-student-recruitment-agent-configure/references/routing.md +1 -1
  112. package/skills/experience-afv-analytics-query/SKILL.md +239 -0
  113. package/skills/experience-afv-analytics-query/references/references.md +176 -0
  114. package/skills/experience-app-mcp-delivery-generate/SKILL.md +142 -0
  115. package/skills/experience-app-mcp-delivery-generate/references/eca-consumer-key.md +26 -0
  116. package/skills/experience-app-mcp-delivery-generate/references/mcp-config-delivery.md +38 -0
  117. package/skills/experience-app-mcp-delivery-generate/references/plugin-format-and-publishing.md +80 -0
  118. package/skills/experience-app-mcp-delivery-generate/scripts/developer_name.mjs +9 -0
  119. package/skills/experience-app-mcp-delivery-generate/scripts/discover_mcp_context.mjs +114 -0
  120. package/skills/experience-app-mcp-delivery-generate/scripts/generate_mcp_config.mjs +27 -0
  121. package/skills/experience-app-mcp-delivery-generate/scripts/generate_plugin.mjs +184 -0
  122. package/skills/experience-app-mcp-delivery-generate/scripts/mcp_config.mjs +57 -0
  123. package/skills/experience-app-mcp-delivery-generate/scripts/preflight.mjs +109 -0
  124. package/skills/experience-app-mcp-delivery-generate/scripts/retrieve_eca_consumer_key.mjs +143 -0
  125. package/skills/experience-app-mcp-generate/SKILL.md +174 -0
  126. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.eca-meta.xml +7 -0
  127. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaGlblOauth-meta.xml +15 -0
  128. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauth-meta.xml +6 -0
  129. package/skills/experience-app-mcp-generate/assets/__ECA_NAME__.ecaOauthPlcy-meta.xml +12 -0
  130. package/skills/experience-app-mcp-generate/assets/__ECA_NAME___defaultPolicy.ecaPlcy-meta.xml +7 -0
  131. package/skills/experience-app-mcp-generate/assets/__MCP_SERVER_NAME__.mcpServerDefinition-meta.xml +5 -0
  132. package/skills/experience-app-mcp-generate/references/eca-fields.md +76 -0
  133. package/skills/experience-app-mcp-generate/references/mcp-objects.md +66 -0
  134. package/skills/experience-app-mcp-generate/references/tool-bindings.md +85 -0
  135. package/skills/experience-app-mcp-generate/references/troubleshooting.md +41 -0
  136. package/skills/experience-app-mcp-generate/references/ui-frameworks.md +19 -0
  137. package/skills/experience-app-mcp-generate/references/widget-resources.md +96 -0
  138. package/skills/experience-app-mcp-generate/scripts/activate_server.mjs +166 -0
  139. package/skills/experience-app-mcp-generate/scripts/check_setup_progress.mjs +212 -0
  140. package/skills/experience-app-mcp-generate/scripts/list_sites.mjs +211 -0
  141. package/skills/experience-app-mcp-generate/scripts/merge_tools.mjs +407 -0
  142. package/skills/experience-app-mcp-generate/scripts/preflight.mjs +127 -0
  143. package/skills/experience-app-mcp-generate/scripts/render_eca.mjs +144 -0
  144. package/skills/experience-app-mcp-generate/scripts/render_mcp_server.mjs +64 -0
  145. package/skills/experience-app-mcp-generate/scripts/retrieve_existing_prompts.mjs +145 -0
  146. package/skills/experience-app-mcp-generate/scripts/retrieve_existing_tools.mjs +72 -0
  147. package/skills/experience-app-mcp-generate/scripts/scan_tool_candidates.mjs +195 -0
  148. package/skills/experience-app-mcp-generate/scripts/utils/callback_url.mjs +36 -0
  149. package/skills/experience-app-mcp-generate/scripts/utils/developer_name.mjs +9 -0
  150. package/skills/experience-app-mcp-generate/scripts/utils/eca_check.mjs +156 -0
  151. package/skills/experience-app-mcp-generate/scripts/utils/metadata_path.mjs +13 -0
  152. package/skills/experience-app-mcp-generate/scripts/verify_server.mjs +118 -0
  153. package/skills/experience-cms-content-type-generate/SKILL.md +8 -7
  154. package/skills/experience-cms-content-type-generate/references/agent-checklist.md +3 -3
  155. package/skills/experience-cms-content-type-generate/references/anti-patterns.md +2 -2
  156. package/skills/experience-cms-content-type-generate/references/discovery-details.md +1 -1
  157. package/skills/experience-cms-content-type-generate/references/retrieve-and-reconcile.md +5 -9
  158. package/skills/experience-ui-bundle-custom-app-generate/scripts/resolve-uibundle-path.mjs +10 -0
  159. package/skills/field-service-data-capture-migrate/references/converter-builder-contract.md +2 -2
  160. package/skills/field-service-data-capture-migrate/references/fsm-dc-capability-catalog.md +2 -2
  161. package/skills/field-service-data-capture-migrate/scripts/analyze_flow.py +1 -1
  162. package/skills/field-service-data-capture-migrate/scripts/convert_to_dc_spec.py +1 -1
  163. package/skills/field-service-data-capture-migrate/scripts/fsm_dc_catalog.py +2 -2
  164. package/skills/field-service-data-capture-migrate/scripts/generate_summary.py +2 -2
  165. package/skills/nonprofit-fundraising-configure/SKILL.md +1 -1
  166. package/skills/nonprofit-fundraising-configure/references/mcp-invocation.md +52 -4
  167. package/skills/nonprofit-fundraising-configure/references/permission-targeting.md +19 -2
  168. package/skills/platform-custom-application-generate/SKILL.md +97 -104
  169. package/skills/platform-custom-application-generate/references/app-properties.md +52 -0
  170. package/skills/platform-custom-application-generate/references/app-visibility.md +19 -0
  171. package/skills/platform-custom-application-generate/references/utility-bar.md +55 -0
  172. package/skills/platform-custom-field-generate/SKILL.md +24 -16
  173. package/skills/platform-custom-metadata-type-generate/SKILL.md +1 -0
  174. package/skills/platform-custom-setting-generate/SKILL.md +1 -0
  175. package/skills/platform-datamask-run/SKILL.md +1 -1
  176. package/skills/platform-datamask-run/references/policy-authoring.md +41 -18
  177. package/skills/platform-dataspace-access-configure/SKILL.md +25 -10
  178. package/skills/platform-dsar-policy-manage/SKILL.md +7 -6
  179. package/skills/platform-dsar-policy-manage/references/export-and-history.md +10 -8
  180. package/skills/platform-dsar-policy-manage/references/report-format.md +4 -2
  181. package/skills/platform-flexipage-generate/SKILL.md +7 -10
  182. package/skills/platform-flexipage-generate/references/mcp_action_examples.md +42 -38
  183. package/skills/platform-metadata-grounding-get/SKILL.md +7 -7
  184. package/skills/platform-policy-rule-generate/SKILL.md +9 -7
  185. package/skills/platform-policy-rule-generate/references/condition-model.md +3 -3
  186. package/skills/platform-policy-rule-generate/references/conjunction-expression.md +9 -1
  187. package/skills/platform-policy-rule-generate/references/consumer-datacloud-ui.md +9 -1
  188. package/skills/platform-policy-rule-generate/references/examples/ExistsJoinRLS/policyRuleDefinitionSets/ExistsJoinRLS.policyRuleDefinitionSet +1 -2
  189. package/skills/platform-policy-rule-generate/references/examples/FieldReadDeny/policyRuleDefinitionSets/FieldReadDeny.policyRuleDefinitionSet +1 -2
  190. package/skills/platform-policy-rule-generate/references/examples/LastCharactersFieldMasking/policyRuleDefinitionSets/LastCharactersFieldMasking.policyRuleDefinitionSet +1 -2
  191. package/skills/platform-policy-rule-generate/references/examples/PrincipalFieldMatchRLS/policyRuleDefinitionSets/PrincipalFieldMatchRLS.policyRuleDefinitionSet +1 -2
  192. package/skills/platform-policy-rule-generate/references/examples/TaggedObjectAccess/policyRuleDefinitionSets/TaggedObjectAccess.policyRuleDefinitionSet +1 -0
  193. package/skills/platform-policy-rule-generate/references/headless-transport.md +2 -2
  194. package/skills/platform-policy-rule-generate/references/policy-schema-full.md +1 -1
  195. package/skills/platform-policy-rule-generate/references/policy-shapes.md +33 -0
  196. package/skills/platform-policy-rule-generate/references/templates-advanced.md +1 -1
  197. package/skills/platform-policy-rule-generate/references/ui-compatibility.md +5 -5
  198. package/skills/platform-report-generate/SKILL.md +29 -8
  199. package/skills/platform-report-generate/references/column-names.md +12 -1
  200. package/skills/platform-report-generate/references/errors-and-troubleshooting.md +1 -1
  201. package/skills/platform-report-generate/references/summary-formulas-sorting-limits.md +118 -0
  202. package/skills/platform-report-generate/references/verification-checklist.md +12 -0
  203. package/skills/platform-sharing-rules-generate/SKILL.md +12 -3
  204. package/skills/platform-sharing-rules-generate/references/rule-types.md +1 -0
  205. package/skills/service-agentforce-channel-configure/SKILL.md +6 -3
  206. package/skills/service-agentforce-channel-configure/references/agent-wiring.md +5 -3
  207. package/skills/service-agentforce-channel-configure/references/channel-branch-email.md +24 -15
  208. package/skills/service-agentforce-channel-configure/references/input-validation.md +23 -0
  209. package/skills/service-agentforce-channel-configure/references/live-traffic-gate.md +13 -7
  210. package/skills/service-agentforce-channel-configure/references/queue-resolution.md +3 -1
  211. package/skills/service-agentforce-human-escalation-configure/references/_vendored/input-validation.md +23 -0
  212. package/skills/service-agentforce-human-escalation-configure/references/_vendored/queue-resolution.md +146 -0
  213. package/skills/service-agentforce-human-escalation-configure/references/escalation-mechanism.md +1 -1
  214. package/skills/service-agentforce-human-escalation-configure/scripts/tests/_bootstrap.py +42 -11
  215. package/skills/service-agentforce-human-escalation-configure/scripts/tests/test_escalation_contracts.py +45 -0
  216. package/skills/service-agentforce-human-escalation-configure/scripts/verify-and-configure.sh +23 -9
  217. package/skills/service-de-channel-activate/SKILL.md +10 -10
  218. package/skills/service-de-channel-activate/references/gotchas.md +4 -4
  219. package/skills/service-de-channel-activate/references/phone-verification.md +43 -19
  220. package/skills/service-de-channel-create/SKILL.md +1 -1
  221. package/skills/service-de-channel-create/references/facebook.md +1 -1
  222. package/skills/service-de-channel-create/references/whatsapp.md +33 -6
  223. package/skills/service-de-channel-routing-configure/SKILL.md +5 -1
  224. package/skills/service-de-channel-routing-configure/references/gotchas.md +3 -1
  225. package/skills/service-de-channel-routing-configure/references/named-queue.md +39 -0
  226. package/skills/service-de-channel-settings-configure/SKILL.md +3 -1
  227. package/skills/service-de-channel-settings-configure/references/channel-settings-facets.md +2 -2
  228. package/skills/service-de-channel-settings-configure/references/gotchas.md +12 -1
  229. package/skills/service-de-headless-channel-configure/SKILL.md +68 -74
  230. package/skills/service-de-headless-channel-configure/references/gotchas.md +6 -2
  231. package/skills/service-de-headless-channel-configure/references/inputs.md +19 -0
  232. package/skills/service-de-headless-channel-configure/references/output-envelopes.md +23 -1
  233. package/skills/service-de-headless-channel-configure/references/partial-success.md +1 -0
  234. package/skills/service-de-headless-channel-configure/references/requested-settings.md +55 -0
  235. package/skills/service-de-headless-channel-configure/references/worked-examples.md +35 -1
  236. package/skills/service-digital-engagement-channel-configure/SKILL.md +45 -108
  237. package/skills/service-digital-engagement-channel-configure/assets/messaging_channel_template.xml +2 -0
  238. package/skills/service-digital-engagement-channel-configure/examples/asa_agent_channel.xml +2 -2
  239. package/skills/service-digital-engagement-channel-configure/examples/auth_queue_channel.xml +58 -0
  240. package/skills/service-digital-engagement-channel-configure/examples/omni_flow_channel.xml +2 -2
  241. package/skills/service-digital-engagement-channel-configure/examples/omni_queue_channel.xml +3 -3
  242. package/skills/service-digital-engagement-channel-configure/references/channel_settings.md +18 -14
  243. package/skills/service-digital-engagement-channel-configure/references/onboarding_contract.md +17 -21
  244. package/skills/service-digital-engagement-channel-configure/references/prechat_params.md +10 -0
  245. package/skills/service-digital-engagement-channel-configure/references/recaptcha_handoff.md +38 -0
  246. package/skills/service-digital-engagement-channel-configure/references/user_verification.md +9 -0
  247. package/skills/service-digital-engagement-channel-configure/scripts/check-api-version.sh +4 -4
  248. package/skills/service-digital-engagement-channel-configure/scripts/normalize-channel-name.sh +12 -7
  249. package/skills/service-digital-engagement-deployment-configure/SKILL.md +2 -2
  250. package/skills/service-digital-engagement-deployment-configure/references/onboarding_contract.md +4 -2
  251. package/skills/service-digital-engagement-deployment-configure/scripts/check-api-version.sh +1 -1
  252. package/skills/service-e911-configure/SKILL.md +242 -0
  253. package/skills/service-itsm-agentic-setup-agent-runtime-access-assign/SKILL.md +1 -1
  254. package/skills/service-itsm-agentic-setup-agentforce-coordinate/SKILL.md +1 -1
  255. package/skills/service-itsm-agentic-setup-agentforce-studio-configure/SKILL.md +1 -1
  256. package/skills/service-itsm-agentic-setup-agentforce-studio-validate/SKILL.md +1 -1
  257. package/skills/service-itsm-agentic-setup-employee-agent-configure/SKILL.md +1 -1
  258. package/skills/service-itsm-agentic-setup-fulfiller-agent-configure/SKILL.md +1 -1
  259. package/skills/service-itsm-agentic-setup-incident-management/SKILL.md +47 -44
  260. package/skills/service-itsm-agentic-setup-incident-management/examples/output-templates.md +110 -83
  261. package/skills/service-itsm-agentic-setup-incident-management/references/manage-incidents-with-ai.md +7 -3
  262. package/skills/service-itsm-agentic-setup-incident-management/references/priority-matrix.md +7 -5
  263. package/skills/service-itsm-agentic-setup-incident-management/references/sla-milestones.md +2 -2
  264. package/skills/service-itsm-agentic-setup-incident-management/references/status-checks.md +437 -0
  265. package/skills/service-itsm-agentic-setup-itsm-agentforce-permset-assign/SKILL.md +1 -1
  266. package/skills/service-omni-command-center-configure/SKILL.md +1 -1
  267. package/skills/agentforce-bot-upgrade/references/planner-workflow-reference.md +0 -78
  268. package/skills/data360-schema-get/SKILL.md +0 -388
  269. package/skills/data360-schema-get/references/README.md +0 -191
  270. package/skills/data360-schema-get/scripts/get_dlo_schema.py +0 -244
  271. package/skills/data360-schema-get/scripts/get_dmo_schema.py +0 -233
  272. package/skills/dx-lifecycle-center/assets/widgets/connect-connected/connect-connected.json +0 -65
  273. package/skills/dx-lifecycle-center/assets/widgets/connect-connected/schema.json +0 -32
  274. package/skills/dx-lifecycle-center/assets/widgets/connect-sign-in/connect-sign-in.json +0 -57
  275. package/skills/dx-lifecycle-center/assets/widgets/connect-sign-in/schema.json +0 -21
  276. package/skills/dx-lifecycle-center/scripts/card-policy.jq +0 -71
  277. package/skills/dx-lifecycle-center/scripts/fill-widget.jq +0 -29
  278. package/skills/dx-lifecycle-center/scripts/widget.sh +0 -28
  279. package/skills/experience-content-media-image-generate/SKILL.md +0 -83
  280. package/skills/experience-content-media-image-generate/scripts/download-image.sh +0 -84
  281. package/skills/experience-content-media-stock-image-search/SKILL.md +0 -193
  282. package/skills/experience-content-media-stock-image-search/scripts/download-stock-image.py +0 -102
  283. package/skills/field-service-prework-brief-deployer-configure/SKILL.md +0 -646
  284. package/skills/field-service-voice-to-form-configure/SKILL.md +0 -650
@@ -0,0 +1,887 @@
1
+ """Offline behavioral coverage for the portable customer-org optimizer skill."""
2
+
3
+ import base64
4
+ import importlib.util
5
+ import io
6
+ import http.client
7
+ from email.utils import formatdate
8
+ import json
9
+ from pathlib import Path
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import time
14
+ from types import SimpleNamespace
15
+ import urllib.error
16
+
17
+ import pytest
18
+
19
+
20
+ SKILL = Path(__file__).resolve().parents[2]
21
+
22
+
23
+ def _load_module(name, path, package=False):
24
+ spec = importlib.util.spec_from_file_location(
25
+ name, path, submodule_search_locations=[str(path.parent)] if package else None)
26
+ module = importlib.util.module_from_spec(spec)
27
+ sys.modules[name] = module
28
+ spec.loader.exec_module(module)
29
+ return module
30
+
31
+
32
+ _load_module("hcopt", SKILL / "scripts/hcopt/__init__.py", package=True)
33
+ from hcopt import client, evaluation, optimizer
34
+ from hcopt import onboarding, eca
35
+
36
+ cli = _load_module("hyperclassifier_skill_cli", SKILL / "scripts/hyperclassifier.py")
37
+ setup_cli = _load_module("hyperclassifier_setup_cli", SKILL / "scripts/setup_hyperclassifier.py")
38
+ report_cli = _load_module("hyperclassifier_report_cli", SKILL / "scripts/report_hyperclassifier.py")
39
+ TOPICS = [{"go_to_orders": "Order help."}, {"go_to_billing": "Billing help."}]
40
+ CASES = [{"id": "1", "utterance": "Track a package", "expected_action": "go_to_orders", "group": "primary"},
41
+ {"id": "2", "utterance": "Duplicate charge", "expected_action": "go_to_billing", "group": "control"}]
42
+ CREDS = {"SF_INSTANCE_URL": "https://example.my.salesforce.com", "SF_CLIENT_ID": "private-id",
43
+ "SF_CLIENT_SECRET": "private-secret"}
44
+
45
+
46
+ def envelope(action="go_to_orders", probability=0.8):
47
+ """Build a realistic score envelope for deterministic transport-free tests."""
48
+ other = "go_to_billing" if action == "go_to_orders" else "go_to_orders"
49
+ return {"generation_details": {"generations": [
50
+ {"content": action, "parameters": {"probability": probability}},
51
+ {"content": other, "parameters": {"probability": 1 - probability}},
52
+ ]}}
53
+
54
+
55
+ def jwt(expiry=None):
56
+ """Create structurally valid test tokens without real credentials."""
57
+ encode = lambda obj: base64.urlsafe_b64encode(json.dumps(obj).encode()).decode().rstrip("=")
58
+ return encode({"alg": "RS256"}) + "." + encode({"exp": expiry or time.time() + 1800}) + ".signature"
59
+
60
+
61
+ class FakeClient:
62
+ """Control classifier outcomes and proposals while recording what was sent."""
63
+
64
+ def __init__(self, predictions, proposals=()):
65
+ self.predictions = iter(predictions)
66
+ self.proposals = iter(proposals)
67
+ self.calls = self.http_attempts = 0
68
+ self.prompts = []
69
+
70
+ def classify(self, utterance, topics):
71
+ self.calls += 1
72
+ self.http_attempts += 1
73
+ item = next(self.predictions)
74
+ if isinstance(item, BaseException):
75
+ raise item
76
+ return envelope(item)
77
+
78
+ def propose(self, model, prompt):
79
+ self.calls += 1
80
+ self.http_attempts += 1
81
+ self.prompts.append(prompt)
82
+ return next(self.proposals)
83
+
84
+ def check_proposer(self, model):
85
+ self.calls += 1
86
+ self.http_attempts += 1
87
+
88
+
89
+ def args_for(output, **changes):
90
+ """Return a small optimizer configuration with a bounded test budget."""
91
+ values = dict(output_dir=output, max_rounds=2, patience=2, repeats=1, target_accuracy=1.0,
92
+ proposer_model="example_model", max_calls=20)
93
+ values.update(changes)
94
+ return SimpleNamespace(**values)
95
+
96
+
97
+ def proposal(description="Existing order help, including tracking."):
98
+ """Change one boundary without changing action names."""
99
+ return json.dumps({"rationale": "Clarify tracking scope", "changes": {"go_to_orders": description}})
100
+
101
+
102
+ @pytest.mark.parametrize("folder", [".claude/skills", ".agents/skills", ".opencode/skills"])
103
+ def test_copied_skill_runs_without_source_repo_or_credentials(tmp_path, folder):
104
+ installed = tmp_path / "project with spaces" / folder / SKILL.name
105
+ shutil.copytree(SKILL, installed, ignore=shutil.ignore_patterns("__pycache__"))
106
+ output = tmp_path / "must-not-be-created"
107
+ process = subprocess.run([sys.executable, "-B", str(installed / "scripts/hyperclassifier.py"), "evaluate",
108
+ "--evals", str(installed / "assets/sample_evals.csv"),
109
+ "--descriptions", str(installed / "assets/sample_descriptions.json"),
110
+ "--env-file", str(tmp_path / "missing-secret.env"),
111
+ "--output-dir", str(output), "--dry-run"],
112
+ cwd=tmp_path, capture_output=True, text=True)
113
+ assert process.returncode == 0, process.stderr
114
+ assert "16 cases, 6 actions" in process.stdout
115
+ assert not output.exists()
116
+
117
+
118
+ def test_inputs_bom_and_unknown_expected_action(tmp_path):
119
+ descriptions = tmp_path / "descriptions.json"
120
+ descriptions.write_text(json.dumps(TOPICS))
121
+ cases = tmp_path / "evals.csv"
122
+ cases.write_text("\ufeffutterance,expected_action\nTrack order,go_to_orders\n", encoding="utf-8")
123
+ loaded, topics = evaluation.load_inputs(cases, descriptions)
124
+ assert loaded[0]["id"] == "1" and topics == TOPICS
125
+ cases.write_text("utterance,expected_action\nTrack order,unknown\n")
126
+ with pytest.raises(ValueError, match="unknown expected"):
127
+ evaluation.load_inputs(cases, descriptions)
128
+
129
+
130
+ def test_duplicate_case_ids_rejected(tmp_path):
131
+ descriptions, cases = tmp_path / "descriptions.json", tmp_path / "evals.jsonl"
132
+ descriptions.write_text(json.dumps(TOPICS))
133
+ cases.write_text("\n".join(json.dumps(CASES[0]) for _ in range(2)))
134
+ with pytest.raises(ValueError, match="duplicate id"):
135
+ evaluation.load_inputs(cases, descriptions)
136
+
137
+
138
+ @pytest.mark.parametrize("bad", [True, float("nan"), float("inf"), -0.1, 1.01, "0.5", None, 10**400])
139
+ def test_invalid_probability_is_contract_error(bad):
140
+ data = envelope()
141
+ data["generation_details"]["generations"][0]["parameters"]["probability"] = bad
142
+ with pytest.raises(client.ServiceError, match="invalid probability"):
143
+ evaluation.parse_prediction(data, ["go_to_orders", "go_to_billing"])
144
+
145
+
146
+ @pytest.mark.parametrize("mutation", ["missing", "duplicate", "unknown"])
147
+ def test_score_set_must_match_all_actions(mutation):
148
+ data = envelope()
149
+ scores = data["generation_details"]["generations"]
150
+ if mutation == "missing":
151
+ scores.pop()
152
+ elif mutation == "duplicate":
153
+ scores[1]["content"] = scores[0]["content"]
154
+ else:
155
+ scores[1]["content"] = "unknown"
156
+ with pytest.raises(client.ServiceError):
157
+ evaluation.parse_prediction(data, ["go_to_orders", "go_to_billing"])
158
+
159
+
160
+ def test_ties_keep_endpoint_order():
161
+ result = evaluation.parse_prediction(envelope("go_to_billing", 0.5), ["go_to_orders", "go_to_billing"])
162
+ assert result["actual_action"] == "go_to_billing" and result["top_tie"] and result["margin"] == 0
163
+
164
+
165
+ def test_credentials_are_literal_data_and_private(tmp_path, monkeypatch):
166
+ for name in client.CREDENTIAL_KEYS:
167
+ monkeypatch.delenv(name, raising=False)
168
+ path = tmp_path / "org.env"
169
+ path.write_text("SF_INSTANCE_URL=https://example.my.salesforce.com\nSF_CLIENT_ID=id\n"
170
+ "SF_CLIENT_SECRET='$(touch should-not-exist)'\n")
171
+ path.chmod(0o600)
172
+ assert client.load_credentials(path)["SF_CLIENT_SECRET"] == "$(touch should-not-exist)"
173
+ assert not (tmp_path / "should-not-exist").exists()
174
+ path.chmod(0o644)
175
+ with pytest.raises(ValueError, match="private"):
176
+ client.load_credentials(path)
177
+
178
+
179
+ @pytest.mark.parametrize("origin", ["http://example.my.salesforce.com", "https://evil.example", "https://example.my.salesforce.com.evil.example",
180
+ "https://user@example.my.salesforce.com", "https://example.my.salesforce.com/path",
181
+ "https://example.my.salesforce.com:8443"])
182
+ def test_credentials_never_sent_to_arbitrary_origin(monkeypatch, origin):
183
+ for key, value in CREDS.items():
184
+ monkeypatch.setenv(key, value)
185
+ monkeypatch.setenv("SF_INSTANCE_URL", origin)
186
+ with pytest.raises(ValueError, match="My Domain"):
187
+ client.load_credentials()
188
+
189
+
190
+ def test_redirect_is_refused():
191
+ assert client.NoRedirect().redirect_request(None, None, 302, "Found", {}, "https://evil.example") is None
192
+
193
+
194
+ def test_http_error_body_never_leaks_and_retry_is_bounded(monkeypatch):
195
+ attempts = []
196
+ def fail(*args, **kwargs):
197
+ attempts.append(1)
198
+ raise urllib.error.HTTPError("https://api.salesforce.com", 503, "private-secret", {}, io.BytesIO(b"private-secret"))
199
+ transport = client.Client(CREDS, retries=1)
200
+ monkeypatch.setattr(transport.opener, "open", fail)
201
+ monkeypatch.setattr(client.time, "sleep", lambda value: None)
202
+ status, data = transport._request(client.API, b"{}", {})
203
+ assert status == 503 and data == {} and len(attempts) == 2
204
+
205
+
206
+ def test_401_refreshes_once_and_keeps_expected_labels_out(monkeypatch):
207
+ transport = client.Client(CREDS)
208
+ requests = []
209
+ responses = iter([(200, {"access_token": jwt()}), (401, {}), (200, {"access_token": jwt()}), (200, envelope())])
210
+ def request(url, body, headers):
211
+ requests.append((url, body, headers))
212
+ return next(responses)
213
+ monkeypatch.setattr(transport, "_request", request)
214
+ transport.classify("Track order", TOPICS)
215
+ assert len(requests) == 4 and transport.calls == 1
216
+ payload = json.loads(requests[-1][1])
217
+ assert payload["topics_config"]["topics"] == TOPICS
218
+ assert "expected_action" not in json.dumps(payload)
219
+ assert requests[-1][0] == client.API + client.CLASSIFIER_PATH
220
+
221
+
222
+ def test_second_401_stops(monkeypatch):
223
+ transport = client.Client(CREDS)
224
+ responses = iter([(200, {"access_token": jwt()}), (401, {}), (200, {"access_token": jwt()}), (401, {})])
225
+ monkeypatch.setattr(transport, "_request", lambda *args: next(responses))
226
+ with pytest.raises(client.ServiceError, match="HTTP 401"):
227
+ transport.classify("Track order", TOPICS)
228
+
229
+
230
+ @pytest.mark.parametrize("token", ["not-a-jwt", "abc.def.signature", jwt(time.time() - 10), jwt() + "\r\n", jwt(10**400)])
231
+ def test_invalid_or_expired_jwt_rejected(token):
232
+ with pytest.raises(client.ServiceError):
233
+ client.jwt_expiry(token)
234
+
235
+
236
+ def test_call_budget_prevents_authentication(monkeypatch):
237
+ transport = client.Client(CREDS, max_calls=1)
238
+ transport.calls = 1
239
+ monkeypatch.setattr(transport, "_authenticate", lambda: pytest.fail("must not authenticate"))
240
+ with pytest.raises(client.ServiceError, match="budget"):
241
+ transport.classify("Track order", TOPICS)
242
+
243
+
244
+ def test_evaluation_reports_repeated_mismatches_and_preserves_inputs(tmp_path):
245
+ original = json.dumps(CASES)
246
+ fake = FakeClient(["go_to_orders", "go_to_orders", "go_to_orders", "go_to_billing"])
247
+ rows = evaluation.evaluate(fake, CASES, TOPICS, tmp_path / "eval", repeats=2)
248
+ report = json.loads((tmp_path / "eval/summary.json").read_text())
249
+ assert len(rows) == 4 and report["pass"] == 3 and report["fail"] == 1
250
+ assert report["cases_passing_every_repeat"] == 1
251
+ assert report["cases_with_varying_predictions"] == 1
252
+ assert report["groups"]["control"]["accuracy"] == 0.5
253
+ assert json.dumps(CASES) == original
254
+
255
+
256
+ def test_service_failure_checkpoints_and_stops_without_fabricating_rows(tmp_path):
257
+ fake = FakeClient(["go_to_orders", client.ServiceError("HTTP 403")])
258
+ folder = tmp_path / "error"
259
+ rows = evaluation.evaluate(fake, CASES, TOPICS, folder, repeats=3)
260
+ run = json.loads((folder / "run.json").read_text())
261
+ assert len(rows) == 2 and run["state"] == "service_error"
262
+ assert run["planned_predictions"] == 6 and run["completed_predictions"] == 2
263
+ assert json.loads((folder / "summary.json").read_text())["error"] == 1
264
+
265
+
266
+ def test_interruption_preserves_completed_results(tmp_path):
267
+ folder = tmp_path / "interrupted"
268
+ with pytest.raises(KeyboardInterrupt):
269
+ evaluation.evaluate(FakeClient(["go_to_orders", KeyboardInterrupt()]), CASES, TOPICS, folder)
270
+ assert json.loads((folder / "run.json").read_text())["state"] == "interrupted"
271
+ assert len((folder / "results.jsonl").read_text().splitlines()) == 1
272
+
273
+
274
+ def test_optimizer_accepts_only_measured_improvement(tmp_path):
275
+ fake = FakeClient(["go_to_orders", "go_to_orders", "go_to_orders", "go_to_billing"], [proposal()])
276
+ state = optimizer.optimize(fake, args_for(tmp_path / "loop"), CASES, TOPICS)
277
+ assert state["state"] == "target_reached" and state["best_round"] == 1
278
+ assert state["baseline"]["pass"] == 1 and state["best_summary"]["pass"] == 2
279
+ assert (tmp_path / "loop/round_001/descriptions.diff").is_file()
280
+ best = json.loads((tmp_path / "loop/best_descriptions.json").read_text())
281
+ assert best[1] == TOPICS[1] and best[0] != TOPICS[0]
282
+
283
+
284
+ def test_optimizer_rejects_regression_and_duplicate_then_stops(tmp_path):
285
+ fake = FakeClient(["go_to_orders", "go_to_orders", "go_to_billing", "go_to_billing"], [proposal(), proposal()])
286
+ state = optimizer.optimize(fake, args_for(tmp_path / "loop"), CASES, TOPICS)
287
+ assert state["state"] == "plateau" and state["best_round"] == 0
288
+ assert [d["reason"] for d in state["history"]] == ["previous_pass_regressed", "duplicate_candidate"]
289
+ assert fake.calls == 7
290
+ assert json.loads((tmp_path / "loop/best_descriptions.json").read_text()) == TOPICS
291
+
292
+
293
+ @pytest.mark.parametrize("text", ['{"rationale":"x","changes":{"new_action":"x"}}',
294
+ '{"rationale":"x","changes":{},"labels":[]}', "not-json"])
295
+ def test_invalid_proposal_cannot_relabel_or_add_actions(text):
296
+ with pytest.raises(ValueError):
297
+ optimizer.candidate_from_text(text, TOPICS)
298
+
299
+
300
+ def test_holdout_never_enters_proposal_or_selection(tmp_path):
301
+ holdout = [{**CASES[0], "utterance": "UNSEEN HELD OUT TEXT"}]
302
+ fake = FakeClient(["go_to_orders", "go_to_orders", "go_to_orders", "go_to_billing", "go_to_billing"], [proposal()])
303
+ state = optimizer.optimize(fake, args_for(tmp_path / "loop"), CASES, TOPICS, holdout)
304
+ assert state["holdout"]["fail"] == 1 and state["best_round"] == 1
305
+ assert "UNSEEN HELD OUT TEXT" not in fake.prompts[0]
306
+
307
+
308
+ def test_budget_and_holdout_overlap_rejected_before_network(tmp_path):
309
+ descriptions, cases = tmp_path / "descriptions.json", tmp_path / "evals.jsonl"
310
+ descriptions.write_text(json.dumps(TOPICS))
311
+ cases.write_text("\n".join(json.dumps(row) for row in CASES))
312
+ args = cli.build_parser().parse_args(["optimize", "--evals", str(cases), "--descriptions", str(descriptions),
313
+ "--output-dir", str(tmp_path / "new"), "--max-calls", "1"])
314
+ with pytest.raises(ValueError, match="Worst-case plan"):
315
+ cli.prepare(args)
316
+ args.max_calls = 100
317
+ args.holdout = cases
318
+ with pytest.raises(ValueError, match="overlaps"):
319
+ cli.prepare(args)
320
+
321
+
322
+ def test_gate_rejects_changed_labels_and_incomplete_results():
323
+ previous = [{**CASES[0], "iteration": 1, "status": "fail", "actual_action": "go_to_billing"}]
324
+ candidate = [{**previous[0], "expected_action": "go_to_billing", "status": "pass"}]
325
+ assert optimizer.gate(previous, candidate) == (False, "evaluation_inputs_changed")
326
+ assert optimizer.gate(previous, []) == (False, "incomplete_or_duplicate_results")
327
+
328
+
329
+ def test_proposer_uses_documented_generation_contract(monkeypatch):
330
+ transport = client.Client(CREDS)
331
+ requests = []
332
+ def post(path, payload):
333
+ requests.append((path, payload))
334
+ return {"generation": {"generatedText": proposal()}}
335
+ monkeypatch.setattr(transport, "post", post)
336
+ assert transport.propose("example_model", "test prompt") == proposal()
337
+ assert requests == [("/einstein/platform/v1/models/example_model/generations", {"prompt": "test prompt"})]
338
+
339
+
340
+ def test_service_error_during_candidate_preserves_previous_best(tmp_path):
341
+ fake = FakeClient(["go_to_orders", "go_to_orders", client.ServiceError("HTTP 403")], [proposal()])
342
+ folder = tmp_path / "loop"
343
+ with pytest.raises(client.ServiceError):
344
+ optimizer.optimize(fake, args_for(folder), CASES, TOPICS)
345
+ state = json.loads((folder / "experiment.json").read_text())
346
+ assert state["state"] == "service_error" and state["best_round"] == 0
347
+ assert json.loads((folder / "best_descriptions.json").read_text()) == TOPICS
348
+
349
+
350
+ def test_holdout_interrupt_is_not_reported_as_completed_target(tmp_path):
351
+ fake = FakeClient(["go_to_orders", "go_to_billing", KeyboardInterrupt()])
352
+ folder = tmp_path / "loop"
353
+ with pytest.raises(KeyboardInterrupt):
354
+ optimizer.optimize(fake, args_for(folder), CASES, TOPICS, [{**CASES[0], "utterance": "Unseen case"}])
355
+ assert json.loads((folder / "experiment.json").read_text())["state"] == "interrupted"
356
+
357
+
358
+ def test_csv_formulas_escaped_but_jsonl_preserves_utterance(tmp_path):
359
+ cases = [{**CASES[0], "utterance": "=SUM(1+2)"}]
360
+ evaluation.evaluate(FakeClient(["go_to_orders"]), cases, TOPICS, tmp_path / "eval")
361
+ assert "'=SUM(1+2)" in (tmp_path / "eval/results.csv").read_text()
362
+ assert json.loads((tmp_path / "eval/results.jsonl").read_text())["utterance"] == "=SUM(1+2)"
363
+
364
+
365
+ def test_expiring_token_is_refreshed_before_inference(monkeypatch):
366
+ transport = client.Client(CREDS)
367
+ transport.token, transport.expires = "old-token", time.time() + 5
368
+ requests = []
369
+ def request(url, body, headers):
370
+ requests.append(url)
371
+ return (200, {"access_token": jwt()}) if url.endswith("/token") else (200, envelope())
372
+ monkeypatch.setattr(transport, "_request", request)
373
+ transport.classify("Track package", TOPICS)
374
+ assert requests[0].endswith("/services/oauth2/token")
375
+ assert requests[1] == client.API + client.CLASSIFIER_PATH
376
+
377
+
378
+ ORG = {"org_id": "00D000000000001AAA", "alias": "customer", "username": "admin@example.com",
379
+ "instance_url": "https://example.my.salesforce.com", "api_version": "68.0"}
380
+
381
+
382
+ def test_org_discovery_redacts_all_authentication_fields(monkeypatch):
383
+ result = {"id": ORG["org_id"], "alias": ORG["alias"], "username": ORG["username"],
384
+ "instanceUrl": ORG["instance_url"], "apiVersion": "68.0", "accessToken": "secret-session",
385
+ "clientId": "private-client", "sfdxAuthUrl": "private-refresh-token"}
386
+ calls = []
387
+ monkeypatch.setattr(onboarding, "sf", lambda args: calls.append(args) or result)
388
+ resolved = onboarding.resolve_org()
389
+ assert resolved == ORG and calls == [["org", "display"]]
390
+ assert "secret" not in json.dumps(resolved) and "private" not in json.dumps(resolved)
391
+ monkeypatch.setattr(onboarding, "sf", lambda args: [result])
392
+ assert "accessToken" not in onboarding.discover_orgs()[0]
393
+
394
+
395
+ def test_new_cli_secret_command_only_returns_token_in_memory(monkeypatch):
396
+ replies = iter([{"username": "admin@example.com"}, {"accessToken": "private-session"}])
397
+ calls = []
398
+ def sf(args):
399
+ calls.append(args)
400
+ return next(replies)
401
+ monkeypatch.setattr(onboarding, "sf", sf)
402
+ assert onboarding.read_org_session("customer") == "private-session"
403
+ assert calls[-1] == ["org", "auth", "show-access-token", "--target-org", "customer"]
404
+
405
+
406
+ def test_cli_failure_never_exposes_raw_secret_output(monkeypatch, capsys):
407
+ monkeypatch.setattr(onboarding.shutil, "which", lambda name: "/fake/sf")
408
+ monkeypatch.setattr(onboarding.subprocess, "run", lambda *a, **k: SimpleNamespace(
409
+ returncode=1, stdout=json.dumps({"status": 1, "name": "AuthError", "message": "private-token"}), stderr="private-token"))
410
+ with pytest.raises(ValueError, match="AuthError") as error:
411
+ onboarding.sf(["org", "display"])
412
+ assert "private-token" not in str(error.value)
413
+ assert "private-token" not in str(capsys.readouterr())
414
+
415
+
416
+ def test_eca_discovery_uses_cli_tooling_session_without_gateway(monkeypatch):
417
+ calls = []
418
+ def sf(args):
419
+ calls.append(args)
420
+ return {"records": [{"Id": "example-app", "DeveloperName": onboarding.APP_NAME,
421
+ "MasterLabel": onboarding.APP_LABEL, "accessToken": "must-not-escape"}]}
422
+ monkeypatch.setattr(onboarding, "sf", sf)
423
+ records = onboarding.discover_eca(ORG)
424
+ assert "--use-tooling-api" in calls[0]
425
+ assert "ExternalClientApplication" in calls[0][-1]
426
+ assert "must-not-escape" not in json.dumps(records)
427
+
428
+
429
+ def test_failed_eca_query_is_not_treated_as_missing(monkeypatch):
430
+ def sf(args):
431
+ raise ValueError("insufficient permissions")
432
+ monkeypatch.setattr(onboarding, "sf", sf)
433
+ with pytest.raises(ValueError, match="permissions"):
434
+ onboarding.discover_eca(ORG)
435
+
436
+
437
+ def test_missing_eca_inspect_offers_onboarding_without_creating_app(monkeypatch, capsys, tmp_path):
438
+ monkeypatch.setattr(setup_cli, "resolve_org", lambda target: ORG)
439
+ monkeypatch.setattr(setup_cli, "discover_eca", lambda *args: [])
440
+ monkeypatch.setattr(setup_cli, "deploy_eca", lambda *args: pytest.fail("No permission to deploy"))
441
+ assert setup_cli.main(["inspect", "--workspace", str(tmp_path / "new")]) == 0
442
+ result = json.loads(capsys.readouterr().out)
443
+ assert result["next_step"] == "ask_for_existing_eca_credentials_or_create_eca"
444
+ assert result["cli_session_is_gateway_auth"] is False
445
+ assert not (tmp_path / "new").exists()
446
+
447
+
448
+ def test_private_saved_credentials_are_bound_to_org_and_reused(tmp_path, monkeypatch):
449
+ workspace = onboarding.initialize_workspace(ORG, tmp_path / "profile")
450
+ source = tmp_path / "source.env"
451
+ source.write_text("\n".join(k + "=" + v for k, v in CREDS.items()))
452
+ source.chmod(0o600)
453
+ destination = onboarding.save_credentials(ORG, workspace, source)
454
+ assert destination.stat().st_mode & 0o077 == 0
455
+ assert client.load_credentials(destination) == CREDS
456
+ monkeypatch.setattr(onboarding, "resolve_org", lambda alias: ORG)
457
+ values = onboarding.credentials_for_run(SimpleNamespace(target_org="customer", env_file=None, workspace=workspace))
458
+ assert values == CREDS
459
+ with pytest.raises(ValueError, match="already saved"):
460
+ onboarding.save_credentials(ORG, workspace, source)
461
+
462
+
463
+ def test_workspace_and_credentials_cannot_cross_orgs(tmp_path):
464
+ workspace = onboarding.initialize_workspace(ORG, tmp_path / "profile")
465
+ with pytest.raises(ValueError, match="different org"):
466
+ onboarding.initialize_workspace({**ORG, "org_id": "00D000000000002AAA"}, workspace)
467
+ source = tmp_path / "wrong.env"
468
+ source.write_text("SF_INSTANCE_URL=https://different.my.salesforce.com\nSF_CLIENT_ID=id\nSF_CLIENT_SECRET=secret\n")
469
+ source.chmod(0o600)
470
+ with pytest.raises(ValueError, match="different org origin"):
471
+ onboarding.save_credentials(ORG, workspace, source)
472
+ assert not (workspace / "credentials.env").exists()
473
+
474
+
475
+ def test_existing_project_cannot_become_credential_workspace(tmp_path):
476
+ (tmp_path / "source.py").write_text("print('project')")
477
+ with pytest.raises(ValueError, match="empty private workspace"):
478
+ onboarding.initialize_workspace(ORG, tmp_path)
479
+
480
+
481
+ def test_cli_session_token_never_substitutes_for_missing_eca_credentials(tmp_path, monkeypatch):
482
+ for key in client.CREDENTIAL_KEYS:
483
+ monkeypatch.delenv(key, raising=False)
484
+ monkeypatch.setattr(onboarding, "resolve_org", lambda alias=None: ORG)
485
+ monkeypatch.setattr(onboarding, "workspace_path", lambda org: tmp_path)
486
+ monkeypatch.setattr(onboarding, "read_org_session", lambda target: pytest.fail("Must not use CLI session for inference"))
487
+ with pytest.raises(ValueError, match="onboarding required"):
488
+ onboarding.credentials_for_run(SimpleNamespace(target_org="customer", env_file=None, workspace=None))
489
+
490
+
491
+ def test_eca_prepare_has_only_required_scopes_and_no_secrets(tmp_path, monkeypatch):
492
+ monkeypatch.setattr(eca, "discover_eca", lambda *args: [])
493
+ monkeypatch.setattr(eca, "sf", lambda *args: {"records": [{"Username": "admin@example.com", "IsActive": True}]})
494
+ plan = eca.prepare_eca(ORG, tmp_path, "admin@example.com", "admin@example.com")
495
+ assert plan["state"] == "prepared" and plan["scopes"] == ["api", "refresh_token", "sfap_api"]
496
+ xml = "\n".join(p.read_text() for p in (tmp_path / "eca").rglob("*.xml"))
497
+ assert "isNamedUserJwtEnabled>true" in xml
498
+ assert "clientSecret" not in xml and "<userPermissions>" not in xml and ">Full<" not in xml
499
+
500
+
501
+ def test_eca_prepare_rejects_existing_app(tmp_path, monkeypatch):
502
+ monkeypatch.setattr(eca, "discover_eca", lambda *args: [{"Id": "existing"}])
503
+ with pytest.raises(ValueError, match="already exists"):
504
+ eca.prepare_eca(ORG, tmp_path, "admin@example.com", "admin@example.com")
505
+ assert not (tmp_path / "eca").exists()
506
+
507
+
508
+ @pytest.mark.parametrize("run_as", [None, "", "integration@example.com", ORG["username"]])
509
+ def test_prepare_cli_warns_only_for_implicit_run_as(tmp_path, monkeypatch, capsys, run_as):
510
+ selected_user = run_as or ORG["username"]
511
+ monkeypatch.setattr(setup_cli, "resolve_org", lambda target: ORG)
512
+ monkeypatch.setattr(eca, "discover_eca", lambda *args: [])
513
+ queries = []
514
+ def sf(arguments):
515
+ queries.append(arguments)
516
+ return {"records": [{"Username": selected_user, "IsActive": True}]}
517
+ monkeypatch.setattr(eca, "sf", sf)
518
+ arguments = ["prepare-eca", "--workspace", str(tmp_path), "--contact-email", "contact@example.com"]
519
+ if run_as is not None:
520
+ arguments.extend(["--run-as", run_as])
521
+ assert setup_cli.main(arguments) == 0
522
+ captured = capsys.readouterr()
523
+ result = json.loads(captured.out)
524
+ saved_plan = json.loads((tmp_path / "eca/plan.json").read_text())
525
+ assert result["plan"]["run_as"] == saved_plan["run_as"] == selected_user
526
+ assert result["deployed"] is False
527
+ assert len(queries) == 1 and queries[0][:2] == ["data", "query"]
528
+ assert f"Username = '{selected_user}'" in queries[0][-1]
529
+ if not run_as:
530
+ assert len(result["warnings"]) == 1
531
+ warning = result["warnings"][0]
532
+ assert selected_user in warning and "--run-as" in warning
533
+ assert "permissions" in warning and "dedicated integration user" in warning
534
+ assert captured.err == f"Warning: {warning}\n"
535
+ else:
536
+ assert result["warnings"] == [] and captured.err == ""
537
+
538
+
539
+ def test_eca_policy_is_retrieved_and_backed_up_before_edit(tmp_path, monkeypatch):
540
+ monkeypatch.setattr(eca, "discover_eca", lambda *args: [])
541
+ monkeypatch.setattr(eca, "sf", lambda *args: {"records": [{"Username": "admin@example.com"}]})
542
+ plan = eca.prepare_eca(ORG, tmp_path, "admin@example.com", "admin@example.com")
543
+ calls = []
544
+ def sf(args, cwd=None, timeout=None):
545
+ calls.append(args)
546
+ if args[:3] == ["project", "deploy", "start"]:
547
+ return {"id": "0Af000000000001AAA", "status": "Succeeded"}
548
+ if args[:3] == ["project", "retrieve", "start"]:
549
+ base = cwd / "force-app/main/default"
550
+ app = plan["app_name"]
551
+ eca._xml(base / f"extlClntAppOauthPolicies/{app}_oauth_defaultPolicy.ecaOauthPlcy-meta.xml",
552
+ "ExtlClntAppOauthConfigurablePolicies", {"externalClientApplication": app, "refreshTokenPolicyType": "SpecificLifetime"})
553
+ eca._xml(base / f"extlClntAppPolicies/{app}_defaultPolicy.ecaPlcy-meta.xml",
554
+ "ExtlClntAppConfigurablePolicies", {"externalClientApplication": app})
555
+ return {"status": "Succeeded"}
556
+ return {"successes": ["assigned"], "failures": []}
557
+ monkeypatch.setattr(eca, "sf", sf)
558
+ result = eca.deploy_eca(ORG, tmp_path)
559
+ assert result["state"] == "awaiting_credentials"
560
+ assert len(list((tmp_path / "eca/retrieved-policy-backup").glob("*.xml"))) == 2
561
+ policy = next((tmp_path / "eca/force-app/main/default/extlClntAppOauthPolicies").glob("*.xml")).read_text()
562
+ assert "SpecificLifetime" in policy and "AdminApprovedPreAuthorized" in policy and ">Enforce<" in policy
563
+ assert calls[-1][-2:] == ["--on-behalf-of", "admin@example.com"]
564
+ with pytest.raises(ValueError, match="already attempted"):
565
+ eca.deploy_eca(ORG, tmp_path)
566
+
567
+
568
+ def test_deploy_preview_cannot_mutate_org(monkeypatch, tmp_path, capsys):
569
+ workspace = onboarding.initialize_workspace(ORG, tmp_path / "profile")
570
+ (workspace / "eca").mkdir()
571
+ (workspace / "eca/plan.json").write_text('{"state":"prepared"}')
572
+ monkeypatch.setattr(setup_cli, "resolve_org", lambda alias: ORG)
573
+ monkeypatch.setattr(setup_cli, "deploy_eca", lambda *args: pytest.fail("No --apply"))
574
+ assert setup_cli.main(["deploy-eca", "--workspace", str(workspace)]) == 0
575
+ assert "Review this plan" in capsys.readouterr().out
576
+
577
+
578
+ def test_report_shows_the_actual_utterance_expected_and_predicted_action(tmp_path):
579
+ cases = [{**CASES[0], "utterance": "<b>track|package</b>"}]
580
+ evaluation.evaluate(FakeClient(["go_to_billing"]), cases, TOPICS, tmp_path / "run")
581
+ rendered = report_cli.report(tmp_path / "run", failures_only=True)
582
+ assert "&lt;b&gt;track\\|package&lt;/b&gt;" in rendered
583
+ assert "go_to_orders" in rendered and "go_to_billing" in rendered and "1/1 predictions completed" in rendered
584
+
585
+
586
+ @pytest.mark.parametrize('partition', ['', 'sandbox.', 'develop.', 'scratch.', 'demo.', 'trailblaze.', 'patch.'])
587
+ def test_verified_my_domain_partitions_work_for_cli_and_credentials(monkeypatch, partition):
588
+ origin = 'https://example.' + partition + 'my.salesforce.com'
589
+ for key, value in dict(CREDS, SF_INSTANCE_URL=origin).items():
590
+ monkeypatch.setenv(key, value)
591
+ monkeypatch.setattr(onboarding, 'sf', lambda args: {
592
+ 'id': ORG['org_id'], 'username': ORG['username'], 'instanceUrl': origin})
593
+ assert client.load_credentials()['SF_INSTANCE_URL'] == origin
594
+ assert onboarding.resolve_org('customer')['instance_url'] == origin
595
+
596
+
597
+ @pytest.mark.parametrize('origin', ['https://example.unknown.my.salesforce.com',
598
+ 'https://a.b.develop.my.salesforce.com', 'https://example.develop.my.salesforce.com.evil.test',
599
+ 'https://user@example.scratch.my.salesforce.com', 'http://example.demo.my.salesforce.com',
600
+ 'https://example.trailblaze.my.salesforce.com:443', 'https://example.patch.my.salesforce.com/path',
601
+ 'https://example.my.salesforce.com?secret=x', 'https://example.my.salesforce.com#fragment'])
602
+ def test_partition_support_preserves_secret_destination_boundary(origin):
603
+ with pytest.raises(ValueError, match='My Domain'):
604
+ client.my_domain_origin(origin)
605
+
606
+
607
+ @pytest.mark.parametrize('wire', [b'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\n{}',
608
+ b'private-response-data\r\n', b'x' * 66000 + b'\r\n'])
609
+ def test_http_protocol_failure_retries_and_records_sanitized_error(tmp_path, monkeypatch, wire):
610
+ class Socket:
611
+ def makefile(self, *args):
612
+ return io.BytesIO(wire)
613
+ calls = []
614
+ def open_response(*args, **kwargs):
615
+ calls.append(1)
616
+ response = http.client.HTTPResponse(Socket())
617
+ response.begin()
618
+ return response
619
+ transport = client.Client(CREDS, retries=1)
620
+ transport.token, transport.expires = 'synthetic-token', time.time() + 1800
621
+ monkeypatch.setattr(transport.opener, 'open', open_response)
622
+ monkeypatch.setattr(client.time, 'sleep', lambda delay: None)
623
+ rows = evaluation.evaluate(transport, CASES, TOPICS, tmp_path / 'run')
624
+ assert len(calls) == 2 and len(rows) == 1 and rows[0]['status'] == 'error'
625
+ assert 'private-response-data' not in json.dumps(rows)
626
+ assert json.loads((tmp_path / 'run/run.json').read_text())['state'] == 'service_error'
627
+
628
+
629
+ @pytest.mark.parametrize('value,expected', [('20', 20), ('date', 20), ('invalid', 1), ('0', 0)])
630
+ def test_retry_after_honored_in_request(monkeypatch, value, expected):
631
+ now = 1700000000
632
+ monkeypatch.setattr(client.time, 'time', lambda: now)
633
+ if value == 'date':
634
+ value = formatdate(now + 20, usegmt=True)
635
+ attempts, delays = [], []
636
+ def open_response(*args, **kwargs):
637
+ attempts.append(1)
638
+ if len(attempts) == 1:
639
+ raise urllib.error.HTTPError(client.API, 429, 'limited', {'Retry-After': value}, io.BytesIO())
640
+ return io.BytesIO(b'{}')
641
+ transport = client.Client(CREDS, retries=1)
642
+ monkeypatch.setattr(transport.opener, 'open', open_response)
643
+ monkeypatch.setattr(client.time, 'sleep', delays.append)
644
+ assert transport._request(client.API, b'{}', {}) == (200, {})
645
+ assert len(attempts) == 2 and delays == [expected]
646
+
647
+
648
+ @pytest.mark.parametrize('value', ['31', '9' * 5000, 'date'])
649
+ def test_long_retry_after_stops_without_early_retry(monkeypatch, value):
650
+ if value == 'date':
651
+ value = formatdate(time.time() + 120, usegmt=True)
652
+ attempts = []
653
+ def limited(*args, **kwargs):
654
+ attempts.append(1)
655
+ raise urllib.error.HTTPError(client.API, 503, 'limited', {'Retry-After': value}, io.BytesIO())
656
+ transport = client.Client(CREDS, retries=3)
657
+ monkeypatch.setattr(transport.opener, 'open', limited)
658
+ monkeypatch.setattr(client.time, 'sleep', lambda delay: pytest.fail('must not retry early'))
659
+ with pytest.raises(client.ServiceError, match='retry later'):
660
+ transport._request(client.API, b'{}', {})
661
+ assert len(attempts) == 1
662
+
663
+
664
+ @pytest.mark.parametrize('ids,valid', [([0, 1], True), ([0, 0], False)])
665
+ def test_numeric_zero_ids_preserved_and_duplicates_rejected(tmp_path, ids, valid):
666
+ data, descriptions = tmp_path / 'data.jsonl', tmp_path / 'descriptions.json'
667
+ data.write_text('\n'.join(json.dumps(dict(case, id=id_)) for case, id_ in zip(CASES, ids)))
668
+ descriptions.write_text(json.dumps(TOPICS))
669
+ if valid:
670
+ assert [c['id'] for c in evaluation.load_inputs(data, descriptions)[0]] == ['0', '1']
671
+ else:
672
+ with pytest.raises(ValueError, match='duplicate id'):
673
+ evaluation.load_inputs(data, descriptions)
674
+
675
+
676
+ def test_csv_rejects_unclosed_quote_but_preserves_valid_multiline(tmp_path):
677
+ descriptions, cases = tmp_path / 'descriptions.json', tmp_path / 'evals.csv'
678
+ descriptions.write_text(json.dumps(TOPICS))
679
+ cases.write_text('"utterance,expected_action\n')
680
+ with pytest.raises(ValueError, match='Malformed CSV'):
681
+ evaluation.load_inputs(cases, descriptions)
682
+ cases.write_text('id,expected_action,utterance\n1,go_to_orders,"first\n2,go_to_billing,last\n')
683
+ with pytest.raises(ValueError, match='Malformed CSV'):
684
+ evaluation.load_inputs(cases, descriptions)
685
+ cases.write_text('id,expected_action,utterance\n1,go_to_orders,"first\nsecond"\n2,go_to_billing,last\n')
686
+ rows, _ = evaluation.load_inputs(cases, descriptions)
687
+ assert len(rows) == 2 and rows[0]['utterance'] == 'first\nsecond'
688
+
689
+
690
+ @pytest.mark.parametrize('separator', ['\x85', '\u2028', '\u2029'])
691
+ def test_report_accepts_valid_unicode_in_saved_jsonl(tmp_path, separator):
692
+ text = 'Track' + separator + 'package'
693
+ evaluation.evaluate(FakeClient(['go_to_orders']), [dict(CASES[0], utterance=text)], TOPICS, tmp_path / 'run')
694
+ assert text in report_cli.report(tmp_path / 'run')
695
+
696
+
697
+ def test_service_error_confusion_bucket_does_not_collide_with_action():
698
+ rows = [dict(CASES[0], iteration=1, actual_action='ERROR', status='fail'),
699
+ dict(CASES[0], iteration=2, actual_action=None, status='error')]
700
+ evaluation.validate_topics([{'ERROR': 'An action.'}, {'go_to_orders': 'Order help.'}])
701
+ summary = evaluation.summarize(rows)
702
+ assert summary['confusion_matrix']['go_to_orders'] == {'ERROR': 1, '<service_error>': 1}
703
+ assert summary['fail'] == summary['error'] == 1
704
+
705
+
706
+ @pytest.mark.parametrize('failure', ['go_to_billing', client.ServiceError('HTTP 503'), KeyboardInterrupt()])
707
+ def test_experiment_report_includes_holdout_failures_errors_and_interruption(tmp_path, failure):
708
+ fake = FakeClient(['go_to_orders', 'go_to_billing', failure])
709
+ folder = tmp_path / 'loop'
710
+ try:
711
+ optimizer.optimize(fake, args_for(folder), CASES, TOPICS, [dict(CASES[0], utterance='UNSEEN HOLDOUT')])
712
+ except (client.ServiceError, KeyboardInterrupt):
713
+ pass
714
+ for only_failures in [False, True]:
715
+ text = report_cli.report(folder, only_failures)
716
+ assert 'Independent holdout results' in text and 'Expected action' in text and 'Repeat stability' in text
717
+ if isinstance(failure, KeyboardInterrupt):
718
+ assert 'interrupted' in text and '0/1 predictions completed' in text
719
+ else:
720
+ assert 'UNSEEN HOLDOUT' in text
721
+ if isinstance(failure, client.ServiceError):
722
+ assert 'HTTP 503' in text and 'service errors: 1' in text
723
+
724
+
725
+ @pytest.mark.parametrize('target', ['best_candidate.json', 'best_descriptions.json', 'best_summary.json'])
726
+ @pytest.mark.parametrize('after', [False, True])
727
+ def test_interrupted_winner_promotion_reconciles_exports(tmp_path, monkeypatch, target, after):
728
+ original, interrupted = optimizer.write_json, []
729
+ def write(path, value):
730
+ winning = (isinstance(value, dict) and (value.get('round') == 1 or value.get('pass') == 2)) or (
731
+ isinstance(value, list) and value != TOPICS)
732
+ if path.name == target and winning and not interrupted:
733
+ interrupted.append(True)
734
+ if after:
735
+ original(path, value)
736
+ raise KeyboardInterrupt()
737
+ return original(path, value)
738
+ monkeypatch.setattr(optimizer, 'write_json', write)
739
+ folder = tmp_path / 'loop'
740
+ with pytest.raises(KeyboardInterrupt):
741
+ optimizer.optimize(FakeClient(['go_to_orders', 'go_to_orders', 'go_to_orders', 'go_to_billing'], [proposal()]),
742
+ args_for(folder), CASES, TOPICS)
743
+ winner = json.loads((folder / 'best_candidate.json').read_text())
744
+ state = json.loads((folder / 'experiment.json').read_text())
745
+ assert interrupted and state['state'] == 'interrupted'
746
+ assert state['best_round'] == winner['round'] and state['best_summary'] == winner['summary']
747
+ assert json.loads((folder / 'best_descriptions.json').read_text()) == winner['descriptions']
748
+ assert json.loads((folder / 'best_summary.json').read_text()) == winner['summary']
749
+ assert 'Stop state: interrupted' in report_cli.report(folder)
750
+
751
+
752
+ def test_report_uses_committed_winner_after_stale_state(tmp_path):
753
+ folder = tmp_path / 'loop'
754
+ optimizer.optimize(FakeClient(['go_to_orders', 'go_to_orders', 'go_to_orders', 'go_to_billing'], [proposal()]),
755
+ args_for(folder), CASES, TOPICS)
756
+ state = json.loads((folder / 'experiment.json').read_text())
757
+ state.update(best_round=0, best_summary=state['baseline'])
758
+ evaluation.write_json(folder / 'experiment.json', state)
759
+ assert '| Correct / completed | 1/2 | 2/2 |' in report_cli.report(folder)
760
+
761
+
762
+ def test_proposer_failure_precedes_baseline_and_is_reportable(tmp_path, monkeypatch):
763
+ fake = FakeClient([])
764
+ def unavailable(model):
765
+ fake.calls += 1
766
+ raise client.ServiceError('Inference HTTP 404')
767
+ monkeypatch.setattr(fake, 'check_proposer', unavailable)
768
+ folder = tmp_path / 'loop'
769
+ with pytest.raises(client.ServiceError):
770
+ optimizer.optimize(fake, args_for(folder), CASES, TOPICS)
771
+ assert fake.calls == 1 and not (folder / 'baseline').exists()
772
+ text = report_cli.report(folder)
773
+ assert 'HTTP 404' in text and 'Tuning evaluation has not started' in text
774
+
775
+
776
+ def test_proposer_preflight_budget_is_explicit(tmp_path):
777
+ descriptions, cases = tmp_path / 'descriptions.json', tmp_path / 'evals.jsonl'
778
+ descriptions.write_text(json.dumps(TOPICS))
779
+ cases.write_text('\n'.join(json.dumps(c) for c in CASES))
780
+ argv = ['--evals', str(cases), '--descriptions', str(descriptions)]
781
+ args = cli.build_parser().parse_args(['preflight', *argv, '--check-proposer', '--max-calls', '1'])
782
+ with pytest.raises(ValueError, match='needs 2 inference calls'):
783
+ cli.prepare(args)
784
+ args = cli.build_parser().parse_args(['optimize', *argv, '--output-dir', str(tmp_path / 'run'),
785
+ '--max-rounds', '2', '--max-calls', '8'])
786
+ with pytest.raises(ValueError, match='needs 9 inference calls'):
787
+ cli.prepare(args)
788
+
789
+
790
+ @pytest.mark.parametrize('second', ['private-session', '[REDACTED] use secret command'])
791
+ def test_cli_redacted_token_uses_dedicated_command(monkeypatch, second):
792
+ replies = iter([{'accessToken': '[REDACTED] use org auth show-access-token'}, {'accessToken': second}])
793
+ calls = []
794
+ monkeypatch.setattr(onboarding, 'sf', lambda args: calls.append(args) or next(replies))
795
+ if second.startswith('[REDACTED]'):
796
+ with pytest.raises(ValueError, match='No CLI session'):
797
+ onboarding.read_org_session('customer')
798
+ else:
799
+ assert onboarding.read_org_session('customer') == second
800
+ assert calls[-1][:3] == ['org', 'auth', 'show-access-token']
801
+
802
+
803
+ def test_runtime_workspace_uses_setup_normalization(tmp_path, monkeypatch):
804
+ workspace = onboarding.initialize_workspace(ORG, tmp_path / 'profile')
805
+ creds = workspace / 'credentials.env'
806
+ creds.write_text('\n'.join(k + '=' + v for k, v in CREDS.items()))
807
+ creds.chmod(0o600)
808
+ original = Path.expanduser
809
+ monkeypatch.setattr(Path, 'expanduser', lambda path: workspace if str(path) == '~/profile' else original(path))
810
+ args = SimpleNamespace(target_org=None, env_file=None, workspace=Path('~/profile'))
811
+ assert onboarding.credentials_for_run(args) == CREDS
812
+
813
+
814
+ def test_prepare_failure_is_atomic_and_can_be_retried(tmp_path, monkeypatch):
815
+ monkeypatch.setattr(eca, 'discover_eca', lambda *args: [])
816
+ monkeypatch.setattr(eca, 'sf', lambda *args: {'records': [{'Username': ORG['username']}]})
817
+ real = eca.write_json
818
+ def failed_write(*args):
819
+ raise OSError('synthetic write failure')
820
+ monkeypatch.setattr(eca, 'write_json', failed_write)
821
+ with pytest.raises(OSError):
822
+ eca.prepare_eca(ORG, tmp_path, 'admin@example.com', ORG['username'])
823
+ assert not (tmp_path / 'eca').exists() and not list(tmp_path.glob('.eca-prepare-*'))
824
+ monkeypatch.setattr(eca, 'write_json', real)
825
+ assert eca.prepare_eca(ORG, tmp_path, 'admin@example.com', ORG['username'])['state'] == 'prepared'
826
+ with pytest.raises(ValueError, match='Review and reuse'):
827
+ eca.prepare_eca(ORG, tmp_path, 'admin@example.com', ORG['username'])
828
+
829
+
830
+ def test_abandoned_preparation_has_actionable_recovery(tmp_path):
831
+ (tmp_path / 'eca').mkdir()
832
+ (tmp_path / 'eca/keep.txt').write_text('preserve prior work')
833
+ with pytest.raises(ValueError, match='Back up and move'):
834
+ eca.prepare_eca(ORG, tmp_path, 'admin@example.com', ORG['username'])
835
+ assert (tmp_path / 'eca/keep.txt').read_text() == 'preserve prior work'
836
+
837
+
838
+ def test_old_api_is_rejected_before_preparation_or_deployment(tmp_path, monkeypatch):
839
+ monkeypatch.setattr(eca, 'discover_eca', lambda *args: pytest.fail('no org calls'))
840
+ with pytest.raises(ValueError, match='API 65.0'):
841
+ eca.prepare_eca(dict(ORG, api_version='64.0'), tmp_path, 'admin@example.com', ORG['username'])
842
+ assert not (tmp_path / 'eca').exists()
843
+ (tmp_path / 'eca').mkdir()
844
+ evaluation.write_json(tmp_path / 'eca/plan.json', dict(ORG, state='prepared', api_version='64.0'))
845
+ with pytest.raises(ValueError, match='API 65.0'):
846
+ eca.deploy_eca(ORG, tmp_path)
847
+
848
+
849
+ @pytest.mark.parametrize('status,returncode', [('Failed', 1), ('InProgress', 0)])
850
+ def test_failed_deployment_retains_job_id_without_raw_cli_output(tmp_path, monkeypatch, status, returncode):
851
+ monkeypatch.setattr(eca, 'discover_eca', lambda *args: [])
852
+ monkeypatch.setattr(eca, 'sf', lambda *args: {'records': [{'Username': ORG['username']}]})
853
+ eca.prepare_eca(ORG, tmp_path, 'admin@example.com', ORG['username'])
854
+ monkeypatch.setattr(onboarding.shutil, 'which', lambda _: '/fake/sf')
855
+ job = '0Af000000000001AAA'
856
+ envelope_ = {'status': returncode, 'name': 'DeployFailed', 'message': 'private-secret',
857
+ 'result': {'id': job, 'status': status, 'accessToken': 'private-secret'}}
858
+ monkeypatch.setattr(onboarding.subprocess, 'run', lambda *a, **k: SimpleNamespace(
859
+ returncode=returncode, stdout=json.dumps(envelope_), stderr='private-secret'))
860
+ monkeypatch.setattr(eca, 'sf', onboarding.sf)
861
+ with pytest.raises(ValueError, match=job) as error:
862
+ eca.deploy_eca(ORG, tmp_path)
863
+ plan = json.loads((tmp_path / 'eca/plan.json').read_text())
864
+ assert plan['steps'][0]['base'] == {'deployment_id': job, 'status': status}
865
+ assert plan['state'] == 'incomplete_check_org_before_retry'
866
+ assert 'private-secret' not in json.dumps(plan) + str(error.value)
867
+
868
+
869
+ @pytest.mark.parametrize('mode', ['missing', 'corrupt', 'wrong-shape'])
870
+ def test_report_cli_expected_errors_have_no_traceback(tmp_path, capsys, mode):
871
+ if mode != 'missing':
872
+ (tmp_path / 'run.json').write_text('{' if mode == 'corrupt' else '[]')
873
+ assert report_cli.main(['--run', str(tmp_path)]) == 2
874
+ captured = capsys.readouterr()
875
+ assert 'Report error' in captured.err and 'Traceback' not in captured.err
876
+
877
+
878
+ @pytest.mark.parametrize('key', ['groups', 'expected_actions'])
879
+ def test_report_rejects_malformed_nested_buckets(tmp_path, capsys, key):
880
+ folder = tmp_path / 'run'
881
+ evaluation.evaluate(FakeClient(['go_to_orders']), CASES[:1], TOPICS, folder)
882
+ summary = json.loads((folder / 'summary.json').read_text())
883
+ summary[key] = []
884
+ evaluation.write_json(folder / 'summary.json', summary)
885
+ assert report_cli.main(['--run', str(folder)]) == 2
886
+ error = capsys.readouterr().err
887
+ assert key in error and 'summary.json' in error and 'Traceback' not in error