bpmax-cli 0.1.43 → 0.1.44-beta.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 (251) hide show
  1. package/README.md +3 -3
  2. package/dist/bin.js +3372 -453
  3. package/dist/bin.js.map +1 -1
  4. package/package.json +1 -1
  5. package/skills/bpmax-api-platform-editor/SKILL.md +321 -0
  6. package/skills/bpmax-api-platform-editor/agents/openai.yaml +4 -0
  7. package/skills/bpmax-api-platform-editor/references/api-doc-debug-workflow.md +34 -0
  8. package/skills/bpmax-api-platform-editor/references/api-proxy-shape.md +41 -0
  9. package/skills/bpmax-api-platform-editor/references/instance-config-shape.md +41 -0
  10. package/skills/bpmax-api-platform-editor/references/platform-api-map.md +52 -0
  11. package/skills/bpmax-api-platform-editor/references/runtime-workflow.md +32 -0
  12. package/skills/bpmax-api-platform-editor/scripts/api_platform_editor_common.py +1276 -0
  13. package/skills/bpmax-api-platform-editor/scripts/build_submit_payload.py +64 -0
  14. package/skills/bpmax-api-platform-editor/scripts/capture_write_contract.py +40 -0
  15. package/skills/bpmax-api-platform-editor/scripts/export_layer_bundle.py +212 -0
  16. package/skills/bpmax-api-platform-editor/scripts/record_doc_debug_acceptance.py +62 -0
  17. package/skills/bpmax-api-platform-editor/scripts/submit_and_verify_layer.py +75 -0
  18. package/skills/bpmax-api-platform-editor/tests/test_api_platform_editor.py +287 -0
  19. package/skills/bpmax-auth/SKILL.md +6 -17
  20. package/skills/bpmax-builder-shared/SKILL.md +44 -0
  21. package/skills/bpmax-builder-shared/base_url.py +81 -0
  22. package/skills/bpmax-builder-shared/runtime-script-site-matrix.json +71 -0
  23. package/skills/bpmax-builder-shared/runtime-script-site-matrix.md +34 -0
  24. package/skills/bpmax-builder-shared/runtime-script-template-catalog.md +123 -0
  25. package/skills/bpmax-builder-shared/runtime_script_rules.py +272 -0
  26. package/skills/bpmax-builder-shared/skill_audit.py +374 -0
  27. package/skills/bpmax-builder-shared/template_script_hard_rules.py +280 -0
  28. package/skills/bpmax-builder-shared/tests/test_base_url.py +80 -0
  29. package/skills/bpmax-builder-shared/tests/test_runtime_script_rules.py +115 -0
  30. package/skills/bpmax-builder-shared/tests/test_skill_audit.py +231 -0
  31. package/skills/bpmax-builder-shared/tests/test_template_script_hard_rules.py +281 -0
  32. package/skills/bpmax-cli/SKILL.md +2 -0
  33. package/skills/bpmax-config-latest/SKILL.md +71 -0
  34. package/skills/bpmax-console-template-editor/SKILL.md +536 -0
  35. package/skills/bpmax-console-template-editor/agents/openai.yaml +4 -0
  36. package/skills/bpmax-console-template-editor/references/filter-integration.md +60 -0
  37. package/skills/bpmax-console-template-editor/references/lessons-from-resume-dashboard.md +114 -0
  38. package/skills/bpmax-console-template-editor/references/local-temp-workflow.md +69 -0
  39. package/skills/bpmax-console-template-editor/references/module-catalog.md +100 -0
  40. package/skills/bpmax-console-template-editor/references/runtime-page-shape.md +91 -0
  41. package/skills/bpmax-console-template-editor/references/template-shape.md +149 -0
  42. package/skills/bpmax-console-template-editor/scripts/build_submit_payload.py +38 -0
  43. package/skills/bpmax-console-template-editor/scripts/confirm_console_template.py +33 -0
  44. package/skills/bpmax-console-template-editor/scripts/console_template_editor_common.py +964 -0
  45. package/skills/bpmax-console-template-editor/scripts/export_console_template.py +99 -0
  46. package/skills/bpmax-console-template-editor/scripts/lint_console_template.py +46 -0
  47. package/skills/bpmax-console-template-editor/scripts/submit_console_template.py +99 -0
  48. package/skills/bpmax-console-template-editor/tests/test_console_template_editor.py +383 -0
  49. package/skills/bpmax-dataset-field-template-editor/SKILL.md +600 -0
  50. package/skills/bpmax-dataset-field-template-editor/references/create-request-gotchas.md +25 -0
  51. package/skills/bpmax-dataset-field-template-editor/references/field-classify-mapping.md +35 -0
  52. package/skills/bpmax-dataset-field-template-editor/references/nested-field-patterns.md +24 -0
  53. package/skills/bpmax-dataset-field-template-editor/references/runtime-verified-field-page-shape.md +61 -0
  54. package/skills/bpmax-dataset-field-template-editor/references/virtual-field-patterns.md +27 -0
  55. package/skills/bpmax-dataset-field-template-editor/references/work-file-to-submit-mapping.md +127 -0
  56. package/skills/bpmax-dataset-field-template-editor/scripts/build_submit_payload.py +67 -0
  57. package/skills/bpmax-dataset-field-template-editor/scripts/confirm_dataset_field.py +37 -0
  58. package/skills/bpmax-dataset-field-template-editor/scripts/dataset_field_editor_common.py +784 -0
  59. package/skills/bpmax-dataset-field-template-editor/scripts/export_dataset_field.py +62 -0
  60. package/skills/bpmax-dataset-field-template-editor/scripts/init_create_dataset_field.py +104 -0
  61. package/skills/bpmax-dataset-field-template-editor/scripts/inspect_dataset_field_runtime.py +83 -0
  62. package/skills/bpmax-dataset-field-template-editor/scripts/lint_dataset_field_semantics.py +35 -0
  63. package/skills/bpmax-dataset-field-template-editor/scripts/submit_dataset_field.py +95 -0
  64. package/skills/bpmax-dataset-field-template-editor/tests/test_dataset_field_editor.py +709 -0
  65. package/skills/bpmax-dataset-field-template-editor/tests/test_init_create_dataset_field.py +59 -0
  66. package/skills/bpmax-dataset-template-editor/SKILL.md +779 -0
  67. package/skills/bpmax-dataset-template-editor/references/custom-key-usage-patterns.md +18 -0
  68. package/skills/bpmax-dataset-template-editor/references/dataset-script-runtime-matrix.md +73 -0
  69. package/skills/bpmax-dataset-template-editor/references/pre-process-script-authoring-guide.md +186 -0
  70. package/skills/bpmax-dataset-template-editor/references/pre-process-script-example-catalog.md +106 -0
  71. package/skills/bpmax-dataset-template-editor/references/runtime-gotchas.md +28 -0
  72. package/skills/bpmax-dataset-template-editor/references/runtime-verified-dataset-page-shape.md +47 -0
  73. package/skills/bpmax-dataset-template-editor/references/ui-to-backend-field-map.md +23 -0
  74. package/skills/bpmax-dataset-template-editor/references/work-file-to-submit-mapping.md +97 -0
  75. package/skills/bpmax-dataset-template-editor/scripts/basic_table_audit.py +65 -0
  76. package/skills/bpmax-dataset-template-editor/scripts/build_submit_payload.py +38 -0
  77. package/skills/bpmax-dataset-template-editor/scripts/dataset_editor_common.py +650 -0
  78. package/skills/bpmax-dataset-template-editor/scripts/export_dataset.py +155 -0
  79. package/skills/bpmax-dataset-template-editor/scripts/lint_dataset_template.py +42 -0
  80. package/skills/bpmax-dataset-template-editor/scripts/resolve_dataset.py +43 -0
  81. package/skills/bpmax-dataset-template-editor/scripts/scan_custom_key_references.py +27 -0
  82. package/skills/bpmax-dataset-template-editor/scripts/submit_dataset.py +115 -0
  83. package/skills/bpmax-dataset-template-editor/scripts/verify_dataset_list.py +52 -0
  84. package/skills/bpmax-dataset-template-editor/scripts/verify_publish_health.py +39 -0
  85. package/skills/bpmax-dataset-template-editor/tests/test_dataset_editor.py +373 -0
  86. package/skills/bpmax-e2e-flow-config-orchestrator/SKILL.md +151 -0
  87. package/skills/bpmax-e2e-flow-config-orchestrator/agents/openai.yaml +4 -0
  88. package/skills/bpmax-e2e-flow-config-orchestrator/references/orchestration-matrix.md +60 -0
  89. package/skills/bpmax-e2e-flow-test-operator/SKILL.md +371 -0
  90. package/skills/bpmax-e2e-flow-test-operator/agents/openai.yaml +5 -0
  91. package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale.json +97 -0
  92. package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_final_v2.json +105 -0
  93. package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_main.json +36 -0
  94. package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_region.json +40 -0
  95. package/skills/bpmax-e2e-flow-test-operator/references/browser-only-checkpoints.md +33 -0
  96. package/skills/bpmax-e2e-flow-test-operator/references/failure-update-loop.md +17 -0
  97. package/skills/bpmax-e2e-flow-test-operator/references/filter-field-discovery.md +40 -0
  98. package/skills/bpmax-e2e-flow-test-operator/references/minimal-test-loop.md +19 -0
  99. package/skills/bpmax-e2e-flow-test-operator/references/negative-sale-api-matrix.md +75 -0
  100. package/skills/bpmax-e2e-flow-test-operator/references/profile-schema.md +107 -0
  101. package/skills/bpmax-e2e-flow-test-operator/references/skill-experience-coverage-matrix.md +29 -0
  102. package/skills/bpmax-e2e-flow-test-operator/references/stale-runtime-and-clean-sample-rules.md +54 -0
  103. package/skills/bpmax-e2e-flow-test-operator/references/state-schema.md +58 -0
  104. package/skills/bpmax-e2e-flow-test-operator/scripts/bpmax_session.py +287 -0
  105. package/skills/bpmax-e2e-flow-test-operator/scripts/dealer_sample_on_shelf_plan.json +59 -0
  106. package/skills/bpmax-e2e-flow-test-operator/scripts/dealer_sample_on_shelf_runner.py +687 -0
  107. package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_doc.py +95 -0
  108. package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_state.py +288 -0
  109. package/skills/bpmax-e2e-flow-test-operator/scripts/flow_api_matrix.py +161 -0
  110. package/skills/bpmax-e2e-flow-test-operator/scripts/flow_filter_fields.py +138 -0
  111. package/skills/bpmax-e2e-flow-test-operator/scripts/flow_form_runtime.py +396 -0
  112. package/skills/bpmax-e2e-flow-test-operator/scripts/flow_runner.py +341 -0
  113. package/skills/bpmax-e2e-flow-test-operator/scripts/flow_test_profile.py +185 -0
  114. package/skills/bpmax-e2e-flow-test-operator/tests/test_negative_sale_api_tools.py +138 -0
  115. package/skills/bpmax-feishu-chat-flow-plugin-editor/SKILL.md +69 -0
  116. package/skills/bpmax-feishu-chat-flow-plugin-editor/agents/openai.yaml +4 -0
  117. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-checklist.md +42 -0
  118. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-recipes.md +38 -0
  119. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-shape.md +86 -0
  120. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/gate-lint.md +68 -0
  121. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/hoocoo-patterns.md +39 -0
  122. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/runtime-behavior.md +41 -0
  123. package/skills/bpmax-feishu-chat-flow-plugin-editor/references/script-authoring.md +110 -0
  124. package/skills/bpmax-feishu-chat-flow-plugin-editor/scripts/lint_feishu_chat_plugin.py +278 -0
  125. package/skills/bpmax-feishu-chat-flow-plugin-editor/tests/test_lint_feishu_chat_plugin.py +203 -0
  126. package/skills/bpmax-filter-template-editor/SKILL.md +564 -0
  127. package/skills/bpmax-filter-template-editor/references/experience-coverage-matrix.md +38 -0
  128. package/skills/bpmax-filter-template-editor/references/filter-and-flow-binding.md +57 -0
  129. package/skills/bpmax-filter-template-editor/references/filter-content-schema.md +141 -0
  130. package/skills/bpmax-filter-template-editor/references/filter-request-shape.md +287 -0
  131. package/skills/bpmax-filter-template-editor/references/filter-runtime-patterns.md +115 -0
  132. package/skills/bpmax-filter-template-editor/references/runtime-verified-filter-page-shape.md +94 -0
  133. package/skills/bpmax-filter-template-editor/scripts/build_submit_payload.py +25 -0
  134. package/skills/bpmax-filter-template-editor/scripts/confirm_filter_template.py +22 -0
  135. package/skills/bpmax-filter-template-editor/scripts/export_filter_template.py +57 -0
  136. package/skills/bpmax-filter-template-editor/scripts/filter_template_editor_common.py +348 -0
  137. package/skills/bpmax-filter-template-editor/scripts/init_create_filter_template.py +8 -0
  138. package/skills/bpmax-filter-template-editor/scripts/lint_filter_template_semantics.py +26 -0
  139. package/skills/bpmax-filter-template-editor/scripts/submit_filter_template.py +62 -0
  140. package/skills/bpmax-filter-template-editor/tests/test_filter_template_editor.py +231 -0
  141. package/skills/bpmax-flow-template-editor/SKILL.md +1043 -0
  142. package/skills/bpmax-flow-template-editor/agents/openai.yaml +4 -0
  143. package/skills/bpmax-flow-template-editor/references/before-next-step-script-runtime-gotchas.md +62 -0
  144. package/skills/bpmax-flow-template-editor/references/config-surfaces-and-placeholders.md +270 -0
  145. package/skills/bpmax-flow-template-editor/references/diff-strategy.md +67 -0
  146. package/skills/bpmax-flow-template-editor/references/editor-runtime-vs-draft.md +25 -0
  147. package/skills/bpmax-flow-template-editor/references/flow-template-api-workflow.md +159 -0
  148. package/skills/bpmax-flow-template-editor/references/intent-model.md +117 -0
  149. package/skills/bpmax-flow-template-editor/references/lessons-from-price-plan-flow.md +147 -0
  150. package/skills/bpmax-flow-template-editor/references/local-temp-workflow.md +97 -0
  151. package/skills/bpmax-flow-template-editor/references/matrix-flow-form-nav-collaboration.md +163 -0
  152. package/skills/bpmax-flow-template-editor/references/payload-checklist.md +133 -0
  153. package/skills/bpmax-flow-template-editor/references/project-create-runtime-gotchas.md +54 -0
  154. package/skills/bpmax-flow-template-editor/references/requirement-to-node-mapping.md +149 -0
  155. package/skills/bpmax-flow-template-editor/references/runtime-verified-flow-detail-shape.md +41 -0
  156. package/skills/bpmax-flow-template-editor/references/runtime-verified-meta-fields.md +155 -0
  157. package/skills/bpmax-flow-template-editor/references/runtime-verified-node-fields.md +179 -0
  158. package/skills/bpmax-flow-template-editor/references/save-draft-request-shape.md +91 -0
  159. package/skills/bpmax-flow-template-editor/references/script-review-hard-rules.md +93 -0
  160. package/skills/bpmax-flow-template-editor/references/work-file-to-submit-mapping.md +57 -0
  161. package/skills/bpmax-flow-template-editor/scripts/build_submit_payload.py +69 -0
  162. package/skills/bpmax-flow-template-editor/scripts/confirm_flow_template.py +52 -0
  163. package/skills/bpmax-flow-template-editor/scripts/export_flow_template.py +114 -0
  164. package/skills/bpmax-flow-template-editor/scripts/flow_template_editor_common.py +1084 -0
  165. package/skills/bpmax-flow-template-editor/scripts/submit_flow_template.py +159 -0
  166. package/skills/bpmax-flow-template-editor/tests/test_flow_template_editor.py +636 -0
  167. package/skills/bpmax-form-template-editor/SKILL.md +1074 -0
  168. package/skills/bpmax-form-template-editor/agents/openai.yaml +4 -0
  169. package/skills/bpmax-form-template-editor/references/form-template-api-workflow.md +193 -0
  170. package/skills/bpmax-form-template-editor/references/local-temp-workflow.md +125 -0
  171. package/skills/bpmax-form-template-editor/references/payload-checklist.md +77 -0
  172. package/skills/bpmax-form-template-editor/references/sub-form-patterns.md +49 -0
  173. package/skills/bpmax-form-template-editor/scripts/build_submit_payload.py +37 -0
  174. package/skills/bpmax-form-template-editor/scripts/check_form_template_consistency.py +145 -0
  175. package/skills/bpmax-form-template-editor/scripts/confirm_form_template.py +67 -0
  176. package/skills/bpmax-form-template-editor/scripts/export_form_template.py +89 -0
  177. package/skills/bpmax-form-template-editor/scripts/form_template_editor_common.py +1745 -0
  178. package/skills/bpmax-form-template-editor/scripts/lint_form_template_semantics.py +30 -0
  179. package/skills/bpmax-form-template-editor/scripts/record_runtime_acceptance.py +67 -0
  180. package/skills/bpmax-form-template-editor/scripts/submit_form_template.py +163 -0
  181. package/skills/bpmax-form-template-editor/tests/test_form_template_editor.py +1303 -0
  182. package/skills/bpmax-list-template-editor/SKILL.md +468 -0
  183. package/skills/bpmax-list-template-editor/agents/openai.yaml +4 -0
  184. package/skills/bpmax-list-template-editor/references/browser-page-contract.md +81 -0
  185. package/skills/bpmax-list-template-editor/references/content-config-shape.md +148 -0
  186. package/skills/bpmax-list-template-editor/references/dataset-field-mapping.md +60 -0
  187. package/skills/bpmax-list-template-editor/references/list-template-api-workflow.md +103 -0
  188. package/skills/bpmax-list-template-editor/references/local-temp-workflow.md +102 -0
  189. package/skills/bpmax-list-template-editor/references/payload-checklist.md +47 -0
  190. package/skills/bpmax-list-template-editor/references/runtime-verified-workflow.md +140 -0
  191. package/skills/bpmax-list-template-editor/references/special-formats.md +394 -0
  192. package/skills/bpmax-list-template-editor/scripts/build_submit_payload.py +37 -0
  193. package/skills/bpmax-list-template-editor/scripts/confirm_list_template.py +33 -0
  194. package/skills/bpmax-list-template-editor/scripts/export_list_template.py +89 -0
  195. package/skills/bpmax-list-template-editor/scripts/fetch_data_set.py +34 -0
  196. package/skills/bpmax-list-template-editor/scripts/lint_list_template_semantics.py +54 -0
  197. package/skills/bpmax-list-template-editor/scripts/list_template_editor_common.py +955 -0
  198. package/skills/bpmax-list-template-editor/scripts/record_acceptance.py +55 -0
  199. package/skills/bpmax-list-template-editor/scripts/submit_list_template.py +117 -0
  200. package/skills/bpmax-list-template-editor/tests/test_list_template_editor_common.py +441 -0
  201. package/skills/bpmax-nav-config-editor/SKILL.md +347 -0
  202. package/skills/bpmax-nav-config-editor/agents/openai.yaml +4 -0
  203. package/skills/bpmax-nav-config-editor/references/api-workflow.md +68 -0
  204. package/skills/bpmax-nav-config-editor/references/config-shape.md +78 -0
  205. package/skills/bpmax-nav-config-editor/references/icon-selection.md +83 -0
  206. package/skills/bpmax-nav-config-editor/references/path-mapping-rules.md +46 -0
  207. package/skills/bpmax-nav-config-editor/references/payload-checklist.md +41 -0
  208. package/skills/bpmax-nav-config-editor/references/runtime-probing.md +47 -0
  209. package/skills/bpmax-nav-config-editor/scripts/build_submit_payload.py +34 -0
  210. package/skills/bpmax-nav-config-editor/scripts/confirm_nav_config.py +32 -0
  211. package/skills/bpmax-nav-config-editor/scripts/export_nav_config.py +56 -0
  212. package/skills/bpmax-nav-config-editor/scripts/lint_nav_config_semantics.py +33 -0
  213. package/skills/bpmax-nav-config-editor/scripts/nav_config_editor_common.py +812 -0
  214. package/skills/bpmax-nav-config-editor/scripts/submit_nav_config.py +44 -0
  215. package/skills/bpmax-nav-config-editor/scripts/verify_nav_config.py +33 -0
  216. package/skills/bpmax-nav-config-editor/tests/test_nav_config_editor.py +358 -0
  217. package/skills/bpmax-nav-config-editor/tests/test_nav_config_editor_common.py +138 -0
  218. package/skills/bpmax-nav-config-editor/tests/test_nav_config_lint.py +58 -0
  219. package/skills/bpmax-nav-config-editor/tests/test_nav_config_submit_verify.py +51 -0
  220. package/skills/bpmax-project/SKILL.md +1 -1
  221. package/skills/bpmax-project-detail-template-editor/SKILL.md +329 -0
  222. package/skills/bpmax-project-detail-template-editor/agents/openai.yaml +4 -0
  223. package/skills/bpmax-project-detail-template-editor/references/local-temp-workflow.md +59 -0
  224. package/skills/bpmax-project-detail-template-editor/references/module-catalog-and-config-notes.md +47 -0
  225. package/skills/bpmax-project-detail-template-editor/references/payload-checklist.md +33 -0
  226. package/skills/bpmax-project-detail-template-editor/references/project-detail-template-api-workflow.md +44 -0
  227. package/skills/bpmax-project-detail-template-editor/scripts/build_submit_payload.py +30 -0
  228. package/skills/bpmax-project-detail-template-editor/scripts/confirm_project_detail_template.py +33 -0
  229. package/skills/bpmax-project-detail-template-editor/scripts/export_project_detail_template.py +87 -0
  230. package/skills/bpmax-project-detail-template-editor/scripts/lint_project_detail_template_semantics.py +37 -0
  231. package/skills/bpmax-project-detail-template-editor/scripts/project_detail_template_editor_common.py +507 -0
  232. package/skills/bpmax-project-detail-template-editor/scripts/submit_project_detail_template.py +120 -0
  233. package/skills/bpmax-project-detail-template-editor/tests/test_project_detail_template_editor.py +369 -0
  234. package/skills/bpmax-role-editor/SKILL.md +251 -0
  235. package/skills/bpmax-role-editor/references/api-workflow.md +30 -0
  236. package/skills/bpmax-role-editor/references/runtime-page-shape.md +18 -0
  237. package/skills/bpmax-role-editor/references/work-file-mapping.md +32 -0
  238. package/skills/bpmax-role-editor/scripts/build_submit_payload.py +38 -0
  239. package/skills/bpmax-role-editor/scripts/confirm_role.py +33 -0
  240. package/skills/bpmax-role-editor/scripts/export_role.py +163 -0
  241. package/skills/bpmax-role-editor/scripts/lint_role_semantics.py +38 -0
  242. package/skills/bpmax-role-editor/scripts/role_editor_common.py +1231 -0
  243. package/skills/bpmax-role-editor/scripts/submit_role.py +144 -0
  244. package/skills/bpmax-role-editor/tests/test_role_editor.py +343 -0
  245. package/skills/bpmax-shared/SKILL.md +1 -1
  246. package/skills/form-control-library/SKILL.md +82 -0
  247. package/skills/form-control-library/agents/openai.yaml +4 -0
  248. package/skills/form-control-library/references/form-controls.md +199 -0
  249. package/skills/form-control-library/references/form-template-submit-schema.md +180 -0
  250. package/skills/form-control-library/references/group-select-runtime.md +191 -0
  251. package/skills/form-control-library/scripts/rebuild_form_control_library.py +55 -0
@@ -0,0 +1,784 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import sys
7
+ import ssl
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from dataclasses import dataclass
12
+ from datetime import datetime, timezone
13
+ from difflib import unified_diff
14
+ import hashlib
15
+ from pathlib import Path
16
+ from typing import Any, Dict, Optional
17
+
18
+
19
+ SHARED_SKILL_ROOT = Path(__file__).resolve().parents[2] / "bpmax-builder-shared"
20
+ if str(SHARED_SKILL_ROOT) not in sys.path:
21
+ sys.path.insert(0, str(SHARED_SKILL_ROOT))
22
+ from base_url import DEFAULT_BASE_URL, resolve_base_url
23
+
24
+ DEFAULT_LANGUAGE = "zhCN"
25
+ REPO_ROOT = Path(__file__).resolve().parents[4]
26
+ TMP_ROOT = REPO_ROOT / ".codex" / "tmp" / "dataset-field-editor"
27
+ TMP_SUBDIRS = ("raw", "work", "meta", "submit", "diffs", "result")
28
+ EMPTY_OBJECT_FIELDS = {"sourceFilter", "sourceRelationFilter"}
29
+ ADVANCED_CANONICAL_KEYS = ("sourceComputed", "matchRule", "matchLogic")
30
+ FIELD_MAPPING = {
31
+ "name": ("name",),
32
+ "key": ("key",),
33
+ "type": ("type",),
34
+ "classify": ("classify",),
35
+ "flowType": ("flowType", "flow_type"),
36
+ "flowKey": ("flowKey", "flow_key"),
37
+ "sourceTable": ("sourceTable", "source_table"),
38
+ "sourceField": ("sourceField", "source_field"),
39
+ "sourceFk": ("sourceFk", "source_fk"),
40
+ "sourceFilter": ("sourceFilter", "source_filter"),
41
+ "sourceRelationTable": ("sourceRelationTable", "source_relation_table"),
42
+ "sourceRelationField": ("sourceRelationField", "source_relation_field"),
43
+ "sourceRelationFk": ("sourceRelationFk", "source_relation_fk"),
44
+ "sourceRelationFilter": ("sourceRelationFilter", "source_relation_filter"),
45
+ "relationFlow": ("relationFlow", "relation_flow"),
46
+ "postScript": ("postScript", "post_script"),
47
+ "sourceComputed": ("sourceComputed", "source_computed"),
48
+ "matchRule": ("matchRule", "match_rule"),
49
+ "matchLogic": ("matchLogic", "match_logic"),
50
+ }
51
+ READBACK_FIELD_MAPPING = {
52
+ "name": "name",
53
+ "key": "key",
54
+ "type": "type",
55
+ "classify": "classify",
56
+ "flowType": "flow_type",
57
+ "flowKey": "flow_key",
58
+ "sourceTable": "source_table",
59
+ "sourceField": "source_field",
60
+ "sourceFk": "source_fk",
61
+ "sourceFilter": "source_filter",
62
+ "sourceRelationTable": "source_relation_table",
63
+ "sourceRelationField": "source_relation_field",
64
+ "sourceRelationFk": "source_relation_fk",
65
+ "sourceRelationFilter": "source_relation_filter",
66
+ "relationFlow": "relation_flow",
67
+ "postScript": "post_script",
68
+ "sourceComputed": "source_computed",
69
+ "matchRule": "match_rule",
70
+ "matchLogic": "match_logic",
71
+ }
72
+ ADVANCED_FIELDS = {
73
+ "sourceComputed": "source_computed",
74
+ "matchRule": "match_rule",
75
+ "matchLogic": "match_logic",
76
+ }
77
+
78
+ from template_script_hard_rules import scan_named_script_surfaces
79
+
80
+
81
+ def utc_now_iso() -> str:
82
+ return datetime.now(timezone.utc).isoformat()
83
+
84
+
85
+ def parse_json_like(value: Any) -> Any:
86
+ if not isinstance(value, str):
87
+ return value
88
+ text = value.strip()
89
+ if not text:
90
+ return value
91
+ if text[0] not in "{[":
92
+ return value
93
+ try:
94
+ return json.loads(text)
95
+ except json.JSONDecodeError:
96
+ return value
97
+
98
+
99
+ def normalize_optional_text(value: Any) -> Any:
100
+ if value is None:
101
+ return ""
102
+ return value
103
+
104
+
105
+ def ensure_tmp_dirs() -> None:
106
+ for part in TMP_SUBDIRS:
107
+ (TMP_ROOT / part).mkdir(parents=True, exist_ok=True)
108
+
109
+
110
+ def paths_for(field_id: Any) -> Dict[str, Path]:
111
+ ensure_tmp_dirs()
112
+ stem = str(field_id)
113
+ return {
114
+ "raw": TMP_ROOT / "raw" / f"{stem}.json",
115
+ "work": TMP_ROOT / "work" / f"{stem}.json",
116
+ "meta": TMP_ROOT / "meta" / f"{stem}.json",
117
+ "submit": TMP_ROOT / "submit" / f"{stem}.json",
118
+ "work_diff": TMP_ROOT / "diffs" / f"{stem}.work.diff.txt",
119
+ "submit_diff": TMP_ROOT / "diffs" / f"{stem}.submit.diff.txt",
120
+ "response": TMP_ROOT / "result" / f"{stem}.response.json",
121
+ "readback": TMP_ROOT / "result" / f"{stem}.readback.json",
122
+ "verify": TMP_ROOT / "result" / f"{stem}.verify.json",
123
+ "lint": TMP_ROOT / "result" / f"{stem}.lint.json",
124
+ }
125
+
126
+
127
+ def make_create_artifact_id(flow_type: str, key: str) -> str:
128
+ def _clean(value: str) -> str:
129
+ cleaned = "".join(ch if ch.isalnum() or ch in ("-", "_") else "_" for ch in str(value or "").strip())
130
+ return cleaned.strip("_") or "unknown"
131
+
132
+ return f"create__{_clean(flow_type)}__{_clean(key)}"
133
+
134
+
135
+ def dump_json(path: Path, payload: Any) -> None:
136
+ path.parent.mkdir(parents=True, exist_ok=True)
137
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
138
+
139
+
140
+ def load_json(path: Path) -> Any:
141
+ return json.loads(path.read_text(encoding="utf-8"))
142
+
143
+
144
+ def file_sha256(path: Path) -> str:
145
+ return hashlib.sha256(path.read_bytes()).hexdigest()
146
+
147
+
148
+ def load_meta(path: Path) -> Dict[str, Any]:
149
+ if not path.exists():
150
+ return {}
151
+ payload = load_json(path)
152
+ if not isinstance(payload, dict):
153
+ raise SystemExit(f"invalid meta file, expected object: {path}")
154
+ return payload
155
+
156
+
157
+ def save_meta(path: Path, payload: Dict[str, Any]) -> None:
158
+ dump_json(path, payload)
159
+
160
+
161
+ def stable_json_lines(payload: Any) -> list[str]:
162
+ return (json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n").splitlines(keepends=True)
163
+
164
+
165
+ def write_diff(path: Path, before: Any, after: Any, before_label: str, after_label: str) -> None:
166
+ diff = unified_diff(
167
+ stable_json_lines(before),
168
+ stable_json_lines(after),
169
+ fromfile=before_label,
170
+ tofile=after_label,
171
+ )
172
+ path.parent.mkdir(parents=True, exist_ok=True)
173
+ text = "".join(diff)
174
+ path.write_text(text or "# no diff\n", encoding="utf-8")
175
+
176
+
177
+ def compact_json(value: Any) -> str:
178
+ if isinstance(value, str):
179
+ return value
180
+ return json.dumps(value, ensure_ascii=False, sort_keys=True)
181
+
182
+
183
+ def normalize_verification_value(field_name: str, value: Any) -> Any:
184
+ if field_name == "relationFlow":
185
+ return _normalize_relation_flow(value)
186
+ if field_name in EMPTY_OBJECT_FIELDS:
187
+ return compact_json(parse_json_like(value))
188
+ return normalize_optional_text(value)
189
+
190
+
191
+ def is_nested_string_source(work: Dict[str, Any]) -> bool:
192
+ source = work.get("source") or {}
193
+ return (
194
+ work.get("type") == "nested"
195
+ and source.get("table") == "think_form_field"
196
+ and source.get("field") == "search_value"
197
+ )
198
+
199
+
200
+ def validate_work_payload(work: Dict[str, Any], *, mode: str) -> None:
201
+ if work.get("classify") == "virtual":
202
+ virtual = work.get("virtual")
203
+ if not isinstance(virtual, dict):
204
+ raise SystemExit("invalid work payload: virtual field requires a virtual object")
205
+ required_fields = {
206
+ "sql": "virtual.sql",
207
+ "outputField": "virtual.outputField",
208
+ "joinField": "virtual.joinField",
209
+ }
210
+ missing = [label for key, label in required_fields.items() if not str(virtual.get(key, "")).strip()]
211
+ if missing:
212
+ raise SystemExit(f"invalid work payload: virtual field missing {', '.join(missing)}")
213
+ sql = str(virtual.get("sql", ""))
214
+ join_field = str(virtual.get("joinField", ""))
215
+ if join_field not in sql:
216
+ raise SystemExit(
217
+ "invalid work payload: virtual.sql must reference virtual.joinField to prove the SQL returns the join column"
218
+ )
219
+ if is_nested_string_source(work) and not str(work.get("postScript", "")).strip():
220
+ raise SystemExit(
221
+ "invalid work payload: nested field sourced from think_form_field.search_value requires a postScript JSON parser"
222
+ )
223
+
224
+
225
+ def lint_dataset_field_semantics(work: Dict[str, Any], *, mode: str) -> Dict[str, Any]:
226
+ report: Dict[str, Any] = {"ok": True, "errors": [], "warnings": [], "checks": {}}
227
+ validate_work_payload(work, mode=mode)
228
+ source = work.get("source") or {}
229
+ advanced = work.get("advanced") or {}
230
+ hard_rule_report = scan_named_script_surfaces(
231
+ [
232
+ {"path": "source.filter", "script": source.get("filter")},
233
+ {"path": "source.relationFilter", "script": source.get("relationFilter")},
234
+ {"path": "source.relationFlow", "value": source.get("relationFlow")},
235
+ {"path": "postScript", "script": work.get("postScript")},
236
+ {"path": "advanced.sourceComputed", "script": advanced.get("sourceComputed")},
237
+ {"path": "advanced.matchRule", "script": advanced.get("matchRule")},
238
+ {"path": "advanced.matchLogic", "script": advanced.get("matchLogic")},
239
+ ]
240
+ )
241
+ report["checks"]["scriptHardRules"] = hard_rule_report["findings"]
242
+ report["errors"].extend(hard_rule_report["errors"])
243
+ report["ok"] = not report["errors"]
244
+ return report
245
+
246
+
247
+ def build_create_seed_detail(
248
+ *,
249
+ name: str,
250
+ key: str,
251
+ field_type: str,
252
+ classify: str,
253
+ flow_type: str,
254
+ flow_key: str,
255
+ source_table: str = "",
256
+ source_field: str = "",
257
+ source_fk: str = "",
258
+ source_filter: Any = "{}",
259
+ relation_table: str = "",
260
+ relation_field: str = "",
261
+ relation_fk: str = "",
262
+ relation_filter: Any = "{}",
263
+ relation_flow: Any = "",
264
+ post_script: Any = "",
265
+ source_computed: Any = None,
266
+ match_rule: Any = None,
267
+ match_logic: Any = None,
268
+ ) -> Dict[str, Any]:
269
+ detail: Dict[str, Any] = {
270
+ "id": None,
271
+ "name": name,
272
+ "key": key,
273
+ "type": field_type,
274
+ "classify": classify,
275
+ "flow_type": flow_type,
276
+ "source_table": source_table,
277
+ "source_field": source_field,
278
+ "source_fk": source_fk,
279
+ "source_filter": normalize_optional_text(source_filter),
280
+ "source_relation_table": relation_table,
281
+ "source_relation_field": relation_field,
282
+ "source_relation_fk": relation_fk,
283
+ "source_relation_filter": normalize_optional_text(relation_filter),
284
+ "relation_flow": relation_flow,
285
+ "post_script": normalize_optional_text(post_script),
286
+ }
287
+ if flow_key not in ("", None):
288
+ detail["flow_key"] = flow_key
289
+ if source_computed is not None:
290
+ detail["source_computed"] = normalize_optional_text(source_computed)
291
+ if match_rule is not None:
292
+ detail["match_rule"] = normalize_optional_text(match_rule)
293
+ if match_logic is not None:
294
+ detail["match_logic"] = normalize_optional_text(match_logic)
295
+ return detail
296
+
297
+
298
+ def detail_to_work_payload(detail: Dict[str, Any]) -> Dict[str, Any]:
299
+ classify = detail.get("classify", "")
300
+ work: Dict[str, Any] = {
301
+ "id": detail.get("id"),
302
+ "name": detail.get("name", ""),
303
+ "key": detail.get("key", ""),
304
+ "type": detail.get("type", ""),
305
+ "classify": classify,
306
+ "flowType": detail.get("flow_type", ""),
307
+ "flowKey": detail.get("flow_key", ""),
308
+ "source": {
309
+ "table": detail.get("source_table", ""),
310
+ "field": detail.get("source_field", ""),
311
+ "fk": detail.get("source_fk", ""),
312
+ "filter": normalize_optional_text(detail.get("source_filter", "")),
313
+ "relationTable": detail.get("source_relation_table", ""),
314
+ "relationField": detail.get("source_relation_field", ""),
315
+ "relationFk": detail.get("source_relation_fk", ""),
316
+ "relationFilter": normalize_optional_text(detail.get("source_relation_filter", "")),
317
+ "relationFlow": parse_json_like(detail.get("relation_flow", "")),
318
+ },
319
+ "postScript": normalize_optional_text(detail.get("post_script", "")),
320
+ }
321
+ if classify == "virtual":
322
+ work["virtual"] = {
323
+ "sql": detail.get("source_table", ""),
324
+ "outputField": detail.get("source_field", ""),
325
+ "joinField": detail.get("source_fk", ""),
326
+ }
327
+ work["source"]["table"] = ""
328
+ work["source"]["field"] = ""
329
+ work["source"]["fk"] = ""
330
+ advanced = {
331
+ "sourceComputed": normalize_optional_text(detail.get("source_computed", "")),
332
+ "matchRule": normalize_optional_text(detail.get("match_rule", "")),
333
+ "matchLogic": normalize_optional_text(detail.get("match_logic", "")),
334
+ }
335
+ if any(value not in ("", None) for value in advanced.values()):
336
+ work["advanced"] = advanced
337
+ return work
338
+
339
+
340
+ def _normalize_relation_flow(value: Any) -> Any:
341
+ parsed = parse_json_like(value)
342
+ if parsed in ("", None, {}, []):
343
+ return ""
344
+ if isinstance(parsed, (dict, list)):
345
+ return compact_json(parsed)
346
+ return parsed
347
+
348
+
349
+ def build_submit_payload(work: Dict[str, Any]) -> Dict[str, Any]:
350
+ source = work.get("source") or {}
351
+ payload: Dict[str, Any] = {
352
+ "name": work.get("name", ""),
353
+ "key": work.get("key", ""),
354
+ "type": work.get("type", ""),
355
+ "classify": work.get("classify", ""),
356
+ "flowType": work.get("flowType", ""),
357
+ "sourceFilter": normalize_optional_text(source.get("filter", "")),
358
+ "sourceRelationTable": source.get("relationTable", ""),
359
+ "sourceRelationField": source.get("relationField", ""),
360
+ "sourceRelationFk": source.get("relationFk", ""),
361
+ "sourceRelationFilter": normalize_optional_text(source.get("relationFilter", "")),
362
+ "relationFlow": _normalize_relation_flow(source.get("relationFlow", {})),
363
+ "postScript": normalize_optional_text(work.get("postScript", "")),
364
+ }
365
+ if work.get("classify") == "virtual":
366
+ virtual = work.get("virtual") or {}
367
+ payload["sourceTable"] = virtual.get("sql", "")
368
+ payload["sourceField"] = virtual.get("outputField", "")
369
+ payload["sourceFk"] = virtual.get("joinField", "")
370
+ else:
371
+ payload["sourceTable"] = source.get("table", "")
372
+ payload["sourceField"] = source.get("field", "")
373
+ payload["sourceFk"] = source.get("fk", "")
374
+ advanced = work.get("advanced")
375
+ if isinstance(advanced, dict):
376
+ if "sourceComputed" in advanced:
377
+ payload["sourceComputed"] = normalize_optional_text(advanced.get("sourceComputed"))
378
+ if "matchRule" in advanced:
379
+ payload["matchRule"] = normalize_optional_text(advanced.get("matchRule"))
380
+ if "matchLogic" in advanced:
381
+ payload["matchLogic"] = normalize_optional_text(advanced.get("matchLogic"))
382
+
383
+ flow_key = work.get("flowKey", "")
384
+ if flow_key not in ("", None):
385
+ payload["flowKey"] = flow_key
386
+ return payload
387
+
388
+
389
+ def build_create_submit_payload(work: Dict[str, Any]) -> Dict[str, Any]:
390
+ source = work.get("source") or {}
391
+ payload: Dict[str, Any] = {
392
+ "name": work.get("name", ""),
393
+ "key": work.get("key", ""),
394
+ "type": work.get("type", ""),
395
+ "classify": work.get("classify", ""),
396
+ "flow_type": work.get("flowType", ""),
397
+ }
398
+ if work.get("classify") == "virtual":
399
+ virtual = work.get("virtual") or {}
400
+ payload["source_table"] = virtual.get("sql", "")
401
+ payload["source_field"] = virtual.get("outputField", "")
402
+ payload["source_fk"] = virtual.get("joinField", "")
403
+ else:
404
+ payload["source_table"] = source.get("table", "")
405
+ payload["source_field"] = source.get("field", "")
406
+ payload["source_fk"] = source.get("fk", "")
407
+
408
+ optional_pairs = {
409
+ "source_filter": normalize_optional_text(source.get("filter", "")),
410
+ "source_relation_table": source.get("relationTable", ""),
411
+ "source_relation_field": source.get("relationField", ""),
412
+ "source_relation_fk": source.get("relationFk", ""),
413
+ "source_relation_filter": normalize_optional_text(source.get("relationFilter", "")),
414
+ "relation_flow": _normalize_relation_flow(source.get("relationFlow", {})),
415
+ }
416
+ payload["post_script"] = normalize_optional_text(work.get("postScript", ""))
417
+ for key, value in optional_pairs.items():
418
+ if value not in ("", None):
419
+ payload[key] = value
420
+
421
+ advanced = work.get("advanced")
422
+ if isinstance(advanced, dict):
423
+ if "sourceComputed" in advanced:
424
+ value = normalize_optional_text(advanced.get("sourceComputed"))
425
+ if value not in ("", None):
426
+ payload["source_computed"] = value
427
+ if "matchRule" in advanced:
428
+ value = normalize_optional_text(advanced.get("matchRule"))
429
+ if value not in ("", None):
430
+ payload["match_rule"] = value
431
+ if "matchLogic" in advanced:
432
+ value = normalize_optional_text(advanced.get("matchLogic"))
433
+ if value not in ("", None):
434
+ payload["match_logic"] = value
435
+ flow_key = work.get("flowKey", "")
436
+ if flow_key not in ("", None):
437
+ payload["flow_key"] = flow_key
438
+ return payload
439
+
440
+
441
+ def canonicalize_submit_payload(submit_payload: Dict[str, Any]) -> Dict[str, Any]:
442
+ canonical: Dict[str, Any] = {}
443
+ for canonical_key, aliases in FIELD_MAPPING.items():
444
+ for alias in aliases:
445
+ if alias in submit_payload:
446
+ canonical[canonical_key] = submit_payload[alias]
447
+ break
448
+ return canonical
449
+
450
+
451
+ def summarize_verification(submit_payload: Dict[str, Any], readback_detail: Dict[str, Any]) -> Dict[str, Any]:
452
+ canonical_submit = canonicalize_submit_payload(submit_payload)
453
+ checks: Dict[str, Dict[str, Any]] = {}
454
+ advanced_checks: Dict[str, Dict[str, Any]] = {}
455
+ submitted_fields = sorted(canonical_submit.keys())
456
+ readback_only_fields: Dict[str, Any] = {}
457
+ ok = True
458
+ for submit_key, readback_key in READBACK_FIELD_MAPPING.items():
459
+ if submit_key not in canonical_submit:
460
+ actual = readback_detail.get(readback_key, "" if readback_key != "relation_flow" else {})
461
+ actual = normalize_verification_value(submit_key, actual)
462
+ if actual not in ("", {}, "{}", None):
463
+ readback_only_fields[submit_key] = actual
464
+ continue
465
+ expected = canonical_submit.get(submit_key, "" if submit_key != "relationFlow" else {})
466
+ actual = readback_detail.get(readback_key, "" if readback_key != "relation_flow" else {})
467
+ expected = normalize_verification_value(submit_key, expected)
468
+ actual = normalize_verification_value(submit_key, actual)
469
+ match = expected == actual
470
+ ok = ok and match
471
+ target = advanced_checks if submit_key in ADVANCED_CANONICAL_KEYS else checks
472
+ target[submit_key] = {
473
+ "match": match,
474
+ "expected": expected,
475
+ "actual": actual,
476
+ }
477
+ return {
478
+ "ok": ok,
479
+ "checks": checks,
480
+ "advancedChecks": advanced_checks,
481
+ "submittedFields": submitted_fields,
482
+ "readbackOnlyFields": readback_only_fields,
483
+ }
484
+
485
+
486
+ def ensure_meta_shape(meta: Dict[str, Any], field_id: Any) -> Dict[str, Any]:
487
+ payload = dict(meta)
488
+ artifact_id = str(payload.get("artifactId") or field_id or "")
489
+ payload.setdefault("artifactId", artifact_id or None)
490
+ payload.setdefault("fieldId", field_id if isinstance(field_id, int) else payload.get("fieldId"))
491
+ payload.setdefault("mode", "edit")
492
+ payload.setdefault("status", "exported")
493
+ payload.setdefault("advancedFieldPresence", {})
494
+ payload.setdefault("listCheckStatus", "not_checked")
495
+ payload.setdefault("lintPassed", False)
496
+ payload.setdefault("lintSha256", None)
497
+ payload.setdefault("lintedAt", None)
498
+ return payload
499
+
500
+
501
+ def write_export_meta(
502
+ path: Path,
503
+ *,
504
+ field_id: Any,
505
+ request_url: str,
506
+ workspace: str,
507
+ language: str,
508
+ flow_type: str,
509
+ flow_key: str,
510
+ raw_path: Path,
511
+ work_path: Path,
512
+ detail: Dict[str, Any],
513
+ ) -> Dict[str, Any]:
514
+ payload = ensure_meta_shape(load_meta(path), field_id)
515
+ payload.update(
516
+ {
517
+ "artifactId": str(field_id),
518
+ "requestUrl": request_url,
519
+ "exportedAt": utc_now_iso(),
520
+ "sourceMode": "api-detail-export",
521
+ "mode": "edit",
522
+ "workspace": workspace,
523
+ "language": language,
524
+ "flowType": flow_type,
525
+ "flowKey": flow_key,
526
+ "rawSha256": file_sha256(raw_path),
527
+ "workSha256": file_sha256(work_path),
528
+ "status": "exported",
529
+ "workConfirmedAt": None,
530
+ "submitConfirmedAt": None,
531
+ "workConfirmedBy": None,
532
+ "submitConfirmedBy": None,
533
+ "submitSha256": None,
534
+ "submitBuiltAt": None,
535
+ "advancedFieldPresence": {
536
+ "sourceComputed": "source_computed" in detail,
537
+ "matchRule": "match_rule" in detail,
538
+ "matchLogic": "match_logic" in detail,
539
+ },
540
+ }
541
+ )
542
+ save_meta(path, payload)
543
+ return payload
544
+
545
+
546
+ def write_create_meta(
547
+ path: Path,
548
+ *,
549
+ artifact_id: str,
550
+ request_url: str,
551
+ workspace: str,
552
+ language: str,
553
+ flow_type: str,
554
+ flow_key: str,
555
+ raw_path: Path,
556
+ work_path: Path,
557
+ detail: Dict[str, Any],
558
+ ) -> Dict[str, Any]:
559
+ payload = ensure_meta_shape(load_meta(path), artifact_id)
560
+ payload.update(
561
+ {
562
+ "artifactId": artifact_id,
563
+ "fieldId": None,
564
+ "remoteFieldId": None,
565
+ "requestUrl": request_url,
566
+ "exportedAt": utc_now_iso(),
567
+ "sourceMode": "local-create-seed",
568
+ "mode": "create",
569
+ "workspace": workspace,
570
+ "language": language,
571
+ "flowType": flow_type,
572
+ "flowKey": flow_key,
573
+ "rawSha256": file_sha256(raw_path),
574
+ "workSha256": file_sha256(work_path),
575
+ "status": "exported",
576
+ "workConfirmedAt": None,
577
+ "submitConfirmedAt": None,
578
+ "workConfirmedBy": None,
579
+ "submitConfirmedBy": None,
580
+ "submitSha256": None,
581
+ "submitBuiltAt": None,
582
+ "advancedFieldPresence": {
583
+ "sourceComputed": "source_computed" in detail,
584
+ "matchRule": "match_rule" in detail,
585
+ "matchLogic": "match_logic" in detail,
586
+ },
587
+ }
588
+ )
589
+ save_meta(path, payload)
590
+ return payload
591
+
592
+
593
+ def update_build_meta(path: Path, *, field_id: Any, work_path: Path, submit_path: Path, submit_payload: Dict[str, Any]) -> Dict[str, Any]:
594
+ payload = ensure_meta_shape(load_meta(path), field_id)
595
+ previous_work_sha = payload.get("workSha256")
596
+ current_work_sha = file_sha256(work_path)
597
+ current_submit_sha = file_sha256(submit_path)
598
+ if payload.get("workConfirmedAt") and previous_work_sha != current_work_sha:
599
+ payload["workConfirmedAt"] = None
600
+ payload["workConfirmedBy"] = None
601
+ payload["workSha256"] = current_work_sha
602
+ payload["submitSha256"] = current_submit_sha
603
+ payload["submitBuiltAt"] = utc_now_iso()
604
+ payload["advancedSubmission"] = {
605
+ key: ("submitted" if key in submit_payload else "omitted")
606
+ for key in ADVANCED_FIELDS
607
+ }
608
+ payload["submitConfirmedAt"] = None
609
+ payload["submitConfirmedBy"] = None
610
+ payload["lintPassed"] = False
611
+ payload["lintSha256"] = None
612
+ payload["lintedAt"] = None
613
+ payload["status"] = "submit_built"
614
+ save_meta(path, payload)
615
+ return payload
616
+
617
+
618
+ def update_lint_meta(path: Path, *, field_id: Any, submit_path: Path, lint_path: Path, lint_report: Dict[str, Any]) -> Dict[str, Any]:
619
+ payload = ensure_meta_shape(load_meta(path), field_id)
620
+ payload["submitSha256"] = file_sha256(submit_path)
621
+ payload["lintPassed"] = bool(lint_report.get("ok"))
622
+ payload["lintSha256"] = file_sha256(lint_path)
623
+ payload["lintedAt"] = utc_now_iso()
624
+ save_meta(path, payload)
625
+ return payload
626
+
627
+
628
+ def update_confirmation_state(
629
+ meta_path: Path,
630
+ *,
631
+ field_id: Any,
632
+ actor: str,
633
+ stage: str,
634
+ work_path: Path,
635
+ submit_path: Optional[Path] = None,
636
+ ) -> Dict[str, Any]:
637
+ payload = ensure_meta_shape(load_meta(meta_path), field_id)
638
+ payload["workSha256"] = file_sha256(work_path)
639
+ now = utc_now_iso()
640
+ if stage == "work":
641
+ payload["workConfirmedAt"] = now
642
+ payload["workConfirmedBy"] = actor
643
+ payload["submitConfirmedAt"] = None
644
+ payload["submitConfirmedBy"] = None
645
+ payload["submitSha256"] = file_sha256(submit_path) if submit_path and submit_path.exists() else None
646
+ payload["status"] = "work_confirmed"
647
+ elif stage == "submit":
648
+ if submit_path is None or not submit_path.exists():
649
+ raise SystemExit("submit confirmation requires an existing submit file")
650
+ confirmed_work_sha = payload.get("workSha256")
651
+ current_work_sha = file_sha256(work_path)
652
+ if payload.get("status") != "submit_built":
653
+ raise SystemExit("submit confirmation requires a freshly built submit payload")
654
+ if not payload.get("workConfirmedAt") or confirmed_work_sha != current_work_sha:
655
+ raise SystemExit("work file is not confirmed or has changed; reconfirm work before submit")
656
+ payload["submitSha256"] = file_sha256(submit_path)
657
+ payload["submitConfirmedAt"] = now
658
+ payload["submitConfirmedBy"] = actor
659
+ payload["status"] = "submit_confirmed"
660
+ else:
661
+ raise SystemExit(f"unsupported confirmation stage: {stage}")
662
+ save_meta(meta_path, payload)
663
+ return payload
664
+
665
+
666
+ def ensure_submission_allowed(meta_path: Path, work_path: Path, submit_path: Path) -> Dict[str, Any]:
667
+ if not meta_path.exists():
668
+ raise SystemExit("submission blocked: missing meta confirmation file")
669
+ raw_meta = load_meta(meta_path)
670
+ meta = ensure_meta_shape(raw_meta, raw_meta.get("fieldId") or raw_meta.get("artifactId"))
671
+ if not meta.get("artifactId"):
672
+ raise SystemExit("submission blocked: meta is malformed, missing artifactId")
673
+ if not meta.get("workConfirmedAt"):
674
+ raise SystemExit("submission blocked: missing work confirmation")
675
+ if not meta.get("submitBuiltAt"):
676
+ raise SystemExit("submission blocked: submit payload has not been built")
677
+ if not meta.get("submitConfirmedAt"):
678
+ raise SystemExit("submission blocked: missing submit confirmation")
679
+ if not meta.get("workSha256"):
680
+ raise SystemExit("submission blocked: meta is malformed, missing workSha256")
681
+ if not meta.get("submitSha256"):
682
+ raise SystemExit("submission blocked: meta is malformed, missing submitSha256")
683
+ if meta.get("status") != "submit_confirmed":
684
+ raise SystemExit(f"submission blocked: current status is {meta.get('status')}, expected submit_confirmed")
685
+ current_work_sha = file_sha256(work_path)
686
+ current_submit_sha = file_sha256(submit_path)
687
+ if meta.get("workSha256") != current_work_sha:
688
+ raise SystemExit("submission blocked: work file changed after confirmation")
689
+ if meta.get("submitSha256") != current_submit_sha:
690
+ raise SystemExit("submission blocked: submit file changed after confirmation")
691
+ if meta.get("lintPassed") is not True:
692
+ raise SystemExit("submission blocked: lint has not passed")
693
+ if not meta.get("lintSha256"):
694
+ raise SystemExit("submission blocked: missing lint result")
695
+ submit_built_at = meta.get("submitBuiltAt")
696
+ work_confirmed_at = meta.get("workConfirmedAt")
697
+ if submit_built_at and work_confirmed_at and submit_built_at < work_confirmed_at:
698
+ raise SystemExit("submission blocked: submit payload predates work confirmation")
699
+ lint_report = lint_dataset_field_semantics(load_json(work_path), mode=str(meta.get("mode") or "edit"))
700
+ if lint_report["errors"]:
701
+ raise SystemExit("submission blocked by lint: " + "; ".join(lint_report["errors"]))
702
+ return meta
703
+
704
+
705
+ @dataclass
706
+ class ApiClient:
707
+ base_url: str
708
+ workspace: str
709
+ language: str
710
+ cookie_header: str
711
+ timeout: float
712
+ insecure: bool = False
713
+
714
+ def _build_url(self, path: str) -> str:
715
+ suffix = f"$workspace={urllib.parse.quote(self.workspace)}&$language={urllib.parse.quote(self.language)}"
716
+ joiner = "&" if "?" in path else "?"
717
+ return self.base_url.rstrip("/") + path + joiner + suffix
718
+
719
+ def request(self, method: str, path: str, body: Optional[dict] = None) -> dict:
720
+ headers = {
721
+ "content-type": "application/json",
722
+ "cookie": self.cookie_header,
723
+ "accept": "application/json, text/plain, */*",
724
+ }
725
+ data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
726
+ req = urllib.request.Request(self._build_url(path), data=data, headers=headers, method=method)
727
+ context = ssl._create_unverified_context() if self.insecure else None
728
+ try:
729
+ with urllib.request.urlopen(req, timeout=self.timeout, context=context) as resp:
730
+ raw = resp.read().decode("utf-8", "replace")
731
+ except urllib.error.HTTPError as err:
732
+ raw = err.read().decode("utf-8", "replace")
733
+ raise SystemExit(f"HTTP {err.code} {path}: {raw}") from err
734
+ except urllib.error.URLError as err:
735
+ raise SystemExit(f"Request failed {path}: {err}") from err
736
+ payload = json.loads(raw)
737
+ if payload.get("code") != 0:
738
+ raise SystemExit(f"API error {path}: {payload}")
739
+ return payload
740
+
741
+ def get_dataset_field(self, field_id: Any) -> dict:
742
+ return self.request("GET", f"/bpmax/data-set-field/{field_id}")
743
+
744
+ def create_dataset_field(self, body: Dict[str, Any]) -> dict:
745
+ return self.request("POST", "/bpmax/data-set-field", body)
746
+
747
+ def update_dataset_field(self, field_id: Any, body: Dict[str, Any]) -> dict:
748
+ return self.request("PUT", f"/bpmax/data-set-field/{field_id}", body)
749
+
750
+
751
+ def extract_field_id_from_response(response: Dict[str, Any]) -> Any:
752
+ data = response.get("data")
753
+ if isinstance(data, dict):
754
+ for key in ("id", "field_id"):
755
+ if data.get(key) not in (None, ""):
756
+ return data[key]
757
+ if data not in (None, "") and not isinstance(data, (list, dict)):
758
+ return data
759
+ raise SystemExit(f"unable to resolve created field id from response: {response}")
760
+
761
+
762
+ def resolve_cookie_header(value: Optional[str]) -> str:
763
+ cookie = value or os.environ.get("BPMAX_COOKIE_HEADER", "")
764
+ if not cookie:
765
+ raise SystemExit("missing cookie header: pass --cookie-header or set BPMAX_COOKIE_HEADER")
766
+ return cookie
767
+
768
+
769
+ def resolve_workspace(value: Optional[str]) -> str:
770
+ workspace = value or os.environ.get("BPMAX_WORKSPACE", "")
771
+ if not workspace:
772
+ raise SystemExit("missing workspace: pass --workspace or set BPMAX_WORKSPACE")
773
+ return workspace
774
+
775
+
776
+ def build_client(args: Any) -> ApiClient:
777
+ return ApiClient(
778
+ base_url=resolve_base_url(getattr(args, "base_url", None)),
779
+ workspace=resolve_workspace(getattr(args, "workspace", None)),
780
+ language=getattr(args, "language", DEFAULT_LANGUAGE),
781
+ cookie_header=resolve_cookie_header(getattr(args, "cookie_header", None)),
782
+ timeout=float(getattr(args, "timeout", 30)),
783
+ insecure=bool(getattr(args, "insecure", False)),
784
+ )