@qingflow-tech/qingflow-cli 1.1.1 → 1.1.33

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 (120) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/pyproject.toml +1 -1
  4. package/skills/qingflow-cli/SKILL.md +59 -45
  5. package/skills/qingflow-cli/manifest.yaml +1 -1
  6. package/skills/qingflow-cli/reference/00-INDEX.md +35 -0
  7. package/skills/qingflow-cli/reference/QINGFLOW_CLI_BUILDER_APP_DELIVERY_WORKFLOW.md +21 -477
  8. package/skills/qingflow-cli/reference/QINGFLOW_CLI_BUILDER_VIEWS_WORKFLOW.md +44 -290
  9. package/skills/qingflow-cli/reference/QINGFLOW_CLI_SCHEMA_APPLY_FIELD_TYPES_AND_SCENARIOS.md +11 -102
  10. package/skills/qingflow-cli/reference/builder/10-build-single-app.md +57 -0
  11. package/skills/qingflow-cli/reference/builder/20-build-complete-system.md +84 -0
  12. package/skills/qingflow-cli/reference/builder/30-schema-fields.md +317 -0
  13. package/skills/qingflow-cli/reference/builder/40-layout.md +70 -0
  14. package/skills/qingflow-cli/reference/builder/50-views.md +540 -0
  15. package/skills/qingflow-cli/reference/builder/60-charts.md +328 -0
  16. package/skills/qingflow-cli/reference/builder/70-portal.md +372 -0
  17. package/skills/qingflow-cli/reference/builder/80-buttons-associated-resources.md +148 -0
  18. package/skills/qingflow-cli/reference/builder/90-workflow.md +41 -0
  19. package/skills/qingflow-cli/reference/builder/99-publish-verify.md +64 -0
  20. package/skills/qingflow-cli/reference/builder/README.md +62 -0
  21. package/skills/qingflow-cli/reference/builder/code-integrations/README.md +130 -0
  22. package/skills/qingflow-cli/reference/builder/code-integrations/code-block.md +66 -0
  23. package/skills/qingflow-cli/reference/builder/code-integrations/q-linker.md +77 -0
  24. package/skills/qingflow-cli/reference/builder/reference/app-delivery-sop.md +511 -0
  25. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/README.md +308 -0
  26. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/build-complete-system.md +819 -0
  27. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/build-single-app.md +836 -0
  28. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/complete-system-development-guide.md +137 -0
  29. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/create-app.md +203 -0
  30. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/environments.md +63 -0
  31. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/flow-actors-and-permissions.md +142 -0
  32. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/gotchas.md +116 -0
  33. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/match-rules.md +114 -0
  34. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/public-surface-sync.md +75 -0
  35. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/single-app-development-guide.md +69 -0
  36. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/solution-playbooks.md +52 -0
  37. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/tool-selection.md +113 -0
  38. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-flow.md +7 -0
  39. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-layout.md +7 -0
  40. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-schema.md +7 -0
  41. package/skills/qingflow-cli/reference/builder/reference/legacy-playbooks/update-views.md +7 -0
  42. package/skills/qingflow-cli/reference/builder/reference/match-rules.md +229 -0
  43. package/skills/qingflow-cli/reference/builder/reference/workspace-icons.md +89 -0
  44. package/skills/qingflow-cli/reference/builder/workflow/01-overview.md +47 -0
  45. package/skills/qingflow-cli/reference/builder/workflow/02-update-mode.md +63 -0
  46. package/skills/qingflow-cli/reference/builder/workflow/03-flow-patterns.md +59 -0
  47. package/skills/qingflow-cli/reference/builder/workflow/04-stage1-business-modeling.md +131 -0
  48. package/skills/qingflow-cli/reference/builder/workflow/05-stage2-members-roles.md +29 -0
  49. package/skills/qingflow-cli/reference/builder/workflow/06-stage3-build-spec.md +217 -0
  50. package/skills/qingflow-cli/reference/builder/workflow/07-stage4-validate-spec.md +42 -0
  51. package/skills/qingflow-cli/reference/builder/workflow/08-stage5-apply-verify.md +67 -0
  52. package/skills/qingflow-cli/reference/builder/workflow/09-stage6-summary.md +88 -0
  53. package/skills/qingflow-cli/reference/builder/workflow/10-node-config-reference.md +93 -0
  54. package/skills/qingflow-cli/reference/builder/workflow/11-troubleshooting.md +17 -0
  55. package/skills/qingflow-cli/reference/builder/workflow/README.md +88 -0
  56. package/skills/qingflow-cli/reference/builder/workflow/workflow-schema.json +1754 -0
  57. package/skills/qingflow-cli/reference/charts_upsert_dashboard_starter.example.json +81 -0
  58. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_ADMIN_CHEATSHEET.md +94 -0
  59. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_DATA_RETRIEVAL_WORKFLOW.md +139 -0
  60. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_EXPLORATION_REPORT.md +84 -0
  61. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_FIELD_DATA_TYPES.md +129 -0
  62. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_MEMBER_CHEATSHEET.md +195 -0
  63. package/skills/qingflow-cli/reference/core/QINGFLOW_CLI_ONE_SHOT_CHEATSHEET.md +159 -0
  64. package/skills/qingflow-cli/reference/examples/README.md +17 -0
  65. package/skills/qingflow-cli/reference/examples/associated/associated_resources_semantic_full.example.json +50 -0
  66. package/skills/qingflow-cli/reference/examples/buttons/custom_buttons_advanced.example.json +56 -0
  67. package/skills/qingflow-cli/reference/examples/charts/charts_remove.example.json +1 -0
  68. package/skills/qingflow-cli/reference/examples/charts/charts_reorder.example.json +1 -0
  69. package/skills/qingflow-cli/reference/examples/charts/charts_upsert_bar.example.json +8 -0
  70. package/skills/qingflow-cli/reference/examples/charts/charts_upsert_dashboard_starter.example.json +118 -0
  71. package/skills/qingflow-cli/reference/examples/charts/charts_upsert_minimal.example.json +13 -0
  72. package/skills/qingflow-cli/reference/examples/layout/layout_sections_full.example.json +22 -0
  73. package/skills/qingflow-cli/reference/examples/portal/portal_sections_all_types.example.json +145 -0
  74. package/skills/qingflow-cli/reference/examples/portal/portal_sections_five_types.example.json +126 -0
  75. package/skills/qingflow-cli/reference/examples/portal/portal_sections_standard_workbench.example.json +178 -0
  76. package/skills/qingflow-cli/reference/examples/record/record_insert_all_field_types.example.json +35 -0
  77. package/skills/qingflow-cli/reference/examples/schema/_batch_schema_complex.json +18 -0
  78. package/skills/qingflow-cli/reference/examples/schema/_batch_schema_scalar.json +17 -0
  79. package/skills/qingflow-cli/reference/examples/schema/schema_add_fields_minimal.example.json +7 -0
  80. package/skills/qingflow-cli/reference/examples/schema/schema_apply_add_fields_all_types.json +78 -0
  81. package/skills/qingflow-cli/reference/examples/schema/schema_multi_app_form_relation_layout.example.json +166 -0
  82. package/skills/qingflow-cli/reference/examples/schema/schema_single_app_form_standard.example.json +95 -0
  83. package/skills/qingflow-cli/reference/examples/views/views_batch_full.example.json +159 -0
  84. package/skills/qingflow-cli/reference/examples/views/views_upsert_table_minimal.example.json +42 -0
  85. package/skills/qingflow-cli/reference/portal_sections_all_types.example.json +18 -4
  86. package/skills/qingflow-cli/reference/portal_sections_five_types.example.json +3 -3
  87. package/skills/qingflow-cli/reference/portal_sections_standard_workbench.example.json +57 -7
  88. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_CREATE_WORKFLOW.md +22 -0
  89. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_DELETE_WORKFLOW.md +31 -0
  90. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_IMPORT_WORKFLOW.md +176 -0
  91. package/skills/qingflow-cli/reference/record/QINGFLOW_CLI_RECORD_UPDATE_WORKFLOW.md +167 -0
  92. package/skills/qingflow-cli/reference/record/analysis/README.md +130 -0
  93. package/skills/qingflow-cli/reference/record/analysis/analysis-gotchas.md +91 -0
  94. package/skills/qingflow-cli/reference/record/analysis/analysis-patterns.md +112 -0
  95. package/skills/qingflow-cli/reference/record/analysis/business-context.md +74 -0
  96. package/skills/qingflow-cli/reference/record/analysis/confidence-reporting.md +69 -0
  97. package/skills/qingflow-cli/reference/record/analysis/data-access-playbook.md +106 -0
  98. package/skills/qingflow-cli/reference/record/analysis/pandas-recipes.md +172 -0
  99. package/skills/qingflow-cli/reference/record/analysis/report-format.md +76 -0
  100. package/skills/qingflow-cli/reference/record/insert/README.md +125 -0
  101. package/skills/qingflow-cli/reference/schema_apply_add_fields_all_types.json +1 -1
  102. package/skills/qingflow-cli/reference/task/QINGFLOW_CLI_TASK_CONTEXT_WORKFLOW.md +153 -0
  103. package/skills/qingflow-cli/reference/task/ops/README.md +134 -0
  104. package/skills/qingflow-cli/reference/task/ops/environments.md +43 -0
  105. package/skills/qingflow-cli/reference/task/ops/workflow-usage.md +29 -0
  106. package/skills/qingflow-cli/reference/views_upsert_table_minimal.example.json +42 -7
  107. package/skills/qingflow-cli/scripts/validate_system_build_summary.py +124 -0
  108. package/skills/qingflow-cli/scripts/workflow/diff_flow_spec.py +275 -0
  109. package/skills/qingflow-cli/scripts/workflow/validate_flow_spec.py +605 -0
  110. package/src/qingflow_mcp/builder_facade/models.py +413 -119
  111. package/src/qingflow_mcp/builder_facade/service.py +4211 -676
  112. package/src/qingflow_mcp/cli/commands/builder.py +233 -74
  113. package/src/qingflow_mcp/cli/main.py +34 -0
  114. package/src/qingflow_mcp/public_surface.py +10 -0
  115. package/src/qingflow_mcp/server_app_builder.py +68 -34
  116. package/src/qingflow_mcp/solution/compiler/workflow_compiler.py +173 -0
  117. package/src/qingflow_mcp/solution/executor.py +2 -0
  118. package/src/qingflow_mcp/tools/ai_builder_tools.py +2662 -451
  119. package/src/qingflow_mcp/tools/record_tools.py +23 -11
  120. package/src/qingflow_mcp/tools/task_context_tools.py +35 -11
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ VALID_PORTAL_STATUSES = {"verified", "unverified", "not_created"}
12
+ VALID_APP_VERIFY_STATUSES = {"verified", "unverified", "failed"}
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ parser = argparse.ArgumentParser(description="Validate a Qingflow complete-system delivery summary JSON file.")
17
+ parser.add_argument("summary_file", nargs="?", default="tmp/qingflow_system_build_summary.json")
18
+ args = parser.parse_args(argv)
19
+ path = Path(args.summary_file)
20
+ issues = validate_summary_file(path)
21
+ if issues:
22
+ _emit({"status": "failed", "error_code": "SYSTEM_BUILD_SUMMARY_INVALID", "path": str(path), "issues": issues})
23
+ return 1
24
+ payload = json.loads(path.read_text(encoding="utf-8"))
25
+ _emit(
26
+ {
27
+ "status": "success",
28
+ "path": str(path),
29
+ "summary": {
30
+ "package_id": payload.get("package_id"),
31
+ "package_name": payload.get("package_name"),
32
+ "portal_dash_key": payload.get("portal_dash_key"),
33
+ "portal_live_status": payload.get("portal_live_status"),
34
+ "app_count": len(payload.get("apps") or []),
35
+ "partial_count": len(payload.get("partial_items") or []),
36
+ "needs_followup_count": len(payload.get("needs_followup") or []),
37
+ },
38
+ }
39
+ )
40
+ return 0
41
+
42
+
43
+ def validate_summary_file(path: Path) -> list[dict[str, Any]]:
44
+ if not path.exists():
45
+ return [_issue("MISSING_FILE", "$", f"summary file does not exist: {path}")]
46
+ try:
47
+ payload = json.loads(path.read_text(encoding="utf-8"))
48
+ except OSError as exc:
49
+ return [_issue("READ_FAILED", "$", str(exc))]
50
+ except json.JSONDecodeError as exc:
51
+ return [_issue("INVALID_JSON", "$", exc.msg)]
52
+ if not isinstance(payload, dict):
53
+ return [_issue("INVALID_ROOT", "$", "summary root must be a JSON object")]
54
+
55
+ issues: list[dict[str, Any]] = []
56
+ _require_positive_int(payload, "package_id", issues)
57
+ _require_nonempty_string(payload, "package_name", issues)
58
+ _require_bool(payload, "front_end_visible", issues)
59
+ _require_string_enum(payload, "portal_live_status", VALID_PORTAL_STATUSES, issues)
60
+ if payload.get("portal_live_status") == "verified":
61
+ _require_nonempty_string(payload, "portal_dash_key", issues)
62
+ elif "portal_dash_key" in payload and payload.get("portal_dash_key") is not None and not isinstance(payload.get("portal_dash_key"), str):
63
+ issues.append(_issue("INVALID_TYPE", "$.portal_dash_key", "portal_dash_key must be a string when present"))
64
+
65
+ apps = payload.get("apps")
66
+ if not isinstance(apps, list) or not apps:
67
+ issues.append(_issue("INVALID_APPS", "$.apps", "apps must be a non-empty array"))
68
+ else:
69
+ for index, app in enumerate(apps):
70
+ prefix = f"$.apps[{index}]"
71
+ if not isinstance(app, dict):
72
+ issues.append(_issue("INVALID_APP_ITEM", prefix, "app item must be an object"))
73
+ continue
74
+ _require_nonempty_string(app, "app_key", issues, prefix)
75
+ _require_nonempty_string(app, "app_name", issues, prefix)
76
+ for key in ("fields_count", "views_count", "flows_count", "charts_count"):
77
+ _require_nonnegative_int(app, key, issues, prefix)
78
+ _require_string_enum(app, "publish_verify_status", VALID_APP_VERIFY_STATUSES, issues, prefix)
79
+
80
+ for key in ("warnings", "partial_items", "needs_followup"):
81
+ if not isinstance(payload.get(key), list):
82
+ issues.append(_issue("INVALID_TYPE", f"$.{key}", f"{key} must be an array"))
83
+ return issues
84
+
85
+
86
+ def _require_positive_int(payload: dict[str, Any], key: str, issues: list[dict[str, Any]], prefix: str = "$") -> None:
87
+ value = payload.get(key)
88
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
89
+ issues.append(_issue("INVALID_TYPE", f"{prefix}.{key}", f"{key} must be a positive integer"))
90
+
91
+
92
+ def _require_nonnegative_int(payload: dict[str, Any], key: str, issues: list[dict[str, Any]], prefix: str = "$") -> None:
93
+ value = payload.get(key)
94
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
95
+ issues.append(_issue("INVALID_TYPE", f"{prefix}.{key}", f"{key} must be a non-negative integer"))
96
+
97
+
98
+ def _require_nonempty_string(payload: dict[str, Any], key: str, issues: list[dict[str, Any]], prefix: str = "$") -> None:
99
+ value = payload.get(key)
100
+ if not isinstance(value, str) or not value.strip():
101
+ issues.append(_issue("INVALID_TYPE", f"{prefix}.{key}", f"{key} must be a non-empty string"))
102
+
103
+
104
+ def _require_bool(payload: dict[str, Any], key: str, issues: list[dict[str, Any]], prefix: str = "$") -> None:
105
+ if not isinstance(payload.get(key), bool):
106
+ issues.append(_issue("INVALID_TYPE", f"{prefix}.{key}", f"{key} must be a boolean"))
107
+
108
+
109
+ def _require_string_enum(payload: dict[str, Any], key: str, allowed: set[str], issues: list[dict[str, Any]], prefix: str = "$") -> None:
110
+ value = payload.get(key)
111
+ if value not in allowed:
112
+ issues.append(_issue("INVALID_VALUE", f"{prefix}.{key}", f"{key} must be one of {sorted(allowed)}"))
113
+
114
+
115
+ def _issue(code: str, path: str, message: str) -> dict[str, Any]:
116
+ return {"code": code, "path": path, "message": message}
117
+
118
+
119
+ def _emit(payload: dict[str, Any]) -> None:
120
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
121
+
122
+
123
+ if __name__ == "__main__":
124
+ sys.exit(main())
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ 对比两个工作流 spec 的差异,输出新增/删除/修改的节点和边。
4
+ 用于更新模式下辅助 agent 判断是否遵循最小修改原则。
5
+
6
+ 用法:
7
+ python3 diff_flow_spec.py <old_spec.json> <new_spec.json>
8
+ python3 diff_flow_spec.py <old_spec.json> <new_spec.json> --json # JSON 输出
9
+ """
10
+
11
+ import json
12
+ import sys
13
+
14
+
15
+ def load_json(path):
16
+ with open(path, 'r', encoding='utf-8') as f:
17
+ return json.load(f)
18
+
19
+
20
+ def extract_edges(spec):
21
+ """从 spec 中提取边列表,兼容 edges 在不同层级的情况"""
22
+ e = spec.get('edges', [])
23
+ if isinstance(e, dict) and 'edges' in e:
24
+ return e['edges']
25
+ if isinstance(e, list):
26
+ return e
27
+ return []
28
+
29
+
30
+ def node_key(n):
31
+ """节点的唯一标识"""
32
+ return n.get('id', '')
33
+
34
+
35
+ def edge_key(e):
36
+ """边的唯一标识:from→to"""
37
+ return (e.get('from', ''), e.get('to', ''))
38
+
39
+
40
+ def node_identity(n):
41
+ """节点的完整内容(不含 id,用于判断是否修改)"""
42
+ return {
43
+ 'type': n.get('type', ''),
44
+ 'name': n.get('name', ''),
45
+ 'attrs': n.get('attrs', {}),
46
+ }
47
+
48
+
49
+ def edge_identity(e):
50
+ """边的完整内容(不含 from/to,用于判断是否修改)"""
51
+ return {
52
+ 'label': e.get('label', ''),
53
+ 'condition': e.get('condition', {}),
54
+ }
55
+
56
+
57
+ def diff_nodes(old_nodes, new_nodes):
58
+ """对比节点差异"""
59
+ old_by_id = {node_key(n): n for n in old_nodes}
60
+ new_by_id = {node_key(n): n for n in new_nodes}
61
+
62
+ old_ids = set(old_by_id.keys())
63
+ new_ids = set(new_by_id.keys())
64
+
65
+ deleted_ids = sorted(old_ids - new_ids)
66
+ added_ids = sorted(new_ids - old_ids)
67
+ common_ids = sorted(old_ids & new_ids)
68
+
69
+ modified = []
70
+ id_changes = []
71
+ for nid in common_ids:
72
+ old_ident = node_identity(old_by_id[nid])
73
+ new_ident = node_identity(new_by_id[nid])
74
+ if old_ident != new_ident:
75
+ modified.append({
76
+ 'id': nid,
77
+ 'old': {'type': old_ident['type'], 'name': old_ident['name']},
78
+ 'new': {'type': new_ident['type'], 'name': new_ident['name']},
79
+ 'attrs_changed': old_ident['attrs'] != new_ident['attrs'],
80
+ 'type_changed': old_ident['type'] != new_ident['type'],
81
+ 'name_changed': old_ident['name'] != new_ident['name'],
82
+ })
83
+
84
+ # 检测可能的不必要 ID 变更(内容相同但 ID 不同)
85
+ old_by_identity = {}
86
+ for n in old_nodes:
87
+ ident = json.dumps(node_identity(n), sort_keys=True, ensure_ascii=False)
88
+ old_by_identity.setdefault(ident, []).append(n)
89
+
90
+ for n in new_nodes:
91
+ if node_key(n) in added_ids:
92
+ ident = json.dumps(node_identity(n), sort_keys=True, ensure_ascii=False)
93
+ if ident in old_by_identity and old_by_identity[ident]:
94
+ old_match = old_by_identity[ident][0]
95
+ if node_key(old_match) in deleted_ids:
96
+ id_changes.append({
97
+ 'old_id': node_key(old_match),
98
+ 'new_id': node_key(n),
99
+ 'identity': node_identity(n),
100
+ 'warning': '节点内容未变但 ID 已变更,可能导致后端不支持配置丢失',
101
+ })
102
+
103
+ return {
104
+ 'deleted': [{'id': nid, 'name': old_by_id[nid].get('name', ''), 'type': old_by_id[nid].get('type', '')} for nid in deleted_ids],
105
+ 'added': [{'id': nid, 'name': new_by_id[nid].get('name', ''), 'type': new_by_id[nid].get('type', '')} for nid in added_ids],
106
+ 'modified': modified,
107
+ 'id_changes': id_changes,
108
+ 'unchanged': len(common_ids) - len(modified),
109
+ }
110
+
111
+
112
+ def diff_edges(old_edges, new_edges):
113
+ """对比边差异"""
114
+ old_by_key = {edge_key(e): e for e in old_edges}
115
+ new_by_key = {edge_key(e): e for e in new_edges}
116
+
117
+ old_keys = set(old_by_key.keys())
118
+ new_keys = set(new_by_key.keys())
119
+
120
+ deleted_keys = sorted(old_keys - new_keys)
121
+ added_keys = sorted(new_keys - old_keys)
122
+ common_keys = sorted(old_keys & new_keys)
123
+
124
+ modified = []
125
+ for key in common_keys:
126
+ old_ident = edge_identity(old_by_key[key])
127
+ new_ident = edge_identity(new_by_key[key])
128
+ if old_ident != new_ident:
129
+ modified.append({
130
+ 'from': key[0],
131
+ 'to': key[1],
132
+ 'old_condition': old_ident['condition'],
133
+ 'new_condition': new_ident['condition'],
134
+ 'label_changed': old_ident['label'] != new_ident['label'],
135
+ 'condition_changed': old_ident['condition'] != new_ident['condition'],
136
+ })
137
+
138
+ return {
139
+ 'deleted': [{'from': k[0], 'to': k[1]} for k in deleted_keys],
140
+ 'added': [{'from': k[0], 'to': k[1]} for k in added_keys],
141
+ 'modified': modified,
142
+ 'unchanged': len(common_keys) - len(modified),
143
+ }
144
+
145
+
146
+ def print_human(result):
147
+ """人类可读输出"""
148
+ nodes = result['nodes']
149
+ edges = result['edges']
150
+
151
+ print("=" * 60)
152
+ print("工作流 Spec 差异分析")
153
+ print("=" * 60)
154
+
155
+ # 节点汇总
156
+ print(f"\n📊 节点汇总:")
157
+ print(f" 删除: {len(nodes['deleted'])} | 新增: {len(nodes['added'])} | "
158
+ f"修改: {len(nodes['modified'])} | 未变: {nodes['unchanged']}")
159
+
160
+ if nodes['id_changes']:
161
+ print(f"\n⚠️ 检测到 {len(nodes['id_changes'])} 个可能的 ID 变更(内容相同但 ID 不同):")
162
+ for ic in nodes['id_changes']:
163
+ print(f" {ic['old_id']} → {ic['new_id']} ({ic['identity']['name']})")
164
+ print(f" ⚠ {ic['warning']}")
165
+
166
+ if nodes['deleted']:
167
+ print(f"\n🗑 删除的节点 ({len(nodes['deleted'])}):")
168
+ for d in nodes['deleted']:
169
+ print(f" - [{d['type']}] {d['id']} ({d['name']})")
170
+
171
+ if nodes['added']:
172
+ print(f"\n➕ 新增的节点 ({len(nodes['added'])}):")
173
+ for a in nodes['added']:
174
+ print(f" - [{a['type']}] {a['id']} ({a['name']})")
175
+
176
+ if nodes['modified']:
177
+ print(f"\n✏️ 修改的节点 ({len(nodes['modified'])}):")
178
+ for m in nodes['modified']:
179
+ changes = []
180
+ if m['type_changed']:
181
+ changes.append(f"type: {m['old']['type']} → {m['new']['type']}")
182
+ if m['name_changed']:
183
+ changes.append(f"name: {m['old']['name']} → {m['new']['name']}")
184
+ if m['attrs_changed']:
185
+ changes.append("attrs 已变更")
186
+ print(f" - {m['id']}: {', '.join(changes) if changes else '无实质变更'}")
187
+
188
+ # 边汇总
189
+ print(f"\n📊 边汇总:")
190
+ print(f" 删除: {len(edges['deleted'])} | 新增: {len(edges['added'])} | "
191
+ f"修改: {len(edges['modified'])} | 未变: {edges['unchanged']}")
192
+
193
+ if edges['deleted']:
194
+ print(f"\n🗑 删除的边 ({len(edges['deleted'])}):")
195
+ for d in edges['deleted']:
196
+ print(f" - {d['from']} → {d['to']}")
197
+
198
+ if edges['added']:
199
+ print(f"\n➕ 新增的边 ({len(edges['added'])}):")
200
+ for a in edges['added']:
201
+ print(f" - {a['from']} → {a['to']}")
202
+
203
+ if edges['modified']:
204
+ print(f"\n✏️ 修改的边 ({len(edges['modified'])}):")
205
+ for m in edges['modified']:
206
+ changes = []
207
+ if m['label_changed']:
208
+ changes.append("label 已变更")
209
+ if m['condition_changed']:
210
+ changes.append("condition 已变更")
211
+ if changes:
212
+ print(f" - {m['from']} → {m['to']}: {', '.join(changes)}")
213
+ else:
214
+ print(f" - {m['from']} → {m['to']}: 无实质变更")
215
+
216
+ # 最小修改原则评估
217
+ print(f"\n📋 最小修改原则评估:")
218
+ issues = 0
219
+ if nodes['id_changes']:
220
+ print(f" ❌ 存在 ID 变更({len(nodes['id_changes'])} 个节点),可能导致后端不支持配置丢失")
221
+ issues += 1
222
+ if nodes['deleted']:
223
+ print(f" ⚠️ 删除了 {len(nodes['deleted'])} 个节点,请确认是否为业务需要")
224
+ issues += 1
225
+ if not nodes['deleted'] and not nodes['id_changes'] and nodes['modified']:
226
+ print(f" ✅ 仅修改已有节点,未删除或变更 ID,符合最小修改原则")
227
+ if not nodes['deleted'] and not nodes['modified'] and not nodes['added'] and not nodes['id_changes']:
228
+ print(f" ✅ 无任何变更")
229
+
230
+ print(f"\n总结: 错误 {issues} 项")
231
+
232
+
233
+ def main():
234
+ if len(sys.argv) < 3:
235
+ print("用法: python3 diff_flow_spec.py <old_spec.json> <new_spec.json> [--json]")
236
+ sys.exit(1)
237
+
238
+ old_file = sys.argv[1]
239
+ new_file = sys.argv[2]
240
+ output_json = '--json' in sys.argv
241
+
242
+ try:
243
+ old_spec = load_json(old_file)
244
+ except Exception as e:
245
+ print(f"FATAL: 无法读取旧 spec 文件 {old_file}: {e}")
246
+ sys.exit(1)
247
+
248
+ try:
249
+ new_spec = load_json(new_file)
250
+ except Exception as e:
251
+ print(f"FATAL: 无法读取新 spec 文件 {new_file}: {e}")
252
+ sys.exit(1)
253
+
254
+ old_nodes = old_spec.get('nodes', [])
255
+ new_nodes = new_spec.get('nodes', [])
256
+ old_edges = extract_edges(old_spec)
257
+ new_edges = extract_edges(new_spec)
258
+
259
+ result = {
260
+ 'nodes': diff_nodes(old_nodes, new_nodes),
261
+ 'edges': diff_edges(old_edges, new_edges),
262
+ }
263
+
264
+ if output_json:
265
+ print(json.dumps(result, indent=2, ensure_ascii=False))
266
+ else:
267
+ print_human(result)
268
+
269
+ # 如果有 ID 变更,返回非零以便脚本判断
270
+ has_id_changes = len(result['nodes']['id_changes']) > 0
271
+ sys.exit(1 if has_id_changes else 0)
272
+
273
+
274
+ if __name__ == '__main__':
275
+ main()