bpmax-cli 0.1.44 → 0.2.1-beta.2
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.
- package/README.md +52 -5
- package/dist/bin.js +12304 -1315
- package/dist/bin.js.map +1 -1
- package/package.json +1 -1
- package/scripts/install-skills.mjs +98 -0
- package/skills/bpmax-ai-taskbook/SKILL.md +227 -0
- package/skills/bpmax-ai-taskbook/agents/openai.yaml +3 -0
- package/skills/bpmax-ai-taskbook/references/taskbook-template.md +68 -0
- package/skills/bpmax-api-platform-editor/SKILL.md +321 -0
- package/skills/bpmax-api-platform-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-api-platform-editor/references/api-doc-debug-workflow.md +34 -0
- package/skills/bpmax-api-platform-editor/references/api-proxy-shape.md +41 -0
- package/skills/bpmax-api-platform-editor/references/instance-config-shape.md +41 -0
- package/skills/bpmax-api-platform-editor/references/platform-api-map.md +52 -0
- package/skills/bpmax-api-platform-editor/references/runtime-workflow.md +32 -0
- package/skills/bpmax-api-platform-editor/scripts/api_platform_editor_common.py +1276 -0
- package/skills/bpmax-api-platform-editor/scripts/build_submit_payload.py +64 -0
- package/skills/bpmax-api-platform-editor/scripts/capture_write_contract.py +40 -0
- package/skills/bpmax-api-platform-editor/scripts/export_layer_bundle.py +212 -0
- package/skills/bpmax-api-platform-editor/scripts/record_doc_debug_acceptance.py +62 -0
- package/skills/bpmax-api-platform-editor/scripts/submit_and_verify_layer.py +75 -0
- package/skills/bpmax-api-platform-editor/tests/test_api_platform_editor.py +287 -0
- package/skills/bpmax-approval-matrix/SKILL.md +90 -0
- package/skills/bpmax-auth/SKILL.md +6 -17
- package/skills/bpmax-builder-shared/SKILL.md +44 -0
- package/skills/bpmax-builder-shared/base_url.py +81 -0
- package/skills/bpmax-builder-shared/runtime-script-site-matrix.json +71 -0
- package/skills/bpmax-builder-shared/runtime-script-site-matrix.md +34 -0
- package/skills/bpmax-builder-shared/runtime-script-template-catalog.md +123 -0
- package/skills/bpmax-builder-shared/runtime_script_rules.py +272 -0
- package/skills/bpmax-builder-shared/skill_audit.py +374 -0
- package/skills/bpmax-builder-shared/template_script_hard_rules.py +280 -0
- package/skills/bpmax-builder-shared/tests/test_base_url.py +80 -0
- package/skills/bpmax-builder-shared/tests/test_runtime_script_rules.py +115 -0
- package/skills/bpmax-builder-shared/tests/test_skill_audit.py +231 -0
- package/skills/bpmax-builder-shared/tests/test_template_script_hard_rules.py +281 -0
- package/skills/bpmax-cli/SKILL.md +5 -0
- package/skills/bpmax-config-latest/SKILL.md +71 -0
- package/skills/bpmax-console-template-editor/SKILL.md +536 -0
- package/skills/bpmax-console-template-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-console-template-editor/references/filter-integration.md +60 -0
- package/skills/bpmax-console-template-editor/references/lessons-from-resume-dashboard.md +114 -0
- package/skills/bpmax-console-template-editor/references/local-temp-workflow.md +69 -0
- package/skills/bpmax-console-template-editor/references/module-catalog.md +100 -0
- package/skills/bpmax-console-template-editor/references/runtime-page-shape.md +91 -0
- package/skills/bpmax-console-template-editor/references/template-shape.md +149 -0
- package/skills/bpmax-console-template-editor/scripts/build_submit_payload.py +38 -0
- package/skills/bpmax-console-template-editor/scripts/confirm_console_template.py +33 -0
- package/skills/bpmax-console-template-editor/scripts/console_template_editor_common.py +964 -0
- package/skills/bpmax-console-template-editor/scripts/export_console_template.py +99 -0
- package/skills/bpmax-console-template-editor/scripts/lint_console_template.py +46 -0
- package/skills/bpmax-console-template-editor/scripts/submit_console_template.py +99 -0
- package/skills/bpmax-console-template-editor/tests/test_console_template_editor.py +383 -0
- package/skills/bpmax-dataset-field-template-editor/SKILL.md +606 -0
- package/skills/bpmax-dataset-field-template-editor/references/create-request-gotchas.md +25 -0
- package/skills/bpmax-dataset-field-template-editor/references/field-classify-mapping.md +35 -0
- package/skills/bpmax-dataset-field-template-editor/references/nested-field-patterns.md +24 -0
- package/skills/bpmax-dataset-field-template-editor/references/runtime-verified-field-page-shape.md +61 -0
- package/skills/bpmax-dataset-field-template-editor/references/virtual-field-patterns.md +27 -0
- package/skills/bpmax-dataset-field-template-editor/references/work-file-to-submit-mapping.md +127 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/build_submit_payload.py +67 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/confirm_dataset_field.py +37 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/dataset_field_editor_common.py +784 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/export_dataset_field.py +62 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/init_create_dataset_field.py +104 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/inspect_dataset_field_runtime.py +83 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/lint_dataset_field_semantics.py +35 -0
- package/skills/bpmax-dataset-field-template-editor/scripts/submit_dataset_field.py +95 -0
- package/skills/bpmax-dataset-field-template-editor/tests/test_dataset_field_editor.py +709 -0
- package/skills/bpmax-dataset-field-template-editor/tests/test_init_create_dataset_field.py +59 -0
- package/skills/bpmax-dataset-template-editor/SKILL.md +779 -0
- package/skills/bpmax-dataset-template-editor/references/custom-key-usage-patterns.md +18 -0
- package/skills/bpmax-dataset-template-editor/references/dataset-script-runtime-matrix.md +73 -0
- package/skills/bpmax-dataset-template-editor/references/pre-process-script-authoring-guide.md +186 -0
- package/skills/bpmax-dataset-template-editor/references/pre-process-script-example-catalog.md +106 -0
- package/skills/bpmax-dataset-template-editor/references/runtime-gotchas.md +28 -0
- package/skills/bpmax-dataset-template-editor/references/runtime-verified-dataset-page-shape.md +47 -0
- package/skills/bpmax-dataset-template-editor/references/ui-to-backend-field-map.md +23 -0
- package/skills/bpmax-dataset-template-editor/references/work-file-to-submit-mapping.md +97 -0
- package/skills/bpmax-dataset-template-editor/scripts/basic_table_audit.py +65 -0
- package/skills/bpmax-dataset-template-editor/scripts/build_submit_payload.py +38 -0
- package/skills/bpmax-dataset-template-editor/scripts/dataset_editor_common.py +650 -0
- package/skills/bpmax-dataset-template-editor/scripts/export_dataset.py +155 -0
- package/skills/bpmax-dataset-template-editor/scripts/lint_dataset_template.py +42 -0
- package/skills/bpmax-dataset-template-editor/scripts/resolve_dataset.py +43 -0
- package/skills/bpmax-dataset-template-editor/scripts/scan_custom_key_references.py +27 -0
- package/skills/bpmax-dataset-template-editor/scripts/submit_dataset.py +115 -0
- package/skills/bpmax-dataset-template-editor/scripts/verify_dataset_list.py +52 -0
- package/skills/bpmax-dataset-template-editor/scripts/verify_publish_health.py +39 -0
- package/skills/bpmax-dataset-template-editor/tests/test_dataset_editor.py +373 -0
- package/skills/bpmax-e2e-flow-config-orchestrator/SKILL.md +217 -0
- package/skills/bpmax-e2e-flow-config-orchestrator/agents/openai.yaml +4 -0
- package/skills/bpmax-e2e-flow-config-orchestrator/references/orchestration-matrix.md +63 -0
- package/skills/bpmax-e2e-flow-test-operator/SKILL.md +551 -0
- package/skills/bpmax-e2e-flow-test-operator/agents/openai.yaml +5 -0
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale.json +97 -0
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_final_v2.json +105 -0
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_main.json +36 -0
- package/skills/bpmax-e2e-flow-test-operator/profiles/negative_sale_region.json +40 -0
- package/skills/bpmax-e2e-flow-test-operator/references/ai-test-suite.md +333 -0
- package/skills/bpmax-e2e-flow-test-operator/references/browser-only-checkpoints.md +41 -0
- package/skills/bpmax-e2e-flow-test-operator/references/failure-update-loop.md +17 -0
- package/skills/bpmax-e2e-flow-test-operator/references/filter-field-discovery.md +40 -0
- package/skills/bpmax-e2e-flow-test-operator/references/minimal-test-loop.md +24 -0
- package/skills/bpmax-e2e-flow-test-operator/references/negative-sale-api-matrix.md +75 -0
- package/skills/bpmax-e2e-flow-test-operator/references/profile-schema.md +109 -0
- package/skills/bpmax-e2e-flow-test-operator/references/skill-experience-coverage-matrix.md +29 -0
- package/skills/bpmax-e2e-flow-test-operator/references/stale-runtime-and-clean-sample-rules.md +54 -0
- package/skills/bpmax-e2e-flow-test-operator/references/state-schema.md +83 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/bpmax_session.py +287 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/dealer_sample_on_shelf_plan.json +59 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/dealer_sample_on_shelf_runner.py +687 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_doc.py +121 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/e2e_state.py +288 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_api_matrix.py +161 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_filter_fields.py +138 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_form_runtime.py +396 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_runner.py +341 -0
- package/skills/bpmax-e2e-flow-test-operator/scripts/flow_test_profile.py +185 -0
- package/skills/bpmax-e2e-flow-test-operator/tests/test_negative_sale_api_tools.py +138 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/SKILL.md +69 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-checklist.md +42 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-recipes.md +38 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/config-shape.md +86 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/gate-lint.md +68 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/hoocoo-patterns.md +39 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/runtime-behavior.md +41 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/references/script-authoring.md +110 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/scripts/lint_feishu_chat_plugin.py +278 -0
- package/skills/bpmax-feishu-chat-flow-plugin-editor/tests/test_lint_feishu_chat_plugin.py +203 -0
- package/skills/bpmax-filter-template-editor/SKILL.md +564 -0
- package/skills/bpmax-filter-template-editor/references/experience-coverage-matrix.md +38 -0
- package/skills/bpmax-filter-template-editor/references/filter-and-flow-binding.md +57 -0
- package/skills/bpmax-filter-template-editor/references/filter-content-schema.md +141 -0
- package/skills/bpmax-filter-template-editor/references/filter-request-shape.md +287 -0
- package/skills/bpmax-filter-template-editor/references/filter-runtime-patterns.md +115 -0
- package/skills/bpmax-filter-template-editor/references/runtime-verified-filter-page-shape.md +94 -0
- package/skills/bpmax-filter-template-editor/scripts/build_submit_payload.py +25 -0
- package/skills/bpmax-filter-template-editor/scripts/confirm_filter_template.py +22 -0
- package/skills/bpmax-filter-template-editor/scripts/export_filter_template.py +57 -0
- package/skills/bpmax-filter-template-editor/scripts/filter_template_editor_common.py +348 -0
- package/skills/bpmax-filter-template-editor/scripts/init_create_filter_template.py +8 -0
- package/skills/bpmax-filter-template-editor/scripts/lint_filter_template_semantics.py +26 -0
- package/skills/bpmax-filter-template-editor/scripts/submit_filter_template.py +62 -0
- package/skills/bpmax-filter-template-editor/tests/test_filter_template_editor.py +231 -0
- package/skills/bpmax-flow-template-editor/SKILL.md +1095 -0
- package/skills/bpmax-flow-template-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-flow-template-editor/references/before-next-step-script-runtime-gotchas.md +62 -0
- package/skills/bpmax-flow-template-editor/references/config-surfaces-and-placeholders.md +270 -0
- package/skills/bpmax-flow-template-editor/references/diff-strategy.md +67 -0
- package/skills/bpmax-flow-template-editor/references/editor-runtime-vs-draft.md +25 -0
- package/skills/bpmax-flow-template-editor/references/flow-template-api-workflow.md +174 -0
- package/skills/bpmax-flow-template-editor/references/intent-model.md +117 -0
- package/skills/bpmax-flow-template-editor/references/lessons-from-price-plan-flow.md +147 -0
- package/skills/bpmax-flow-template-editor/references/local-temp-workflow.md +97 -0
- package/skills/bpmax-flow-template-editor/references/matrix-flow-form-nav-collaboration.md +168 -0
- package/skills/bpmax-flow-template-editor/references/payload-checklist.md +133 -0
- package/skills/bpmax-flow-template-editor/references/project-create-runtime-gotchas.md +106 -0
- package/skills/bpmax-flow-template-editor/references/requirement-to-node-mapping.md +149 -0
- package/skills/bpmax-flow-template-editor/references/runtime-verified-flow-detail-shape.md +41 -0
- package/skills/bpmax-flow-template-editor/references/runtime-verified-meta-fields.md +155 -0
- package/skills/bpmax-flow-template-editor/references/runtime-verified-node-fields.md +179 -0
- package/skills/bpmax-flow-template-editor/references/save-draft-request-shape.md +91 -0
- package/skills/bpmax-flow-template-editor/references/script-review-hard-rules.md +96 -0
- package/skills/bpmax-flow-template-editor/references/work-file-to-submit-mapping.md +57 -0
- package/skills/bpmax-flow-template-editor/scripts/build_submit_payload.py +69 -0
- package/skills/bpmax-flow-template-editor/scripts/confirm_flow_template.py +52 -0
- package/skills/bpmax-flow-template-editor/scripts/export_flow_template.py +114 -0
- package/skills/bpmax-flow-template-editor/scripts/flow_template_editor_common.py +1084 -0
- package/skills/bpmax-flow-template-editor/scripts/submit_flow_template.py +159 -0
- package/skills/bpmax-flow-template-editor/tests/test_flow_template_editor.py +636 -0
- package/skills/bpmax-form-template-editor/SKILL.md +1113 -0
- package/skills/bpmax-form-template-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-form-template-editor/references/form-template-api-workflow.md +203 -0
- package/skills/bpmax-form-template-editor/references/local-temp-workflow.md +125 -0
- package/skills/bpmax-form-template-editor/references/payload-checklist.md +77 -0
- package/skills/bpmax-form-template-editor/references/sub-form-patterns.md +49 -0
- package/skills/bpmax-form-template-editor/scripts/build_submit_payload.py +37 -0
- package/skills/bpmax-form-template-editor/scripts/check_form_template_consistency.py +145 -0
- package/skills/bpmax-form-template-editor/scripts/confirm_form_template.py +67 -0
- package/skills/bpmax-form-template-editor/scripts/export_form_template.py +91 -0
- package/skills/bpmax-form-template-editor/scripts/form_template_editor_common.py +1762 -0
- package/skills/bpmax-form-template-editor/scripts/lint_form_template_semantics.py +30 -0
- package/skills/bpmax-form-template-editor/scripts/record_runtime_acceptance.py +67 -0
- package/skills/bpmax-form-template-editor/scripts/submit_form_template.py +163 -0
- package/skills/bpmax-form-template-editor/tests/test_form_template_editor.py +1292 -0
- package/skills/bpmax-list-template-editor/SKILL.md +478 -0
- package/skills/bpmax-list-template-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-list-template-editor/references/browser-page-contract.md +81 -0
- package/skills/bpmax-list-template-editor/references/content-config-shape.md +165 -0
- package/skills/bpmax-list-template-editor/references/dataset-field-mapping.md +60 -0
- package/skills/bpmax-list-template-editor/references/list-template-api-workflow.md +108 -0
- package/skills/bpmax-list-template-editor/references/local-temp-workflow.md +102 -0
- package/skills/bpmax-list-template-editor/references/payload-checklist.md +47 -0
- package/skills/bpmax-list-template-editor/references/runtime-verified-workflow.md +147 -0
- package/skills/bpmax-list-template-editor/references/special-formats.md +411 -0
- package/skills/bpmax-list-template-editor/scripts/build_submit_payload.py +37 -0
- package/skills/bpmax-list-template-editor/scripts/confirm_list_template.py +33 -0
- package/skills/bpmax-list-template-editor/scripts/export_list_template.py +89 -0
- package/skills/bpmax-list-template-editor/scripts/fetch_data_set.py +34 -0
- package/skills/bpmax-list-template-editor/scripts/lint_list_template_semantics.py +54 -0
- package/skills/bpmax-list-template-editor/scripts/list_template_editor_common.py +955 -0
- package/skills/bpmax-list-template-editor/scripts/record_acceptance.py +55 -0
- package/skills/bpmax-list-template-editor/scripts/submit_list_template.py +117 -0
- package/skills/bpmax-list-template-editor/tests/test_list_template_editor_common.py +441 -0
- package/skills/bpmax-memory-protocol/SKILL.md +72 -0
- package/skills/bpmax-nav-config-editor/SKILL.md +350 -0
- package/skills/bpmax-nav-config-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-nav-config-editor/references/api-workflow.md +70 -0
- package/skills/bpmax-nav-config-editor/references/config-shape.md +78 -0
- package/skills/bpmax-nav-config-editor/references/icon-selection.md +83 -0
- package/skills/bpmax-nav-config-editor/references/path-mapping-rules.md +51 -0
- package/skills/bpmax-nav-config-editor/references/payload-checklist.md +41 -0
- package/skills/bpmax-nav-config-editor/references/runtime-probing.md +47 -0
- package/skills/bpmax-nav-config-editor/scripts/build_submit_payload.py +34 -0
- package/skills/bpmax-nav-config-editor/scripts/confirm_nav_config.py +32 -0
- package/skills/bpmax-nav-config-editor/scripts/export_nav_config.py +56 -0
- package/skills/bpmax-nav-config-editor/scripts/lint_nav_config_semantics.py +33 -0
- package/skills/bpmax-nav-config-editor/scripts/nav_config_editor_common.py +812 -0
- package/skills/bpmax-nav-config-editor/scripts/submit_nav_config.py +44 -0
- package/skills/bpmax-nav-config-editor/scripts/verify_nav_config.py +33 -0
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_editor.py +358 -0
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_editor_common.py +138 -0
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_lint.py +58 -0
- package/skills/bpmax-nav-config-editor/tests/test_nav_config_submit_verify.py +51 -0
- package/skills/bpmax-plugin-config/SKILL.md +42 -0
- package/skills/bpmax-project/SKILL.md +17 -3
- package/skills/bpmax-project-detail-template-editor/SKILL.md +355 -0
- package/skills/bpmax-project-detail-template-editor/agents/openai.yaml +4 -0
- package/skills/bpmax-project-detail-template-editor/references/local-temp-workflow.md +59 -0
- package/skills/bpmax-project-detail-template-editor/references/module-catalog-and-config-notes.md +120 -0
- package/skills/bpmax-project-detail-template-editor/references/payload-checklist.md +33 -0
- package/skills/bpmax-project-detail-template-editor/references/project-detail-template-api-workflow.md +44 -0
- package/skills/bpmax-project-detail-template-editor/scripts/build_submit_payload.py +30 -0
- package/skills/bpmax-project-detail-template-editor/scripts/confirm_project_detail_template.py +33 -0
- package/skills/bpmax-project-detail-template-editor/scripts/export_project_detail_template.py +87 -0
- package/skills/bpmax-project-detail-template-editor/scripts/lint_project_detail_template_semantics.py +37 -0
- package/skills/bpmax-project-detail-template-editor/scripts/project_detail_template_editor_common.py +507 -0
- package/skills/bpmax-project-detail-template-editor/scripts/submit_project_detail_template.py +120 -0
- package/skills/bpmax-project-detail-template-editor/tests/test_project_detail_template_editor.py +369 -0
- package/skills/bpmax-role-editor/SKILL.md +251 -0
- package/skills/bpmax-role-editor/references/api-workflow.md +30 -0
- package/skills/bpmax-role-editor/references/runtime-page-shape.md +18 -0
- package/skills/bpmax-role-editor/references/work-file-mapping.md +32 -0
- package/skills/bpmax-role-editor/scripts/build_submit_payload.py +38 -0
- package/skills/bpmax-role-editor/scripts/confirm_role.py +33 -0
- package/skills/bpmax-role-editor/scripts/export_role.py +163 -0
- package/skills/bpmax-role-editor/scripts/lint_role_semantics.py +38 -0
- package/skills/bpmax-role-editor/scripts/role_editor_common.py +1231 -0
- package/skills/bpmax-role-editor/scripts/submit_role.py +144 -0
- package/skills/bpmax-role-editor/tests/test_role_editor.py +343 -0
- package/skills/bpmax-shared/SKILL.md +1 -1
- package/skills/bpmax-user-mock-operator/SKILL.md +106 -0
- package/skills/bpmax-user-mock-operator/agents/openai.yaml +4 -0
- package/skills/bpmax-user-mock-operator/scripts/switch_user_identity.py +37 -0
- package/skills/bpmax-user-mock-operator/scripts/user_mock_operator_common.py +136 -0
- package/skills/bpmax-user-mock-operator/tests/test_user_mock_operator.py +138 -0
- package/skills/bpmax-workspace-editor/SKILL.md +78 -0
- package/skills/bpmax-workspace-editor/agents/openai.yaml +4 -0
- package/skills/form-control-library/SKILL.md +82 -0
- package/skills/form-control-library/agents/openai.yaml +4 -0
- package/skills/form-control-library/references/form-controls.md +199 -0
- package/skills/form-control-library/references/form-template-submit-schema.md +180 -0
- package/skills/form-control-library/references/group-select-runtime.md +191 -0
- package/skills/form-control-library/scripts/rebuild_form_control_library.py +55 -0
|
@@ -0,0 +1,1231 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import copy
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import ssl
|
|
10
|
+
import sys
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from difflib import unified_diff
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any, Dict, Iterable, Optional
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
SHARED_SKILL_ROOT = Path(__file__).resolve().parents[2] / "bpmax-builder-shared"
|
|
22
|
+
if str(SHARED_SKILL_ROOT) not in sys.path:
|
|
23
|
+
sys.path.insert(0, str(SHARED_SKILL_ROOT))
|
|
24
|
+
from base_url import DEFAULT_BASE_URL, resolve_base_url
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
DEFAULT_LANGUAGE = "zhCN"
|
|
28
|
+
REPO_ROOT = Path(__file__).resolve().parents[4]
|
|
29
|
+
TMP_ROOT = REPO_ROOT / ".codex" / "tmp" / "role-editor"
|
|
30
|
+
TMP_SUBDIRS = ("raw", "work", "meta", "submit", "diffs", "result")
|
|
31
|
+
ROLE_KEY_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_:-]*$")
|
|
32
|
+
DEFAULT_PERMISSIONS = {"system": [], "custom": [], "flow": {}, "workspace": {}}
|
|
33
|
+
VISIBLE_SCOPE_TO_MODE = {
|
|
34
|
+
"team.all": "all",
|
|
35
|
+
"team.self": "self",
|
|
36
|
+
"team.specify_team_and_user": "custom",
|
|
37
|
+
}
|
|
38
|
+
MODE_TO_VISIBLE_SCOPE = {value: key for key, value in VISIBLE_SCOPE_TO_MODE.items()}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def utc_now_iso() -> str:
|
|
42
|
+
return datetime.now(timezone.utc).isoformat()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def ensure_tmp_dirs() -> None:
|
|
46
|
+
for part in TMP_SUBDIRS:
|
|
47
|
+
(TMP_ROOT / part).mkdir(parents=True, exist_ok=True)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def dump_json(path: Path, payload: Any) -> None:
|
|
51
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_json(path: Path) -> Any:
|
|
56
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def file_sha256(path: Path) -> str:
|
|
60
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def stable_json_lines(payload: Any) -> list[str]:
|
|
64
|
+
return (json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n").splitlines(keepends=True)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def write_diff(path: Path, before: Any, after: Any, before_label: str, after_label: str) -> None:
|
|
68
|
+
diff = unified_diff(
|
|
69
|
+
stable_json_lines(before),
|
|
70
|
+
stable_json_lines(after),
|
|
71
|
+
fromfile=before_label,
|
|
72
|
+
tofile=after_label,
|
|
73
|
+
)
|
|
74
|
+
text = "".join(diff)
|
|
75
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
76
|
+
path.write_text(text or "# no diff\n", encoding="utf-8")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def paths_for(stem: str) -> Dict[str, Path]:
|
|
80
|
+
ensure_tmp_dirs()
|
|
81
|
+
return {
|
|
82
|
+
"raw": TMP_ROOT / "raw" / f"{stem}.json",
|
|
83
|
+
"work": TMP_ROOT / "work" / f"{stem}.json",
|
|
84
|
+
"meta": TMP_ROOT / "meta" / f"{stem}.json",
|
|
85
|
+
"submit": TMP_ROOT / "submit" / f"{stem}.json",
|
|
86
|
+
"work_diff": TMP_ROOT / "diffs" / f"{stem}.work.diff.txt",
|
|
87
|
+
"submit_diff": TMP_ROOT / "diffs" / f"{stem}.submit.diff.txt",
|
|
88
|
+
"response": TMP_ROOT / "result" / f"{stem}.response.json",
|
|
89
|
+
"readback": TMP_ROOT / "result" / f"{stem}.readback.json",
|
|
90
|
+
"verify": TMP_ROOT / "result" / f"{stem}.verify.json",
|
|
91
|
+
"drift": TMP_ROOT / "result" / f"{stem}.drift.json",
|
|
92
|
+
"lint": TMP_ROOT / "result" / f"{stem}.lint.json",
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def load_meta(path: Path) -> Dict[str, Any]:
|
|
97
|
+
if not path.exists():
|
|
98
|
+
return {}
|
|
99
|
+
payload = load_json(path)
|
|
100
|
+
if not isinstance(payload, dict):
|
|
101
|
+
raise SystemExit(f"invalid meta file: {path}")
|
|
102
|
+
return payload
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def save_meta(path: Path, payload: Dict[str, Any]) -> None:
|
|
106
|
+
dump_json(path, payload)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def ensure_meta_shape(meta: Dict[str, Any], stem: str) -> Dict[str, Any]:
|
|
110
|
+
payload = dict(meta)
|
|
111
|
+
payload.setdefault("stem", stem)
|
|
112
|
+
payload.setdefault("status", "exported")
|
|
113
|
+
payload.setdefault("notes", "")
|
|
114
|
+
payload.setdefault("lintOk", None)
|
|
115
|
+
return payload
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def canonical_json(value: Any) -> str:
|
|
119
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def normalize_id_list(values: Any, *, allow_zero: bool = False) -> list[int]:
|
|
123
|
+
if values in (None, ""):
|
|
124
|
+
return []
|
|
125
|
+
if not isinstance(values, list):
|
|
126
|
+
raise SystemExit("expected an array of numeric ids")
|
|
127
|
+
normalized: list[int] = []
|
|
128
|
+
for idx, value in enumerate(values):
|
|
129
|
+
if isinstance(value, bool):
|
|
130
|
+
raise SystemExit(f"id list item {idx} cannot be boolean")
|
|
131
|
+
if isinstance(value, int):
|
|
132
|
+
number = value
|
|
133
|
+
elif isinstance(value, str) and value.strip().isdigit():
|
|
134
|
+
number = int(value.strip())
|
|
135
|
+
else:
|
|
136
|
+
raise SystemExit(f"id list item {idx} must be an integer or integer string")
|
|
137
|
+
if number < 0 or (number == 0 and not allow_zero):
|
|
138
|
+
raise SystemExit(f"id list item {idx} must be positive")
|
|
139
|
+
normalized.append(number)
|
|
140
|
+
return normalized
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def normalize_visible_scope(detail: Dict[str, Any]) -> Dict[str, Any]:
|
|
144
|
+
raw = detail.get("visible_scope")
|
|
145
|
+
if isinstance(raw, str):
|
|
146
|
+
text = raw.strip()
|
|
147
|
+
if not text:
|
|
148
|
+
raw = {}
|
|
149
|
+
else:
|
|
150
|
+
raw = json.loads(text)
|
|
151
|
+
if not isinstance(raw, dict):
|
|
152
|
+
raw = {}
|
|
153
|
+
value = raw.get("value") or "team.self"
|
|
154
|
+
mode = VISIBLE_SCOPE_TO_MODE.get(value, "all")
|
|
155
|
+
config = raw.get("config") if isinstance(raw.get("config"), dict) else {}
|
|
156
|
+
normalized = {
|
|
157
|
+
"mode": mode,
|
|
158
|
+
"config": {
|
|
159
|
+
"role": copy.deepcopy(config.get("role") if isinstance(config.get("role"), list) else []),
|
|
160
|
+
"user": copy.deepcopy(config.get("user") if isinstance(config.get("user"), list) else []),
|
|
161
|
+
"group": copy.deepcopy(config.get("group") if isinstance(config.get("group"), list) else []),
|
|
162
|
+
},
|
|
163
|
+
}
|
|
164
|
+
return normalized
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def build_visible_scope_payload(work_scope: Dict[str, Any]) -> Dict[str, Any]:
|
|
168
|
+
mode = work_scope.get("mode") or "all"
|
|
169
|
+
if mode not in MODE_TO_VISIBLE_SCOPE:
|
|
170
|
+
raise SystemExit(f"unsupported visible scope mode: {mode}")
|
|
171
|
+
config = work_scope.get("config") if isinstance(work_scope.get("config"), dict) else {}
|
|
172
|
+
normalized = {
|
|
173
|
+
"value": MODE_TO_VISIBLE_SCOPE[mode],
|
|
174
|
+
"config": {
|
|
175
|
+
"role": copy.deepcopy(config.get("role") if isinstance(config.get("role"), list) else []),
|
|
176
|
+
"user": copy.deepcopy(config.get("user") if isinstance(config.get("user"), list) else []),
|
|
177
|
+
"group": copy.deepcopy(config.get("group") if isinstance(config.get("group"), list) else []),
|
|
178
|
+
},
|
|
179
|
+
}
|
|
180
|
+
return normalized
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def normalize_permission_bucket(value: Any) -> list[str]:
|
|
184
|
+
if value in (None, ""):
|
|
185
|
+
return []
|
|
186
|
+
if not isinstance(value, list):
|
|
187
|
+
raise SystemExit("permission bucket must be an array")
|
|
188
|
+
normalized: list[str] = []
|
|
189
|
+
for idx, item in enumerate(value):
|
|
190
|
+
if not isinstance(item, str) or not item.strip():
|
|
191
|
+
raise SystemExit(f"permission bucket item {idx} must be a non-empty string")
|
|
192
|
+
normalized.append(item.strip())
|
|
193
|
+
return normalized
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def normalize_flow_permissions(value: Any) -> Dict[str, list[str]]:
|
|
197
|
+
if value in (None, ""):
|
|
198
|
+
return {}
|
|
199
|
+
if not isinstance(value, dict):
|
|
200
|
+
raise SystemExit("flow permissions must be an object")
|
|
201
|
+
normalized: Dict[str, list[str]] = {}
|
|
202
|
+
for key, bucket in value.items():
|
|
203
|
+
if not isinstance(key, str) or not key.strip():
|
|
204
|
+
raise SystemExit("flow permission key must be a non-empty string")
|
|
205
|
+
normalized[key.strip()] = normalize_permission_bucket(bucket)
|
|
206
|
+
return normalized
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def normalize_workspace_permissions(value: Any) -> Dict[str, Dict[str, Any]]:
|
|
210
|
+
if value in (None, ""):
|
|
211
|
+
return {}
|
|
212
|
+
if not isinstance(value, dict):
|
|
213
|
+
raise SystemExit("workspace permissions must be an object")
|
|
214
|
+
normalized: Dict[str, Dict[str, Any]] = {}
|
|
215
|
+
for key, bucket in value.items():
|
|
216
|
+
if not isinstance(key, str) or not key.strip():
|
|
217
|
+
raise SystemExit("workspace permission key must be a non-empty string")
|
|
218
|
+
payload = bucket if isinstance(bucket, dict) else {}
|
|
219
|
+
normalized[key.strip()] = {
|
|
220
|
+
"system": normalize_permission_bucket(payload.get("system")),
|
|
221
|
+
"custom": normalize_permission_bucket(payload.get("custom")),
|
|
222
|
+
"flow": normalize_flow_permissions(payload.get("flow")),
|
|
223
|
+
}
|
|
224
|
+
return normalized
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def normalize_permissions(value: Any) -> Dict[str, Any]:
|
|
228
|
+
if isinstance(value, str):
|
|
229
|
+
text = value.strip()
|
|
230
|
+
value = json.loads(text) if text else {}
|
|
231
|
+
if not isinstance(value, dict):
|
|
232
|
+
value = {}
|
|
233
|
+
return {
|
|
234
|
+
"system": normalize_permission_bucket(value.get("system")),
|
|
235
|
+
"custom": normalize_permission_bucket(value.get("custom")),
|
|
236
|
+
"flow": normalize_flow_permissions(value.get("flow")),
|
|
237
|
+
"workspace": normalize_workspace_permissions(value.get("workspace")),
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def point_category_fields(detail: Dict[str, Any]) -> Dict[str, str]:
|
|
242
|
+
category = str(detail.get("category") or "").strip()
|
|
243
|
+
en_category = str(detail.get("en_category") or "").strip()
|
|
244
|
+
category_text, operation_text = "", ""
|
|
245
|
+
if category:
|
|
246
|
+
category_parts = [part.strip() for part in category.split(",", 1)]
|
|
247
|
+
category_text = category_parts[0]
|
|
248
|
+
operation_text = category_parts[1] if len(category_parts) > 1 else ""
|
|
249
|
+
en_category_text, en_operation_text = "", ""
|
|
250
|
+
if en_category:
|
|
251
|
+
en_parts = [part.strip() for part in en_category.split(",", 1)]
|
|
252
|
+
en_category_text = en_parts[0]
|
|
253
|
+
en_operation_text = en_parts[1] if len(en_parts) > 1 else ""
|
|
254
|
+
return {
|
|
255
|
+
"category": category_text,
|
|
256
|
+
"operation": operation_text,
|
|
257
|
+
"enCategory": en_category_text,
|
|
258
|
+
"enOperation": en_operation_text,
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def normalize_point_detail(detail: Dict[str, Any]) -> Dict[str, Any]:
|
|
263
|
+
payload = dict(detail)
|
|
264
|
+
category_fields = point_category_fields(payload)
|
|
265
|
+
return {
|
|
266
|
+
"id": payload.get("id"),
|
|
267
|
+
"point": payload.get("point"),
|
|
268
|
+
"name": payload.get("name"),
|
|
269
|
+
"desc": payload.get("desc") or "",
|
|
270
|
+
"category": category_fields["category"],
|
|
271
|
+
"operation": category_fields["operation"],
|
|
272
|
+
"enCategory": category_fields["enCategory"],
|
|
273
|
+
"enOperation": category_fields["enOperation"],
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def member_readback_entry(detail: Dict[str, Any]) -> Dict[str, Any]:
|
|
278
|
+
return {
|
|
279
|
+
"id": detail.get("id"),
|
|
280
|
+
"user_role_id": detail.get("user_role_id"),
|
|
281
|
+
"name": detail.get("name"),
|
|
282
|
+
"email": detail.get("email"),
|
|
283
|
+
"phone": detail.get("phone"),
|
|
284
|
+
"status": detail.get("status"),
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def build_point_payload(point: Dict[str, Any]) -> Dict[str, Any]:
|
|
289
|
+
category = str(point.get("category") or "").strip()
|
|
290
|
+
operation = str(point.get("operation") or "").strip()
|
|
291
|
+
payload = {
|
|
292
|
+
"name": point.get("name"),
|
|
293
|
+
"desc": point.get("desc") or "",
|
|
294
|
+
"point": point.get("point"),
|
|
295
|
+
"category": f"{category},{operation}" if operation else category,
|
|
296
|
+
}
|
|
297
|
+
en_category = str(point.get("enCategory") or "").strip()
|
|
298
|
+
en_operation = str(point.get("enOperation") or "").strip()
|
|
299
|
+
if en_category or en_operation:
|
|
300
|
+
payload["en_category"] = f"{en_category},{en_operation}" if en_operation else en_category
|
|
301
|
+
return payload
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def build_flow_key(flow: Dict[str, Any]) -> str:
|
|
305
|
+
flow_type = str(flow.get("flow_type") or "").strip()
|
|
306
|
+
key = str(flow.get("key") or "").strip()
|
|
307
|
+
if flow_type == "default":
|
|
308
|
+
if not key:
|
|
309
|
+
raise SystemExit("default flow permission requires non-empty flow key")
|
|
310
|
+
return f"default:{key}"
|
|
311
|
+
if not flow_type:
|
|
312
|
+
raise SystemExit("flow permission requires flow_type")
|
|
313
|
+
return f"{flow_type}:"
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def detail_to_work_payload(
|
|
317
|
+
role_detail: Dict[str, Any],
|
|
318
|
+
*,
|
|
319
|
+
workspace: str,
|
|
320
|
+
point_details: Optional[list[Dict[str, Any]]] = None,
|
|
321
|
+
member_details: Optional[list[Dict[str, Any]]] = None,
|
|
322
|
+
role_list: Optional[list[Dict[str, Any]]] = None,
|
|
323
|
+
workspace_list: Optional[list[Dict[str, Any]]] = None,
|
|
324
|
+
flow_details: Optional[list[Dict[str, Any]]] = None,
|
|
325
|
+
mode: str = "edit",
|
|
326
|
+
) -> Dict[str, Any]:
|
|
327
|
+
if mode not in ("edit", "create"):
|
|
328
|
+
raise SystemExit("mode must be edit or create")
|
|
329
|
+
points = point_details or []
|
|
330
|
+
members = member_details or []
|
|
331
|
+
roles = role_list or []
|
|
332
|
+
workspaces = workspace_list or []
|
|
333
|
+
flows = flow_details or []
|
|
334
|
+
payload = {
|
|
335
|
+
"id": role_detail.get("id") if mode == "edit" else None,
|
|
336
|
+
"mode": mode,
|
|
337
|
+
"workspace": workspace,
|
|
338
|
+
"basic": {
|
|
339
|
+
"name": role_detail.get("name") or "",
|
|
340
|
+
"key": role_detail.get("key") or "",
|
|
341
|
+
"intro": role_detail.get("intro") or "",
|
|
342
|
+
},
|
|
343
|
+
"visibleScope": normalize_visible_scope(role_detail),
|
|
344
|
+
"permissions": normalize_permissions(role_detail.get("permissions")),
|
|
345
|
+
"customPoints": {
|
|
346
|
+
"upserts": [],
|
|
347
|
+
"deletes": [],
|
|
348
|
+
},
|
|
349
|
+
"members": {
|
|
350
|
+
"addUserIds": [],
|
|
351
|
+
"removeUserRoleIds": [],
|
|
352
|
+
},
|
|
353
|
+
"preserve": {
|
|
354
|
+
"guid": role_detail.get("guid"),
|
|
355
|
+
"userCount": role_detail.get("user_count"),
|
|
356
|
+
"availablePoints": [normalize_point_detail(item) for item in points],
|
|
357
|
+
"existingMembers": [member_readback_entry(item) for item in members],
|
|
358
|
+
"availableRoles": [
|
|
359
|
+
{"id": item.get("id"), "name": item.get("name"), "key": item.get("key")}
|
|
360
|
+
for item in roles
|
|
361
|
+
],
|
|
362
|
+
"availableWorkspaces": [
|
|
363
|
+
{"id": item.get("id"), "name": item.get("name"), "key": item.get("key")}
|
|
364
|
+
for item in workspaces
|
|
365
|
+
],
|
|
366
|
+
"flows": [
|
|
367
|
+
{
|
|
368
|
+
"id": item.get("id"),
|
|
369
|
+
"name": item.get("name"),
|
|
370
|
+
"flow_type": item.get("flow_type"),
|
|
371
|
+
"key": item.get("key"),
|
|
372
|
+
"permissionKey": build_flow_key(item),
|
|
373
|
+
}
|
|
374
|
+
for item in flows
|
|
375
|
+
if isinstance(item, dict)
|
|
376
|
+
],
|
|
377
|
+
"rawVisibleScope": copy.deepcopy(role_detail.get("visible_scope")),
|
|
378
|
+
"rawPermissions": normalize_permissions(role_detail.get("permissions")),
|
|
379
|
+
},
|
|
380
|
+
"notes": "",
|
|
381
|
+
}
|
|
382
|
+
if mode == "create":
|
|
383
|
+
payload["permissions"] = copy.deepcopy(DEFAULT_PERMISSIONS)
|
|
384
|
+
payload["preserve"]["existingMembers"] = []
|
|
385
|
+
return payload
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def build_create_seed_detail(*, name: str = "", key: str = "", intro: str = "") -> Dict[str, Any]:
|
|
389
|
+
return {
|
|
390
|
+
"id": None,
|
|
391
|
+
"name": name,
|
|
392
|
+
"key": key,
|
|
393
|
+
"intro": intro,
|
|
394
|
+
"visible_scope": {"value": "team.self", "config": {"role": [], "user": [], "group": []}},
|
|
395
|
+
"permissions": copy.deepcopy(DEFAULT_PERMISSIONS),
|
|
396
|
+
"guid": None,
|
|
397
|
+
"user_count": 0,
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def build_create_work_payload(
|
|
402
|
+
*,
|
|
403
|
+
workspace: str,
|
|
404
|
+
name: str = "",
|
|
405
|
+
key: str = "",
|
|
406
|
+
intro: str = "",
|
|
407
|
+
point_details: Optional[list[Dict[str, Any]]] = None,
|
|
408
|
+
role_list: Optional[list[Dict[str, Any]]] = None,
|
|
409
|
+
workspace_list: Optional[list[Dict[str, Any]]] = None,
|
|
410
|
+
flow_details: Optional[list[Dict[str, Any]]] = None,
|
|
411
|
+
) -> Dict[str, Any]:
|
|
412
|
+
seed = build_create_seed_detail(name=name, key=key, intro=intro)
|
|
413
|
+
return detail_to_work_payload(
|
|
414
|
+
seed,
|
|
415
|
+
workspace=workspace,
|
|
416
|
+
point_details=point_details,
|
|
417
|
+
role_list=role_list,
|
|
418
|
+
workspace_list=workspace_list,
|
|
419
|
+
flow_details=flow_details,
|
|
420
|
+
mode="create",
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def collect_permission_strings(permissions: Dict[str, Any]) -> set[str]:
|
|
425
|
+
normalized = normalize_permissions(permissions)
|
|
426
|
+
values = set(normalized["system"]) | set(normalized["custom"])
|
|
427
|
+
for bucket in normalized["flow"].values():
|
|
428
|
+
values.update(bucket)
|
|
429
|
+
for bucket in normalized["workspace"].values():
|
|
430
|
+
values.update(bucket["system"])
|
|
431
|
+
values.update(bucket["custom"])
|
|
432
|
+
for flow_values in bucket["flow"].values():
|
|
433
|
+
values.update(flow_values)
|
|
434
|
+
return values
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def collect_custom_point_references(permissions: Dict[str, Any]) -> set[str]:
|
|
438
|
+
normalized = normalize_permissions(permissions)
|
|
439
|
+
values = set(normalized["custom"])
|
|
440
|
+
for bucket in normalized["workspace"].values():
|
|
441
|
+
values.update(bucket["custom"])
|
|
442
|
+
return values
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _validate_permission_shape(permissions: Dict[str, Any], errors: list[str], warnings: list[str], checks: Dict[str, Any]) -> None:
|
|
446
|
+
normalized = normalize_permissions(permissions)
|
|
447
|
+
checks["systemPermissionCount"] = len(normalized["system"])
|
|
448
|
+
checks["customPermissionCount"] = len(normalized["custom"])
|
|
449
|
+
checks["flowPermissionCount"] = len(normalized["flow"])
|
|
450
|
+
checks["workspacePermissionCount"] = len(normalized["workspace"])
|
|
451
|
+
all_refs = collect_permission_strings(normalized)
|
|
452
|
+
checks["permissionStrings"] = sorted(all_refs)
|
|
453
|
+
flow_keys = sorted(normalized["flow"].keys())
|
|
454
|
+
checks["flowKeys"] = flow_keys
|
|
455
|
+
workspace_keys = sorted(normalized["workspace"].keys())
|
|
456
|
+
checks["workspaceKeys"] = workspace_keys
|
|
457
|
+
for key in flow_keys:
|
|
458
|
+
if key.startswith("default:"):
|
|
459
|
+
if len(key) <= len("default:"):
|
|
460
|
+
errors.append("default flow permission key must include a non-empty flow key")
|
|
461
|
+
elif not key.endswith(":"):
|
|
462
|
+
errors.append(f"invalid flow permission key: {key}")
|
|
463
|
+
for workspace_key, bucket in normalized["workspace"].items():
|
|
464
|
+
if not ROLE_KEY_PATTERN.match(workspace_key):
|
|
465
|
+
warnings.append(f"workspace key looks unusual: {workspace_key}")
|
|
466
|
+
for flow_key in bucket["flow"].keys():
|
|
467
|
+
if flow_key.startswith("default:"):
|
|
468
|
+
if len(flow_key) <= len("default:"):
|
|
469
|
+
errors.append(f"workspace {workspace_key} contains invalid default flow key")
|
|
470
|
+
elif not flow_key.endswith(":"):
|
|
471
|
+
errors.append(f"workspace {workspace_key} contains invalid flow key: {flow_key}")
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def lint_work_payload(work: Dict[str, Any], *, raw_payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
475
|
+
report: Dict[str, Any] = {"ok": True, "errors": [], "warnings": [], "checks": {}}
|
|
476
|
+
if work.get("mode") not in ("edit", "create"):
|
|
477
|
+
report["errors"].append("mode must be edit or create")
|
|
478
|
+
basic = work.get("basic")
|
|
479
|
+
if not isinstance(basic, dict):
|
|
480
|
+
report["errors"].append("basic must be an object")
|
|
481
|
+
basic = {}
|
|
482
|
+
for key in ("name", "key", "intro"):
|
|
483
|
+
value = basic.get(key)
|
|
484
|
+
if not isinstance(value, str) or not value.strip():
|
|
485
|
+
report["errors"].append(f"basic.{key} must be a non-empty string")
|
|
486
|
+
role_key = str(basic.get("key") or "").strip()
|
|
487
|
+
if role_key and not ROLE_KEY_PATTERN.match(role_key):
|
|
488
|
+
report["errors"].append("basic.key must start with a letter and contain only letters, numbers, _, :, -")
|
|
489
|
+
|
|
490
|
+
visible_scope = work.get("visibleScope")
|
|
491
|
+
if not isinstance(visible_scope, dict):
|
|
492
|
+
report["errors"].append("visibleScope must be an object")
|
|
493
|
+
visible_scope = {}
|
|
494
|
+
else:
|
|
495
|
+
mode = visible_scope.get("mode")
|
|
496
|
+
if mode not in ("all", "self", "custom"):
|
|
497
|
+
report["errors"].append("visibleScope.mode must be all, self, or custom")
|
|
498
|
+
config = visible_scope.get("config")
|
|
499
|
+
if not isinstance(config, dict):
|
|
500
|
+
report["errors"].append("visibleScope.config must be an object")
|
|
501
|
+
elif mode == "custom":
|
|
502
|
+
has_selected = False
|
|
503
|
+
for bucket_name in ("user", "group", "role"):
|
|
504
|
+
bucket = config.get(bucket_name)
|
|
505
|
+
if bucket not in (None, "") and not isinstance(bucket, list):
|
|
506
|
+
report["errors"].append(f"visibleScope.config.{bucket_name} must be an array")
|
|
507
|
+
continue
|
|
508
|
+
if bucket:
|
|
509
|
+
has_selected = True
|
|
510
|
+
if not has_selected:
|
|
511
|
+
report["errors"].append("visibleScope.mode=custom requires at least one selected user, group, or role")
|
|
512
|
+
|
|
513
|
+
try:
|
|
514
|
+
permissions = normalize_permissions(work.get("permissions"))
|
|
515
|
+
except SystemExit as exc:
|
|
516
|
+
report["errors"].append(str(exc))
|
|
517
|
+
permissions = copy.deepcopy(DEFAULT_PERMISSIONS)
|
|
518
|
+
_validate_permission_shape(permissions, report["errors"], report["warnings"], report["checks"])
|
|
519
|
+
|
|
520
|
+
custom_points = work.get("customPoints")
|
|
521
|
+
if not isinstance(custom_points, dict):
|
|
522
|
+
report["errors"].append("customPoints must be an object")
|
|
523
|
+
custom_points = {"upserts": [], "deletes": []}
|
|
524
|
+
upserts = custom_points.get("upserts")
|
|
525
|
+
deletes = custom_points.get("deletes")
|
|
526
|
+
if not isinstance(upserts, list):
|
|
527
|
+
report["errors"].append("customPoints.upserts must be an array")
|
|
528
|
+
upserts = []
|
|
529
|
+
if not isinstance(deletes, list):
|
|
530
|
+
report["errors"].append("customPoints.deletes must be an array")
|
|
531
|
+
deletes = []
|
|
532
|
+
deleted_ids: list[int] = []
|
|
533
|
+
try:
|
|
534
|
+
deleted_ids = normalize_id_list(deletes)
|
|
535
|
+
except SystemExit as exc:
|
|
536
|
+
report["errors"].append(str(exc))
|
|
537
|
+
point_ids: set[int] = set()
|
|
538
|
+
point_names: set[str] = set()
|
|
539
|
+
point_keys: set[str] = set()
|
|
540
|
+
point_name_to_id: Dict[str, int] = {}
|
|
541
|
+
for idx, point in enumerate(upserts):
|
|
542
|
+
if not isinstance(point, dict):
|
|
543
|
+
report["errors"].append(f"customPoints.upserts[{idx}] must be an object")
|
|
544
|
+
continue
|
|
545
|
+
point_name = str(point.get("name") or "").strip()
|
|
546
|
+
point_key = str(point.get("point") or "").strip()
|
|
547
|
+
category = str(point.get("category") or "").strip()
|
|
548
|
+
if not point_name:
|
|
549
|
+
report["errors"].append(f"customPoints.upserts[{idx}].name must be non-empty")
|
|
550
|
+
if not point_key:
|
|
551
|
+
report["errors"].append(f"customPoints.upserts[{idx}].point must be non-empty")
|
|
552
|
+
if not category:
|
|
553
|
+
report["errors"].append(f"customPoints.upserts[{idx}].category must be non-empty")
|
|
554
|
+
point_id = point.get("id")
|
|
555
|
+
if point_id not in (None, ""):
|
|
556
|
+
try:
|
|
557
|
+
normalized_id = normalize_id_list([point_id])[0]
|
|
558
|
+
except SystemExit as exc:
|
|
559
|
+
report["errors"].append(str(exc))
|
|
560
|
+
normalized_id = None
|
|
561
|
+
if normalized_id is not None:
|
|
562
|
+
if normalized_id in point_ids:
|
|
563
|
+
report["errors"].append(f"customPoints.upserts[{idx}] duplicates point id {normalized_id}")
|
|
564
|
+
point_ids.add(normalized_id)
|
|
565
|
+
point_name_to_id[point_key] = normalized_id
|
|
566
|
+
if point_key in point_keys:
|
|
567
|
+
report["errors"].append(f"customPoints.upserts[{idx}] duplicates point value {point_key}")
|
|
568
|
+
point_keys.add(point_key)
|
|
569
|
+
if point_name in point_names:
|
|
570
|
+
report["warnings"].append(f"customPoints.upserts[{idx}] duplicates point name {point_name}")
|
|
571
|
+
point_names.add(point_name)
|
|
572
|
+
referenced_points = collect_custom_point_references(permissions)
|
|
573
|
+
deleted_refs = []
|
|
574
|
+
if raw_payload and isinstance(raw_payload, dict):
|
|
575
|
+
preserve = raw_payload.get("preserve") if isinstance(raw_payload.get("preserve"), dict) else {}
|
|
576
|
+
available_points = preserve.get("availablePoints") if isinstance(preserve.get("availablePoints"), list) else []
|
|
577
|
+
point_name_to_id.update(
|
|
578
|
+
{
|
|
579
|
+
str(item.get("point")): int(item["id"])
|
|
580
|
+
for item in available_points
|
|
581
|
+
if isinstance(item, dict) and item.get("id") not in (None, "") and str(item.get("point") or "").strip()
|
|
582
|
+
}
|
|
583
|
+
)
|
|
584
|
+
for point_name in referenced_points:
|
|
585
|
+
point_id = point_name_to_id.get(point_name)
|
|
586
|
+
if point_id in deleted_ids:
|
|
587
|
+
deleted_refs.append(point_name)
|
|
588
|
+
if deleted_refs:
|
|
589
|
+
report["errors"].append(
|
|
590
|
+
"customPoints.deletes cannot delete points still referenced by permissions.custom: "
|
|
591
|
+
+ ", ".join(sorted(deleted_refs))
|
|
592
|
+
)
|
|
593
|
+
|
|
594
|
+
members = work.get("members")
|
|
595
|
+
if not isinstance(members, dict):
|
|
596
|
+
report["errors"].append("members must be an object")
|
|
597
|
+
members = {"addUserIds": [], "removeUserRoleIds": []}
|
|
598
|
+
add_user_ids: list[int] = []
|
|
599
|
+
remove_user_role_ids: list[int] = []
|
|
600
|
+
try:
|
|
601
|
+
add_user_ids = normalize_id_list(members.get("addUserIds"))
|
|
602
|
+
except SystemExit as exc:
|
|
603
|
+
report["errors"].append(f"members.addUserIds: {exc}")
|
|
604
|
+
try:
|
|
605
|
+
remove_user_role_ids = normalize_id_list(members.get("removeUserRoleIds"))
|
|
606
|
+
except SystemExit as exc:
|
|
607
|
+
report["errors"].append(f"members.removeUserRoleIds: {exc}")
|
|
608
|
+
if len(add_user_ids) != len(set(add_user_ids)):
|
|
609
|
+
report["errors"].append("members.addUserIds contains duplicate ids")
|
|
610
|
+
if len(remove_user_role_ids) != len(set(remove_user_role_ids)):
|
|
611
|
+
report["errors"].append("members.removeUserRoleIds contains duplicate ids")
|
|
612
|
+
overlap = set(add_user_ids) & set(remove_user_role_ids)
|
|
613
|
+
if overlap:
|
|
614
|
+
report["errors"].append(
|
|
615
|
+
"members.addUserIds and members.removeUserRoleIds cannot overlap: "
|
|
616
|
+
+ ", ".join(str(item) for item in sorted(overlap))
|
|
617
|
+
)
|
|
618
|
+
report["checks"]["memberAdds"] = add_user_ids
|
|
619
|
+
report["checks"]["memberRemoves"] = remove_user_role_ids
|
|
620
|
+
|
|
621
|
+
report["ok"] = not report["errors"]
|
|
622
|
+
return report
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def build_submit_payload(work: Dict[str, Any]) -> Dict[str, Any]:
|
|
626
|
+
lint = lint_work_payload(work, raw_payload=work)
|
|
627
|
+
if lint["errors"]:
|
|
628
|
+
raise SystemExit("invalid work payload: " + "; ".join(lint["errors"]))
|
|
629
|
+
visible_scope = build_visible_scope_payload(work["visibleScope"])
|
|
630
|
+
permissions = normalize_permissions(work["permissions"])
|
|
631
|
+
role_body = {
|
|
632
|
+
"name": work["basic"]["name"].strip(),
|
|
633
|
+
"key": work["basic"]["key"].strip(),
|
|
634
|
+
"intro": work["basic"]["intro"].strip(),
|
|
635
|
+
"visible_scope": json.dumps(visible_scope, ensure_ascii=False),
|
|
636
|
+
"permissions": json.dumps(permissions, ensure_ascii=False),
|
|
637
|
+
}
|
|
638
|
+
role_id = work.get("id")
|
|
639
|
+
role_op = {
|
|
640
|
+
"method": "POST" if work.get("mode") == "create" else "PUT",
|
|
641
|
+
"path": "/role" if work.get("mode") == "create" else f"/role/{role_id}",
|
|
642
|
+
"body": role_body,
|
|
643
|
+
}
|
|
644
|
+
point_ops = []
|
|
645
|
+
for point_id in normalize_id_list(work["customPoints"].get("deletes")):
|
|
646
|
+
point_ops.append({"method": "DELETE", "path": f"/point/{point_id}", "body": None, "id": point_id})
|
|
647
|
+
for point in work["customPoints"].get("upserts", []):
|
|
648
|
+
payload = build_point_payload(point)
|
|
649
|
+
point_id = point.get("id")
|
|
650
|
+
if point_id not in (None, ""):
|
|
651
|
+
normalized_id = normalize_id_list([point_id])[0]
|
|
652
|
+
point_ops.append({"method": "PUT", "path": f"/point/{normalized_id}", "body": payload, "id": normalized_id})
|
|
653
|
+
else:
|
|
654
|
+
point_ops.append({"method": "POST", "path": "/point", "body": payload, "id": None})
|
|
655
|
+
|
|
656
|
+
member_ops = []
|
|
657
|
+
for user_id in normalize_id_list(work["members"].get("addUserIds")):
|
|
658
|
+
member_ops.append({"method": "POST", "path": "/user_role", "body": {"usersId": [user_id]}, "userId": user_id})
|
|
659
|
+
for user_role_id in normalize_id_list(work["members"].get("removeUserRoleIds")):
|
|
660
|
+
member_ops.append({"method": "DELETE", "path": f"/user_role/{user_role_id}", "body": None, "user_role_id": user_role_id})
|
|
661
|
+
|
|
662
|
+
preserve = work.get("preserve") if isinstance(work.get("preserve"), dict) else {}
|
|
663
|
+
verify = {
|
|
664
|
+
"roleLookup": {
|
|
665
|
+
"id": role_id if work.get("mode") == "edit" else None,
|
|
666
|
+
"key": role_body["key"],
|
|
667
|
+
"name": role_body["name"],
|
|
668
|
+
},
|
|
669
|
+
"expectedVisibleScope": visible_scope,
|
|
670
|
+
"expectedPermissions": permissions,
|
|
671
|
+
"expectedPointDeletes": normalize_id_list(work["customPoints"].get("deletes")),
|
|
672
|
+
"expectedPointUpserts": [build_point_payload(item) for item in work["customPoints"].get("upserts", [])],
|
|
673
|
+
"expectedMemberAdds": normalize_id_list(work["members"].get("addUserIds")),
|
|
674
|
+
"expectedMemberRemoves": normalize_id_list(work["members"].get("removeUserRoleIds")),
|
|
675
|
+
"existingMembers": preserve.get("existingMembers") if isinstance(preserve.get("existingMembers"), list) else [],
|
|
676
|
+
}
|
|
677
|
+
return {
|
|
678
|
+
"role": role_op,
|
|
679
|
+
"pointOps": point_ops,
|
|
680
|
+
"memberOps": member_ops,
|
|
681
|
+
"verify": verify,
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def _normalize_role_readback(detail: Dict[str, Any]) -> Dict[str, Any]:
|
|
686
|
+
return {
|
|
687
|
+
"id": detail.get("id"),
|
|
688
|
+
"basic": {
|
|
689
|
+
"name": detail.get("name") or "",
|
|
690
|
+
"key": detail.get("key") or "",
|
|
691
|
+
"intro": detail.get("intro") or "",
|
|
692
|
+
},
|
|
693
|
+
"visibleScope": build_visible_scope_payload(normalize_visible_scope(detail)),
|
|
694
|
+
"permissions": normalize_permissions(detail.get("permissions")),
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def summarize_verification(
|
|
699
|
+
submit_payload: Dict[str, Any],
|
|
700
|
+
role_readback: Dict[str, Any],
|
|
701
|
+
*,
|
|
702
|
+
point_readback: Optional[list[Dict[str, Any]]] = None,
|
|
703
|
+
member_readback: Optional[list[Dict[str, Any]]] = None,
|
|
704
|
+
) -> Dict[str, Any]:
|
|
705
|
+
role_expected = submit_payload["role"]["body"]
|
|
706
|
+
expected_visible_scope = json.loads(role_expected["visible_scope"])
|
|
707
|
+
expected_permissions = json.loads(role_expected["permissions"])
|
|
708
|
+
actual = _normalize_role_readback(role_readback)
|
|
709
|
+
checks: Dict[str, Any] = {
|
|
710
|
+
"name": {
|
|
711
|
+
"match": role_expected["name"] == actual["basic"]["name"],
|
|
712
|
+
"expected": role_expected["name"],
|
|
713
|
+
"actual": actual["basic"]["name"],
|
|
714
|
+
},
|
|
715
|
+
"key": {
|
|
716
|
+
"match": role_expected["key"] == actual["basic"]["key"],
|
|
717
|
+
"expected": role_expected["key"],
|
|
718
|
+
"actual": actual["basic"]["key"],
|
|
719
|
+
},
|
|
720
|
+
"intro": {
|
|
721
|
+
"match": role_expected["intro"] == actual["basic"]["intro"],
|
|
722
|
+
"expected": role_expected["intro"],
|
|
723
|
+
"actual": actual["basic"]["intro"],
|
|
724
|
+
},
|
|
725
|
+
"visible_scope": {
|
|
726
|
+
"match": expected_visible_scope == actual["visibleScope"],
|
|
727
|
+
"expected": expected_visible_scope,
|
|
728
|
+
"actual": actual["visibleScope"],
|
|
729
|
+
},
|
|
730
|
+
"permissions": {
|
|
731
|
+
"match": expected_permissions == actual["permissions"],
|
|
732
|
+
"expected": expected_permissions,
|
|
733
|
+
"actual": actual["permissions"],
|
|
734
|
+
},
|
|
735
|
+
}
|
|
736
|
+
point_checks = []
|
|
737
|
+
read_points = {
|
|
738
|
+
str(item.get("point")): normalize_point_detail(item)
|
|
739
|
+
for item in (point_readback or [])
|
|
740
|
+
if isinstance(item, dict) and str(item.get("point") or "").strip()
|
|
741
|
+
}
|
|
742
|
+
for op in submit_payload.get("pointOps", []):
|
|
743
|
+
if op["method"] == "DELETE":
|
|
744
|
+
deleted_id = op.get("id")
|
|
745
|
+
exists = any(item.get("id") == deleted_id for item in (point_readback or []))
|
|
746
|
+
point_checks.append(
|
|
747
|
+
{
|
|
748
|
+
"kind": "delete",
|
|
749
|
+
"id": deleted_id,
|
|
750
|
+
"match": not exists,
|
|
751
|
+
"expected": "deleted",
|
|
752
|
+
"actual": "present" if exists else "deleted",
|
|
753
|
+
}
|
|
754
|
+
)
|
|
755
|
+
else:
|
|
756
|
+
body = op["body"] or {}
|
|
757
|
+
point_key = str(body.get("point") or "")
|
|
758
|
+
actual = read_points.get(point_key)
|
|
759
|
+
expected_category = point_category_fields(body)
|
|
760
|
+
expected = {
|
|
761
|
+
"point": point_key,
|
|
762
|
+
"name": body.get("name"),
|
|
763
|
+
"desc": body.get("desc") or "",
|
|
764
|
+
"category": expected_category["category"],
|
|
765
|
+
"operation": expected_category["operation"],
|
|
766
|
+
"enCategory": expected_category["enCategory"],
|
|
767
|
+
"enOperation": expected_category["enOperation"],
|
|
768
|
+
}
|
|
769
|
+
point_checks.append(
|
|
770
|
+
{
|
|
771
|
+
"kind": "upsert",
|
|
772
|
+
"point": point_key,
|
|
773
|
+
"match": bool(
|
|
774
|
+
actual
|
|
775
|
+
and actual["name"] == expected["name"]
|
|
776
|
+
and actual["desc"] == expected["desc"]
|
|
777
|
+
and actual["category"] == expected["category"]
|
|
778
|
+
and actual["operation"] == expected["operation"]
|
|
779
|
+
and actual["enCategory"] == expected["enCategory"]
|
|
780
|
+
and actual["enOperation"] == expected["enOperation"]
|
|
781
|
+
),
|
|
782
|
+
"expected": expected,
|
|
783
|
+
"actual": actual,
|
|
784
|
+
}
|
|
785
|
+
)
|
|
786
|
+
|
|
787
|
+
member_checks = []
|
|
788
|
+
member_items = member_readback or []
|
|
789
|
+
user_ids_present = {item.get("id") for item in member_items if isinstance(item, dict)}
|
|
790
|
+
user_role_ids_present = {item.get("user_role_id") for item in member_items if isinstance(item, dict)}
|
|
791
|
+
for op in submit_payload.get("memberOps", []):
|
|
792
|
+
if op["method"] == "POST":
|
|
793
|
+
user_id = op.get("userId")
|
|
794
|
+
member_checks.append(
|
|
795
|
+
{
|
|
796
|
+
"kind": "add",
|
|
797
|
+
"userId": user_id,
|
|
798
|
+
"match": user_id in user_ids_present,
|
|
799
|
+
"expected": "present",
|
|
800
|
+
"actual": "present" if user_id in user_ids_present else "missing",
|
|
801
|
+
}
|
|
802
|
+
)
|
|
803
|
+
else:
|
|
804
|
+
user_role_id = op.get("user_role_id")
|
|
805
|
+
member_checks.append(
|
|
806
|
+
{
|
|
807
|
+
"kind": "remove",
|
|
808
|
+
"user_role_id": user_role_id,
|
|
809
|
+
"match": user_role_id not in user_role_ids_present,
|
|
810
|
+
"expected": "deleted",
|
|
811
|
+
"actual": "present" if user_role_id in user_role_ids_present else "deleted",
|
|
812
|
+
}
|
|
813
|
+
)
|
|
814
|
+
checks["customPoints"] = {"match": all(item["match"] for item in point_checks), "details": point_checks}
|
|
815
|
+
checks["members"] = {"match": all(item["match"] for item in member_checks), "details": member_checks}
|
|
816
|
+
return {"ok": all(item["match"] for item in checks.values()), "checks": checks}
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
def build_drift_report(
|
|
820
|
+
submit_payload: Dict[str, Any],
|
|
821
|
+
role_readback: Dict[str, Any],
|
|
822
|
+
*,
|
|
823
|
+
point_readback: Optional[list[Dict[str, Any]]] = None,
|
|
824
|
+
member_readback: Optional[list[Dict[str, Any]]] = None,
|
|
825
|
+
) -> Dict[str, Any]:
|
|
826
|
+
verification = summarize_verification(
|
|
827
|
+
submit_payload,
|
|
828
|
+
role_readback,
|
|
829
|
+
point_readback=point_readback,
|
|
830
|
+
member_readback=member_readback,
|
|
831
|
+
)
|
|
832
|
+
changes = {key: value for key, value in verification["checks"].items() if not value["match"]}
|
|
833
|
+
return {"ok": not changes, "submitToReadback": {"ok": not changes, "changes": changes}}
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def write_export_meta(
|
|
837
|
+
path: Path,
|
|
838
|
+
*,
|
|
839
|
+
stem: str,
|
|
840
|
+
mode: str,
|
|
841
|
+
workspace: str,
|
|
842
|
+
role_id: int | None,
|
|
843
|
+
request_url: str,
|
|
844
|
+
raw_path: Path,
|
|
845
|
+
work_path: Path,
|
|
846
|
+
) -> Dict[str, Any]:
|
|
847
|
+
payload = ensure_meta_shape(load_meta(path), stem)
|
|
848
|
+
payload.update(
|
|
849
|
+
{
|
|
850
|
+
"mode": mode,
|
|
851
|
+
"workspace": workspace,
|
|
852
|
+
"roleId": role_id,
|
|
853
|
+
"requestUrl": request_url,
|
|
854
|
+
"rawSha256": file_sha256(raw_path),
|
|
855
|
+
"workSha256": file_sha256(work_path),
|
|
856
|
+
"submitSha256": None,
|
|
857
|
+
"lintSha256": None,
|
|
858
|
+
"lintWorkSha256": None,
|
|
859
|
+
"lintSubmitSha256": None,
|
|
860
|
+
"lintCheckedAt": None,
|
|
861
|
+
"lintOk": None,
|
|
862
|
+
"exportedAt": utc_now_iso(),
|
|
863
|
+
"submitBuiltAt": None,
|
|
864
|
+
"workConfirmedAt": None,
|
|
865
|
+
"workConfirmedBy": None,
|
|
866
|
+
"submitConfirmedAt": None,
|
|
867
|
+
"submitConfirmedBy": None,
|
|
868
|
+
"submittedAt": None,
|
|
869
|
+
"status": "exported",
|
|
870
|
+
}
|
|
871
|
+
)
|
|
872
|
+
save_meta(path, payload)
|
|
873
|
+
return payload
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def update_confirmation_state(
|
|
877
|
+
meta_path: Path,
|
|
878
|
+
*,
|
|
879
|
+
stem: str,
|
|
880
|
+
actor: str,
|
|
881
|
+
stage: str,
|
|
882
|
+
work_path: Path,
|
|
883
|
+
submit_path: Optional[Path] = None,
|
|
884
|
+
) -> Dict[str, Any]:
|
|
885
|
+
payload = ensure_meta_shape(load_meta(meta_path), stem)
|
|
886
|
+
payload["workSha256"] = file_sha256(work_path)
|
|
887
|
+
now = utc_now_iso()
|
|
888
|
+
if stage == "work":
|
|
889
|
+
payload["workConfirmedAt"] = now
|
|
890
|
+
payload["workConfirmedBy"] = actor
|
|
891
|
+
payload["submitConfirmedAt"] = None
|
|
892
|
+
payload["submitConfirmedBy"] = None
|
|
893
|
+
payload["submitSha256"] = None
|
|
894
|
+
payload["submitBuiltAt"] = None
|
|
895
|
+
payload["lintSha256"] = None
|
|
896
|
+
payload["lintWorkSha256"] = None
|
|
897
|
+
payload["lintSubmitSha256"] = None
|
|
898
|
+
payload["lintCheckedAt"] = None
|
|
899
|
+
payload["lintOk"] = None
|
|
900
|
+
payload["submittedAt"] = None
|
|
901
|
+
payload["status"] = "work_confirmed"
|
|
902
|
+
elif stage == "submit":
|
|
903
|
+
if submit_path is None or not submit_path.exists():
|
|
904
|
+
raise SystemExit("submit confirmation requires existing submit file")
|
|
905
|
+
if payload.get("status") != "lint_passed":
|
|
906
|
+
raise SystemExit("submit confirmation requires lint_passed status")
|
|
907
|
+
if payload.get("workSha256") != file_sha256(work_path):
|
|
908
|
+
raise SystemExit("work file changed after confirmation; reconfirm work before submit")
|
|
909
|
+
current_submit_sha = file_sha256(submit_path)
|
|
910
|
+
if payload.get("submitSha256") != current_submit_sha:
|
|
911
|
+
raise SystemExit("submit file changed after lint; rerun lint before submit confirmation")
|
|
912
|
+
if payload.get("lintSubmitSha256") != current_submit_sha or payload.get("lintWorkSha256") != file_sha256(work_path):
|
|
913
|
+
raise SystemExit("lint result is stale; rerun lint before submit confirmation")
|
|
914
|
+
payload["submitConfirmedAt"] = now
|
|
915
|
+
payload["submitConfirmedBy"] = actor
|
|
916
|
+
payload["status"] = "submit_confirmed"
|
|
917
|
+
else:
|
|
918
|
+
raise SystemExit(f"unsupported confirmation stage: {stage}")
|
|
919
|
+
save_meta(meta_path, payload)
|
|
920
|
+
return payload
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def ensure_build_allowed(meta_path: Path, work_path: Path) -> Dict[str, Any]:
|
|
924
|
+
if not meta_path.exists():
|
|
925
|
+
raise SystemExit("missing meta confirmation file")
|
|
926
|
+
raw_meta = load_meta(meta_path)
|
|
927
|
+
meta = ensure_meta_shape(raw_meta, raw_meta.get("stem", "unknown"))
|
|
928
|
+
if meta.get("status") != "work_confirmed":
|
|
929
|
+
raise SystemExit("build blocked: work file is not confirmed")
|
|
930
|
+
if meta.get("workSha256") != file_sha256(work_path):
|
|
931
|
+
raise SystemExit("build blocked: work file changed after confirmation")
|
|
932
|
+
return meta
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def update_build_meta(meta_path: Path, *, stem: str, work_path: Path, submit_path: Path) -> Dict[str, Any]:
|
|
936
|
+
payload = ensure_meta_shape(load_meta(meta_path), stem)
|
|
937
|
+
previous_work_sha = payload.get("workSha256")
|
|
938
|
+
current_work_sha = file_sha256(work_path)
|
|
939
|
+
if payload.get("workConfirmedAt") and previous_work_sha != current_work_sha:
|
|
940
|
+
payload["workConfirmedAt"] = None
|
|
941
|
+
payload["workConfirmedBy"] = None
|
|
942
|
+
payload["workSha256"] = current_work_sha
|
|
943
|
+
payload["submitSha256"] = file_sha256(submit_path)
|
|
944
|
+
payload["submitBuiltAt"] = utc_now_iso()
|
|
945
|
+
payload["submitConfirmedAt"] = None
|
|
946
|
+
payload["submitConfirmedBy"] = None
|
|
947
|
+
payload["lintSha256"] = None
|
|
948
|
+
payload["lintWorkSha256"] = None
|
|
949
|
+
payload["lintSubmitSha256"] = None
|
|
950
|
+
payload["lintCheckedAt"] = None
|
|
951
|
+
payload["lintOk"] = None
|
|
952
|
+
payload["submittedAt"] = None
|
|
953
|
+
payload["status"] = "submit_built"
|
|
954
|
+
save_meta(meta_path, payload)
|
|
955
|
+
return payload
|
|
956
|
+
|
|
957
|
+
|
|
958
|
+
def ensure_lint_allowed(meta_path: Path, work_path: Path, submit_path: Path) -> Dict[str, Any]:
|
|
959
|
+
if not meta_path.exists():
|
|
960
|
+
raise SystemExit("missing meta confirmation file")
|
|
961
|
+
raw_meta = load_meta(meta_path)
|
|
962
|
+
meta = ensure_meta_shape(raw_meta, raw_meta.get("stem", "unknown"))
|
|
963
|
+
if meta.get("status") != "submit_built":
|
|
964
|
+
raise SystemExit("lint blocked: submit payload is not built")
|
|
965
|
+
if meta.get("workSha256") != file_sha256(work_path):
|
|
966
|
+
raise SystemExit("lint blocked: work file changed after build")
|
|
967
|
+
if meta.get("submitSha256") != file_sha256(submit_path):
|
|
968
|
+
raise SystemExit("lint blocked: submit file changed after build")
|
|
969
|
+
return meta
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def update_lint_meta(
|
|
973
|
+
meta_path: Path,
|
|
974
|
+
*,
|
|
975
|
+
stem: str,
|
|
976
|
+
work_path: Path,
|
|
977
|
+
submit_path: Path,
|
|
978
|
+
lint_path: Path,
|
|
979
|
+
lint_report: Dict[str, Any],
|
|
980
|
+
) -> Dict[str, Any]:
|
|
981
|
+
payload = ensure_meta_shape(load_meta(meta_path), stem)
|
|
982
|
+
payload["workSha256"] = file_sha256(work_path)
|
|
983
|
+
payload["submitSha256"] = file_sha256(submit_path)
|
|
984
|
+
payload["lintSha256"] = file_sha256(lint_path)
|
|
985
|
+
payload["lintWorkSha256"] = payload["workSha256"]
|
|
986
|
+
payload["lintSubmitSha256"] = payload["submitSha256"]
|
|
987
|
+
payload["lintCheckedAt"] = utc_now_iso()
|
|
988
|
+
payload["lintOk"] = bool(lint_report.get("ok"))
|
|
989
|
+
payload["submitConfirmedAt"] = None
|
|
990
|
+
payload["submitConfirmedBy"] = None
|
|
991
|
+
payload["status"] = "lint_passed" if lint_report.get("ok") else "lint_failed"
|
|
992
|
+
save_meta(meta_path, payload)
|
|
993
|
+
return payload
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def ensure_submission_allowed(meta_path: Path, work_path: Path, submit_path: Path, raw_path: Path, lint_path: Path) -> Dict[str, Any]:
|
|
997
|
+
if not meta_path.exists():
|
|
998
|
+
raise SystemExit("missing meta confirmation file")
|
|
999
|
+
raw_meta = load_meta(meta_path)
|
|
1000
|
+
meta = ensure_meta_shape(raw_meta, raw_meta.get("stem", "unknown"))
|
|
1001
|
+
required = (
|
|
1002
|
+
"mode",
|
|
1003
|
+
"workspace",
|
|
1004
|
+
"workSha256",
|
|
1005
|
+
"submitSha256",
|
|
1006
|
+
"workConfirmedAt",
|
|
1007
|
+
"submitConfirmedAt",
|
|
1008
|
+
"status",
|
|
1009
|
+
"lintCheckedAt",
|
|
1010
|
+
)
|
|
1011
|
+
missing = [key for key in required if not meta.get(key)]
|
|
1012
|
+
if missing:
|
|
1013
|
+
raise SystemExit(f"meta confirmation incomplete: missing {', '.join(missing)}")
|
|
1014
|
+
if meta.get("status") != "submit_confirmed":
|
|
1015
|
+
raise SystemExit("submission blocked: current status is not submit_confirmed")
|
|
1016
|
+
current_work_sha = file_sha256(work_path)
|
|
1017
|
+
current_submit_sha = file_sha256(submit_path)
|
|
1018
|
+
if meta.get("workSha256") != current_work_sha:
|
|
1019
|
+
raise SystemExit("submission blocked: work file changed after confirmation")
|
|
1020
|
+
if meta.get("submitSha256") != current_submit_sha:
|
|
1021
|
+
raise SystemExit("submission blocked: submit file changed after confirmation")
|
|
1022
|
+
if meta.get("lintOk") is not True:
|
|
1023
|
+
raise SystemExit("submission blocked: lint did not pass")
|
|
1024
|
+
if meta.get("lintWorkSha256") != current_work_sha or meta.get("lintSubmitSha256") != current_submit_sha:
|
|
1025
|
+
raise SystemExit("submission blocked: lint result is stale")
|
|
1026
|
+
if not lint_path.exists():
|
|
1027
|
+
raise SystemExit("submission blocked: missing lint result file")
|
|
1028
|
+
submit_built_at = meta.get("submitBuiltAt")
|
|
1029
|
+
lint_checked_at = meta.get("lintCheckedAt")
|
|
1030
|
+
if submit_built_at and lint_checked_at and lint_checked_at < submit_built_at:
|
|
1031
|
+
raise SystemExit("submission blocked: lint result predates submit build")
|
|
1032
|
+
work_payload = load_json(work_path)
|
|
1033
|
+
raw_payload = load_json(raw_path)
|
|
1034
|
+
submit_payload = load_json(submit_path)
|
|
1035
|
+
lint = lint_work_payload(work_payload, raw_payload=raw_payload)
|
|
1036
|
+
if lint["errors"]:
|
|
1037
|
+
raise SystemExit("submission blocked by lint: " + "; ".join(lint["errors"]))
|
|
1038
|
+
if not isinstance(submit_payload, dict) or "role" not in submit_payload:
|
|
1039
|
+
raise SystemExit("submission blocked: submit payload is malformed")
|
|
1040
|
+
return meta
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def app_base_url(base_url: str) -> str:
|
|
1044
|
+
text = base_url.rstrip("/")
|
|
1045
|
+
if text.endswith("/api"):
|
|
1046
|
+
return text[:-4]
|
|
1047
|
+
return text
|
|
1048
|
+
|
|
1049
|
+
|
|
1050
|
+
def api_base_url(base_url: str) -> str:
|
|
1051
|
+
text = base_url.rstrip("/")
|
|
1052
|
+
if text.endswith("/api"):
|
|
1053
|
+
return text
|
|
1054
|
+
return text + "/api"
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
def build_acceptance_urls(*, base_url: str, workspace: str) -> Dict[str, str]:
|
|
1058
|
+
app_url = app_base_url(base_url)
|
|
1059
|
+
role_url = f"{app_url}/w:{workspace}/role"
|
|
1060
|
+
return {
|
|
1061
|
+
"roleUrl": role_url,
|
|
1062
|
+
"basicTabUrl": role_url,
|
|
1063
|
+
"systemTabUrl": role_url,
|
|
1064
|
+
"customTabUrl": role_url,
|
|
1065
|
+
"flowTabUrl": role_url,
|
|
1066
|
+
"memberTabUrl": role_url,
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
|
|
1070
|
+
def record_submission_meta(meta_path: Path, *, stem: str, role_id: int, acceptance_urls: Dict[str, str]) -> Dict[str, Any]:
|
|
1071
|
+
payload = ensure_meta_shape(load_meta(meta_path), stem)
|
|
1072
|
+
payload["roleId"] = role_id
|
|
1073
|
+
payload["submittedAt"] = utc_now_iso()
|
|
1074
|
+
payload["status"] = "submitted"
|
|
1075
|
+
payload["roleUrl"] = acceptance_urls.get("roleUrl")
|
|
1076
|
+
save_meta(meta_path, payload)
|
|
1077
|
+
return payload
|
|
1078
|
+
|
|
1079
|
+
|
|
1080
|
+
@dataclass
|
|
1081
|
+
class ApiClient:
|
|
1082
|
+
base_url: str
|
|
1083
|
+
workspace: str
|
|
1084
|
+
language: str
|
|
1085
|
+
cookie_header: str
|
|
1086
|
+
timeout: float
|
|
1087
|
+
insecure: bool = False
|
|
1088
|
+
|
|
1089
|
+
def _build_url(self, path: str) -> str:
|
|
1090
|
+
joiner = "&" if "?" in path else "?"
|
|
1091
|
+
suffix = f"$workspace={urllib.parse.quote(self.workspace)}&$language={urllib.parse.quote(self.language)}"
|
|
1092
|
+
return api_base_url(self.base_url) + path + joiner + suffix
|
|
1093
|
+
|
|
1094
|
+
def request(self, method: str, path: str, body: Optional[dict] = None) -> dict:
|
|
1095
|
+
headers = {
|
|
1096
|
+
"content-type": "application/json",
|
|
1097
|
+
"cookie": self.cookie_header,
|
|
1098
|
+
"accept": "application/json, text/plain, */*",
|
|
1099
|
+
}
|
|
1100
|
+
data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
1101
|
+
req = urllib.request.Request(self._build_url(path), data=data, headers=headers, method=method)
|
|
1102
|
+
context = ssl._create_unverified_context() if self.insecure else None
|
|
1103
|
+
try:
|
|
1104
|
+
with urllib.request.urlopen(req, timeout=self.timeout, context=context) as resp:
|
|
1105
|
+
raw = resp.read().decode("utf-8", "replace")
|
|
1106
|
+
except urllib.error.HTTPError as err:
|
|
1107
|
+
raw = err.read().decode("utf-8", "replace")
|
|
1108
|
+
raise SystemExit(f"HTTP {err.code} {path}: {raw}") from err
|
|
1109
|
+
except urllib.error.URLError as err:
|
|
1110
|
+
raise SystemExit(f"Request failed {path}: {err}") from err
|
|
1111
|
+
payload = json.loads(raw)
|
|
1112
|
+
if isinstance(payload, dict) and payload.get("code") not in (None, 0):
|
|
1113
|
+
raise SystemExit(f"API error {path}: {payload}")
|
|
1114
|
+
return payload
|
|
1115
|
+
|
|
1116
|
+
def get_role_list(self, *, page: int = 1, page_size: int = 1000, sort: str = "-id", q_name: str | None = None) -> list[dict]:
|
|
1117
|
+
path = f"/role?page={page}&page_size={page_size}&sort={urllib.parse.quote(sort)}"
|
|
1118
|
+
if q_name:
|
|
1119
|
+
path += f"&q_name={urllib.parse.quote(q_name)}"
|
|
1120
|
+
payload = self.request("GET", path)
|
|
1121
|
+
data = payload.get("data", {})
|
|
1122
|
+
if not isinstance(data, dict):
|
|
1123
|
+
raise SystemExit("role list response must contain object data")
|
|
1124
|
+
items = data.get("data")
|
|
1125
|
+
if not isinstance(items, list):
|
|
1126
|
+
raise SystemExit("role list response must contain data.data array")
|
|
1127
|
+
return items
|
|
1128
|
+
|
|
1129
|
+
def get_role(self, role_id: int) -> dict:
|
|
1130
|
+
for item in self.get_role_list(page_size=1000):
|
|
1131
|
+
if item.get("id") == role_id:
|
|
1132
|
+
return item
|
|
1133
|
+
raise SystemExit(f"unable to locate role {role_id} from /role list")
|
|
1134
|
+
|
|
1135
|
+
def get_point_list(self) -> list[dict]:
|
|
1136
|
+
payload = self.request("GET", "/point/point_list")
|
|
1137
|
+
data = payload.get("data")
|
|
1138
|
+
if not isinstance(data, list):
|
|
1139
|
+
raise SystemExit("point list response must contain array data")
|
|
1140
|
+
return data
|
|
1141
|
+
|
|
1142
|
+
def get_workspace_list(self) -> list[dict]:
|
|
1143
|
+
payload = self.request("GET", "/workspace?page_size=10000")
|
|
1144
|
+
data = payload.get("data")
|
|
1145
|
+
if isinstance(data, dict):
|
|
1146
|
+
items = data.get("data")
|
|
1147
|
+
if isinstance(items, list):
|
|
1148
|
+
return items
|
|
1149
|
+
if not isinstance(data, list):
|
|
1150
|
+
raise SystemExit("workspace response must contain array data")
|
|
1151
|
+
return data
|
|
1152
|
+
|
|
1153
|
+
def get_member_list(self, role_id: int, *, page_size: int = 1000) -> list[dict]:
|
|
1154
|
+
payload = self.request("GET", f"/user_role?page=1&page_size={page_size}&role_id={role_id}")
|
|
1155
|
+
data = payload.get("data", {})
|
|
1156
|
+
if not isinstance(data, dict):
|
|
1157
|
+
raise SystemExit("user_role response must contain object data")
|
|
1158
|
+
items = data.get("data")
|
|
1159
|
+
if not isinstance(items, list):
|
|
1160
|
+
raise SystemExit("user_role response must contain data.data array")
|
|
1161
|
+
return items
|
|
1162
|
+
|
|
1163
|
+
def get_flows_by_keys(self, keys: list[str]) -> list[dict]:
|
|
1164
|
+
if not keys:
|
|
1165
|
+
return []
|
|
1166
|
+
payload = self.request("POST", "/flow/list/lightweight?page_size=1000", {"keyList": keys})
|
|
1167
|
+
data = payload.get("data")
|
|
1168
|
+
if isinstance(data, dict):
|
|
1169
|
+
items = data.get("data")
|
|
1170
|
+
if isinstance(items, list):
|
|
1171
|
+
return items
|
|
1172
|
+
if not isinstance(data, list):
|
|
1173
|
+
raise SystemExit("flow lightweight response must contain array data")
|
|
1174
|
+
return data
|
|
1175
|
+
|
|
1176
|
+
def search_flows_by_name(self, name: str) -> list[dict]:
|
|
1177
|
+
payload = self.request("POST", "/flow/list/lightweight", {"name": name})
|
|
1178
|
+
data = payload.get("data")
|
|
1179
|
+
if isinstance(data, dict):
|
|
1180
|
+
items = data.get("data")
|
|
1181
|
+
if isinstance(items, list):
|
|
1182
|
+
return items
|
|
1183
|
+
if not isinstance(data, list):
|
|
1184
|
+
raise SystemExit("flow lightweight response must contain array data")
|
|
1185
|
+
return data
|
|
1186
|
+
|
|
1187
|
+
def create_role(self, body: Dict[str, Any]) -> dict:
|
|
1188
|
+
return self.request("POST", "/role", body)
|
|
1189
|
+
|
|
1190
|
+
def update_role(self, role_id: int, body: Dict[str, Any]) -> dict:
|
|
1191
|
+
return self.request("PUT", f"/role/{role_id}", body)
|
|
1192
|
+
|
|
1193
|
+
def create_point(self, body: Dict[str, Any]) -> dict:
|
|
1194
|
+
return self.request("POST", "/point", body)
|
|
1195
|
+
|
|
1196
|
+
def update_point(self, point_id: int, body: Dict[str, Any]) -> dict:
|
|
1197
|
+
return self.request("PUT", f"/point/{point_id}", body)
|
|
1198
|
+
|
|
1199
|
+
def delete_point(self, point_id: int) -> dict:
|
|
1200
|
+
return self.request("DELETE", f"/point/{point_id}")
|
|
1201
|
+
|
|
1202
|
+
def add_member(self, role_id: int, user_id: int) -> dict:
|
|
1203
|
+
return self.request("POST", "/user_role", {"usersId": [user_id], "role_id": role_id})
|
|
1204
|
+
|
|
1205
|
+
def delete_member(self, user_role_id: int) -> dict:
|
|
1206
|
+
return self.request("DELETE", f"/user_role/{user_role_id}")
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
def resolve_cookie_header(value: Optional[str]) -> str:
|
|
1210
|
+
cookie = value or os.environ.get("BPMAX_COOKIE_HEADER", "")
|
|
1211
|
+
if not cookie:
|
|
1212
|
+
raise SystemExit("missing cookie header: pass --cookie-header or set BPMAX_COOKIE_HEADER")
|
|
1213
|
+
return cookie
|
|
1214
|
+
|
|
1215
|
+
|
|
1216
|
+
def resolve_workspace(value: Optional[str]) -> str:
|
|
1217
|
+
workspace = value or os.environ.get("BPMAX_WORKSPACE", "")
|
|
1218
|
+
if not workspace:
|
|
1219
|
+
raise SystemExit("missing workspace: pass --workspace or set BPMAX_WORKSPACE")
|
|
1220
|
+
return workspace
|
|
1221
|
+
|
|
1222
|
+
|
|
1223
|
+
def build_client(args: Any) -> ApiClient:
|
|
1224
|
+
return ApiClient(
|
|
1225
|
+
base_url=resolve_base_url(getattr(args, "base_url", None)),
|
|
1226
|
+
workspace=resolve_workspace(getattr(args, "workspace", None)),
|
|
1227
|
+
language=getattr(args, "language", DEFAULT_LANGUAGE),
|
|
1228
|
+
cookie_header=resolve_cookie_header(getattr(args, "cookie_header", None)),
|
|
1229
|
+
timeout=float(getattr(args, "timeout", 30)),
|
|
1230
|
+
insecure=bool(getattr(args, "insecure", False)),
|
|
1231
|
+
)
|