@sokeai/cli 1.0.116 → 1.0.118

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 (68) hide show
  1. package/README.md +2 -0
  2. package/docs/harmonyos.md +67 -0
  3. package/package.json +4 -1
  4. package/scripts/install.js +7 -21
  5. package/scripts/runtime-platform.js +32 -0
  6. package/skills/multi/demo-init/CHANGELOG.md +1241 -0
  7. package/skills/multi/demo-init/README.md +137 -0
  8. package/skills/multi/demo-init/SKILL.legacy.md +307 -0
  9. package/skills/multi/demo-init/assets/placeholder.pptx +0 -0
  10. package/skills/multi/demo-init/references/anti-patterns.md +83 -0
  11. package/skills/multi/demo-init/references/asset-design.md +230 -0
  12. package/skills/multi/demo-init/references/asset-spec.md +94 -0
  13. package/skills/multi/demo-init/references/blueprint-schema.md +174 -0
  14. package/skills/multi/demo-init/references/cli-onboarding.md +207 -0
  15. package/skills/multi/demo-init/references/cli-shared.md +183 -0
  16. package/skills/multi/demo-init/references/contracts.md +34 -0
  17. package/skills/multi/demo-init/references/course-setup.md +265 -0
  18. package/skills/multi/demo-init/references/demo-defaults.md +132 -0
  19. package/skills/multi/demo-init/references/demo-verify.md +355 -0
  20. package/skills/multi/demo-init/references/exam-setup.md +245 -0
  21. package/skills/multi/demo-init/references/gates-matrix.md +38 -0
  22. package/skills/multi/demo-init/references/map-setup.md +283 -0
  23. package/skills/multi/demo-init/references/plan-parse.md +185 -0
  24. package/skills/multi/demo-init/references/platform-access.md +55 -0
  25. package/skills/multi/demo-init/references/platform-commands.md +510 -0
  26. package/skills/multi/demo-init/references/point-setup.md +308 -0
  27. package/skills/multi/demo-init/references/portal-modules.md +130 -0
  28. package/skills/multi/demo-init/references/portal-setup.md +342 -0
  29. package/skills/multi/demo-init/references/project-setup.md +173 -0
  30. package/skills/multi/demo-init/references/run-protocol.md +208 -0
  31. package/skills/multi/demo-init/references/taxonomy-setup.md +101 -0
  32. package/skills/multi/demo-init/scripts/assign_backfill.py +281 -0
  33. package/skills/multi/demo-init/scripts/blueprint_lint.py +693 -0
  34. package/skills/multi/demo-init/scripts/blueprint_write.py +390 -0
  35. package/skills/multi/demo-init/scripts/category_bind.py +303 -0
  36. package/skills/multi/demo-init/scripts/category_create.py +748 -0
  37. package/skills/multi/demo-init/scripts/category_reassign.py +405 -0
  38. package/skills/multi/demo-init/scripts/category_verify.py +373 -0
  39. package/skills/multi/demo-init/scripts/cli_kit.py +597 -0
  40. package/skills/multi/demo-init/scripts/cli_probe.py +205 -0
  41. package/skills/multi/demo-init/scripts/course_build.py +857 -0
  42. package/skills/multi/demo-init/scripts/course_cover_repair.py +243 -0
  43. package/skills/multi/demo-init/scripts/doc_lint.py +619 -0
  44. package/skills/multi/demo-init/scripts/dup_cleanup.py +299 -0
  45. package/skills/multi/demo-init/scripts/dup_scan.py +368 -0
  46. package/skills/multi/demo-init/scripts/exam_build.py +551 -0
  47. package/skills/multi/demo-init/scripts/extract_docx.py +370 -0
  48. package/skills/multi/demo-init/scripts/gen_assets.py +1366 -0
  49. package/skills/multi/demo-init/scripts/guard.py +1272 -0
  50. package/skills/multi/demo-init/scripts/map_rebuild.py +391 -0
  51. package/skills/multi/demo-init/scripts/oss_image_upload.py +367 -0
  52. package/skills/multi/demo-init/scripts/portal_build.py +450 -0
  53. package/skills/multi/demo-init/scripts/portal_home_apply.py +255 -0
  54. package/skills/multi/demo-init/scripts/portal_home_layout.py +398 -0
  55. package/skills/multi/demo-init/scripts/project_build.py +309 -0
  56. package/skills/multi/demo-init/scripts/rebuild_taxonomy_map.py +100 -0
  57. package/skills/multi/demo-init/scripts/scope_plan.py +387 -0
  58. package/skills/multi/demo-init/scripts/selftest_all.py +211 -0
  59. package/skills/multi/demo-init/scripts/stock_probe.py +452 -0
  60. package/skills/multi/demo-init/scripts/taxonomy_build.py +512 -0
  61. package/skills/multi/demo-init-4.1.0.zip +0 -0
  62. package/skills/multi/demo-init-4.1.1.zip +0 -0
  63. package/skills/multi/demo-init-4.1.2.zip +0 -0
  64. package/skills/multi/demo-init-4.1.3.zip +0 -0
  65. package/skills/multi/ziQIJJpL +0 -0
  66. package/skills/multi/ziRsINis +0 -0
  67. package/skills/multi/ziUjKWRm +0 -0
  68. package/skills/multi/zipFWfuj +0 -0
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """portal_home_apply.py — 门户首页「改开关/排序」一条命令闭环(demo-init / portal-setup 消费)
4
+
5
+ 为什么需要它
6
+ 2026-10-21 loong-20261021 实机改造首页时,三个坑连踩,每个都靠人肉绕过:
7
+ ① 结构错配:`portal +home-get` 返回 `data.list.components`,
8
+ `portal +home-apply` 与 `portal_home_layout.py` 只吃 `config.components`
9
+ ② uuid 缺失:`home-apply` 按 `$.config.components[i].uuid` 定位组件,
10
+ 该字段在 home-get 里叫 `id`;一 strip 就报
11
+ `Error: JSON $.config.components[0].uuid 不能为空`
12
+ ③ 伪失败:只传 config(不含 banners)时,CLI 回读会报
13
+ 「首页 config 写入后的读回与目标不一致」——组件其实已写入;
14
+ 真判据是再 home-get 逐组件比对
15
+
16
+ 本脚本把「探测 CLI → home-get → 归一化 → 按方案清单布局 → apply → 回读校验」串成一条命令,
17
+ 失败即以非 0 退出;日志由 guard.py 机械写,不手抄结果。
18
+
19
+ 用法
20
+ python3 portal_home_apply.py --portal <uuid> --modules DEMO-BLUEPRINT.json
21
+ python3 portal_home_apply.py --portal <uuid> --modules BLUEPRINT.json --dry-run
22
+ python3 portal_home_apply.py --portal <uuid> --modules BLUEPRINT.json --demo-root /path/to/demo
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import datetime
29
+ import json
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ import sys
34
+
35
+ HERE = os.path.dirname(os.path.abspath(__file__))
36
+ sys.path.insert(0, HERE)
37
+
38
+ import portal_home_layout as phl # noqa: E402 (同目录复用布局/校验口径)
39
+
40
+ CANDIDATES = [
41
+ os.path.expanduser("~/.npm-global/bin/soke-cli"),
42
+ "/usr/local/bin/soke-cli",
43
+ os.path.expanduser("~/.workbuddy/binaries/node/cli-connector-packages/bin/soke-cli"),
44
+ ]
45
+
46
+
47
+ def find_cli(explicit: str | None = None) -> str | None:
48
+ """按候选顺序找**可执行**的 CLI。
49
+
50
+ ⛔ 只判 os.path.exists 不够:CLI 自更新中途会把 bin 换成 `.soke-cli-XXXX` 临时名,
51
+ 此时真实路径消失但目录还在;必须 `os.access(X_OK)` + 能 `--version` 出结果。
52
+ """
53
+ pool = [explicit] if explicit else CANDIDATES
54
+ for path in pool:
55
+ if not path or not os.path.isfile(path) or not os.access(path, os.X_OK):
56
+ continue
57
+ try:
58
+ proc = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=60)
59
+ except Exception:
60
+ continue
61
+ if proc.returncode == 0 and "version" in (proc.stdout + proc.stderr).lower():
62
+ return path
63
+ return None
64
+
65
+
66
+ def call(cli: str, args: list[str], timeout: int = 180) -> tuple[int, str]:
67
+ proc = subprocess.run([cli] + args, capture_output=True, text=True, timeout=timeout)
68
+ return proc.returncode, (proc.stdout or "") + (proc.stderr or "")
69
+
70
+
71
+ def parse_json(text: str) -> dict:
72
+ """CLI 可能把 banner 打到 stderr,取第一个 '{' 起的片段解析。"""
73
+ start = text.find("{")
74
+ if start < 0:
75
+ raise SystemExit("❌ 输出里没有 JSON:" + text[:200])
76
+ return json.loads(text[start:])
77
+
78
+
79
+ def normalize(doc: dict, portal_id: str) -> dict:
80
+ """两种来源统一成 {portal_id, config:{components}},并**保留 id**(apply 靠它定位)。"""
81
+ comps = None
82
+ if isinstance(doc.get("config"), dict) and isinstance(doc["config"].get("components"), list):
83
+ comps = doc["config"]["components"]
84
+ elif isinstance(doc.get("data"), dict):
85
+ comps = ((doc["data"].get("list") or {}).get("components")) or None
86
+ if not comps:
87
+ raise SystemExit("❌ 快照无 components(期望 config.components 或 data.list.components)")
88
+ for c in comps:
89
+ if not c.get("id") and c.get("uuid"):
90
+ c["id"] = c["uuid"] # 反向兼容:导出结构用 uuid 时补 id
91
+ missing = [c.get("component_name") for c in comps if not c.get("id")]
92
+ if missing:
93
+ raise SystemExit(f"❌ 组件缺 id/uuid,apply 必报 uuid 空:{missing[:5]}")
94
+ return {"portal_id": portal_id, "source": "home-get",
95
+ "exported_at": datetime.datetime.now().isoformat(timespec="seconds"),
96
+ "config": {"components": comps}}
97
+
98
+
99
+ def run(portal: str, modules: str | None, demo_root: str, cli: str, dry_run: bool) -> int:
100
+ order, source, pending = phl.load_order(modules)
101
+ if not order:
102
+ print(f"口径:{source}")
103
+ for item in pending:
104
+ print(" -", item)
105
+ print("PENDING:保留原首页,不调用 home-apply;需明确单门户模块清单")
106
+ return 3
107
+ rc, out = call(cli, ["portal", "+home-get", "--id", portal, "--format", "json"])
108
+ if rc != 0:
109
+ print(out[:400])
110
+ return 2
111
+ before = normalize(parse_json(out), portal)
112
+ os.makedirs(demo_root, exist_ok=True)
113
+ bpath = os.path.join(demo_root, "snapshot.home.before-apply.json")
114
+ json.dump(before, open(bpath, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
115
+
116
+ comps, rows, pend, changed = phl.build(before, order)
117
+ pend = pending + pend
118
+ print(f"口径:{source}")
119
+ print(f"开关变更 {len(changed)} 项:" + (", ".join(changed[:12]) if changed else "无"))
120
+ if pend:
121
+ print("⚠️ 待处理:")
122
+ for p in pend:
123
+ print(" -", p)
124
+
125
+ layout = phl.apply(before, comps)
126
+ lpath = os.path.join(demo_root, "layout.home.apply.json")
127
+ json.dump(layout, open(lpath, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
128
+ if dry_run:
129
+ print(f"[dry-run] 未写入平台;layout={lpath}")
130
+ return 0
131
+
132
+ rc, out = call(cli, ["portal", "+home-apply", "--id", portal, "--file", lpath, "--force",
133
+ "--format", "json"], timeout=300)
134
+ # config-only 传入的 readback 必然报 banner diff,属伪失败:以回读为准
135
+ note = ""
136
+ if rc != 0:
137
+ if "读回与目标不一致" in out:
138
+ note = "apply 报「读回与目标不一致」= config-only 伪失败(banners 未随包),以回读为准"
139
+ else:
140
+ print(out[:400])
141
+ return 2
142
+ print("apply:", "OK" if rc == 0 else "PSEUDO-FAIL(已按回读判定)" + ("|" + note if note else ""))
143
+
144
+ rc, out = call(cli, ["portal", "+home-get", "--id", portal, "--format", "json"])
145
+ if rc != 0:
146
+ print(out[:400])
147
+ return 2
148
+ after = normalize(parse_json(out), portal)
149
+ apath = os.path.join(demo_root, "snapshot.home.after-apply.json")
150
+ json.dump(after, open(apath, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
151
+
152
+ on = [r for r in rows if r["state"] == "ON"]
153
+ vrc = phl.verify(on, after)
154
+ print(f"\n快照:{bpath}\n {apath}\n布局:{lpath}")
155
+ return vrc
156
+
157
+
158
+ def self_test() -> int:
159
+ import tempfile
160
+ fails = []
161
+
162
+ def ck(cond, label):
163
+ if not cond:
164
+ fails.append(label)
165
+
166
+ demo_home = {"data": {"list": {"components": [
167
+ {"component_name": "ContainerView", "id": "ID-0", "is_show": "true", "props": {}},
168
+ {"component_name": "SwiperBanner", "id": "ID-1", "is_show": "true", "props": {}},
169
+ {"component_name": "TaskList", "id": "ID-2", "is_show": "true", "props": {}},
170
+ {"component_name": "NewsArrange", "id": "ID-3", "is_show": "false", "props": {"pc_show": False}},
171
+ {"component_name": "LearnMap", "id": "ID-4", "is_show": "false", "props": {"pc_show": False}},
172
+ {"component_name": "MyExam", "id": "ID-5", "is_show": "false", "props": {"pc_show": False}},
173
+ ]}}}
174
+
175
+ norm = normalize(demo_home, "P1")
176
+ ck(norm["portal_id"] == "P1", "portal_id 应透传")
177
+ ck(all(c.get("id") for c in norm["config"]["components"]), "归一化必须保留 id(uuid 空是硬错)")
178
+
179
+ # uuid→id 反向兼容
180
+ rev = {"config": {"components": [{"component_name": "X", "uuid": "U1", "is_show": "false", "props": {}}]}}
181
+ ck(normalize(rev, "P2")["config"]["components"][0]["id"] == "U1", "uuid 应补成 id")
182
+
183
+ with tempfile.TemporaryDirectory() as td:
184
+ mod = os.path.join(td, "mods.json")
185
+ json.dump({"modules": [{"component": "SwiperBanner"},
186
+ {"component": "TaskList"},
187
+ {"component": "NewsArrange"},
188
+ {"component": "LearnMap"}]},
189
+ open(mod, "w"), ensure_ascii=False)
190
+ order, source, _ = phl.load_order(mod)
191
+ ck(len(order) == 4, "模块清单应解析 4 项")
192
+ comps, rows, _, _ = phl.build(norm, order)
193
+ ck([c["component_name"] for c in comps if c["is_show"] == "true"]
194
+ == ["ContainerView", "SwiperBanner", "TaskList", "NewsArrange", "LearnMap"],
195
+ "开启集合/顺序不符")
196
+ ck(any(c["component_name"] == "MyExam" and c["is_show"] == "false" for c in comps),
197
+ "清单外组件应被关闭")
198
+ layout = phl.apply(norm, comps)
199
+ ck("config" in layout and "components" in layout["config"], "apply 产出结构错")
200
+ ck(phl.verify([r for r in rows if r["state"] == "ON"], layout) == 0, "同文档 verify 应 PASS")
201
+ from unittest.mock import patch
202
+ json.dump({"modules": []}, open(mod, "w", encoding="utf-8"))
203
+ with patch(__name__ + ".call") as mocked_call:
204
+ ck(run("P1", None, td, "unused-cli", False) == 3 and not mocked_call.called,
205
+ "缺模块参数应报告待明确且不调用平台")
206
+ with patch(__name__ + ".call") as mocked_call:
207
+ ck(run("P1", mod, td, "unused-cli", False) == 3, "空模块应报告待明确")
208
+ ck(not mocked_call.called, "空模块不得调用平台或覆盖原配置")
209
+ json.dump({"portals": [{"modules": ["TaskList"]}, {"modules": ["MyExam"]}]},
210
+ open(mod, "w", encoding="utf-8"))
211
+ with patch(__name__ + ".call") as mocked_call:
212
+ ck(run("P1", mod, td, "unused-cli", False) == 3 and not mocked_call.called,
213
+ "多门户应显式报告限制且不得执行首个")
214
+
215
+ ck(find_cli("/definitely/not/exists") is None, "不存在的 CLI 应返回 None")
216
+
217
+ if fails:
218
+ print(json.dumps({"ok": False, "fails": fails}, ensure_ascii=False, indent=2))
219
+ return 2
220
+ print(json.dumps({"ok": True, "assertions": 14}, ensure_ascii=False))
221
+ return 0
222
+
223
+
224
+ def main() -> int:
225
+ ap = argparse.ArgumentParser()
226
+ ap.add_argument("--portal", help="门户 uuid")
227
+ ap.add_argument("--modules", help="BLUEPRINT 或模块清单 JSON")
228
+ ap.add_argument("--demo-root", default=os.getcwd())
229
+ ap.add_argument("--cli")
230
+ ap.add_argument("--dry-run", action="store_true")
231
+ ap.add_argument("--self-test", action="store_true")
232
+ args = ap.parse_args()
233
+
234
+ if args.self_test:
235
+ return self_test()
236
+ if not args.portal:
237
+ ap.print_help()
238
+ return 4
239
+ if not args.modules:
240
+ return run(args.portal, None, args.demo_root, args.cli or "", args.dry_run)
241
+
242
+ cli = find_cli(args.cli)
243
+ if not cli:
244
+ print(json.dumps({
245
+ "ok": False, "error": "CLI 不可用",
246
+ "fix": ["node ~/.npm-global/lib/node_modules/@sokeai/cli/scripts/install.js",
247
+ "ln -sf ../lib/node_modules/@sokeai/cli/scripts/run.js ~/.npm-global/bin/soke-cli",
248
+ "~/.npm-global/bin/soke-cli --version"],
249
+ }, ensure_ascii=False, indent=2))
250
+ return 3
251
+ return run(args.portal, args.modules, args.demo_root, cli, args.dry_run)
252
+
253
+
254
+ if __name__ == "__main__":
255
+ sys.exit(main())
@@ -0,0 +1,398 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """portal_home_layout.py — 门户首页「模块清单」排序与显隐(demo-init / portal-setup 消费)
4
+
5
+ 用途
6
+ 把 `portal +home-export` 导出的首页快照,按**方案要求的模块清单**(BLUEPRINT
7
+ `portals[0].modules[]`)重排 + 收口显隐,产出可直接 `portal +home-apply --force`
8
+ 的 JSON,并打印逐行判定(不靠肉眼)。仅支持单门户;多门户须明确拆分。
9
+
10
+ 两种口径
11
+ ① 方案驱动:`--modules <DEMO-BLUEPRINT.json>`
12
+ 读单个门户的 `modules[]`,顺序即渲染顺序;清单内开、清单外关。
13
+ ② 未指定或空模块清单:保留原首页配置,报告待明确;不补默认业务区块。
14
+
15
+ 硬约束
16
+ - 只改白名单字段:`is_show`(字符串)、`props.pc_show` / `props.mobile_show`(布尔)、
17
+ 以及 modules 里显式给了 `title` 且带 `--allow-title-change` 时的 `props.title`;
18
+ 其余字段 deep-copy 原样回写。
19
+ - 清单外组件一律三开关置关(否则插在中间会破坏顺序);`ContainerView`(页面背景容器)
20
+ 是结构位,保持原相对顺序置顶、不动开关。
21
+ - 清单内组件在快照里缺失 → 不新增(平台组件造不出来),打印 MISSING 并计入 pending。
22
+ - 移动端专属组件(MOBILE_ONLY,实测 `pc_show` 恒 False)只开 is_show + mobile_show,
23
+ `pc_show` 保持原值——强行置 True 会做出一个 PC 端不存在的区块。
24
+
25
+ 用法
26
+ python3 portal_home_layout.py --in snapshot.home.json --modules DEMO-BLUEPRINT.json --out layout.home.json
27
+ python3 portal_home_layout.py --in snapshot.home.json --modules modules.json --dry-run
28
+ python3 portal_home_layout.py --in snapshot.home.json # 未指定模块 → 原样保留并待明确
29
+ python3 portal_home_layout.py --in snapshot.home.json --modules BLUEPRINT.json --verify snapshot.home.after.json
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import copy
36
+ import json
37
+ import os
38
+ import sys
39
+
40
+ # 结构位:不参与排序,保持原相对顺序置顶,三开关不动
41
+ STRUCTURAL = {"ContainerView"}
42
+
43
+ # 移动端专属:平台实测 pc_show 恒 False,开启时不动 pc_show
44
+ MOBILE_ONLY = {"ImageLink", "operateActive", "resumptionList"}
45
+
46
+ WHITELIST_PROPS = ("pc_show", "mobile_show")
47
+
48
+ # 组件中文名(快照里没有时用于日志;也是方案关键词映射的落点,见 references/portal-modules.md)
49
+ COMPONENT_LABELS = {
50
+ "SwiperBanner": "banner", "ActionList": "金刚区", "CheckInArea": "签到区",
51
+ "NewUser": "新员工专区", "TaskList": "我的任务", "LearnCourse": "在学课程",
52
+ "OfflineTraining": "线下培训", "KnowledgeList": "知识库", "RecommendLectors": "推荐讲师",
53
+ "OutstandingMember": "优秀党员", "MyExam": "我的考试", "LearnMap": "学习地图",
54
+ "NewsArrange": "我的必修", "Compulsory": "我的选修", "QuestionnaireList": "调查评估",
55
+ "NewsList": "新闻资讯", "SubPlatform": "学习子平台", "IndexIntegral": "积分兑换",
56
+ "OutLink": "外部链接", "RankList": "积分排行", "ScoreList": "学分排行",
57
+ "CourseList": "推荐课程", "Weike": "微课制作", "ImageLink": "图片链接",
58
+ "TrainRequiredList": "培训需求", "platformFeaturedCourses": "平台精选课",
59
+ "specialCourse": "专题课", "operateActive": "运营活动", "resumptionList": "复学任务",
60
+ "efficiency": "我的测评", "specialArea": "学习专区", "ContainerView": "容器",
61
+ }
62
+
63
+
64
+ def load_components(doc: dict):
65
+ cfg = doc.get("config")
66
+ if isinstance(cfg, dict) and isinstance(cfg.get("components"), list):
67
+ return cfg["components"]
68
+ if isinstance(doc.get("components"), list):
69
+ return doc["components"]
70
+ raise SystemExit("❌ 快照无 components:期望 config.components(home-export 原始结构)")
71
+
72
+
73
+ def load_order(path: str | None):
74
+ """返回 (order 列表, 来源说明, pending)。order 项 = (component, label, title|None)。"""
75
+ if not path:
76
+ return [], "保留原首页(未指定 --modules)", ["待明确:未指定模块,保持现有排序和开关,不自动补业务区块"]
77
+
78
+ doc = json.load(open(path, encoding="utf-8"))
79
+ if isinstance(doc, dict) and len(doc.get("portals") or []) > 1:
80
+ return [], "保留原首页(多门户尚未选择目标)", ["待明确:脚本仅支持单门户,不能静默只取 portals[0];请提供单门户蓝图或该门户的模块清单"]
81
+ if isinstance(doc, list):
82
+ raw = doc
83
+ elif isinstance(doc, dict) and isinstance(doc.get("modules"), list):
84
+ raw = doc["modules"]
85
+ elif isinstance(doc, dict) and isinstance(doc.get("portals"), list) and doc["portals"]:
86
+ raw = (doc["portals"][0] or {}).get("modules") or []
87
+ else:
88
+ raw = []
89
+
90
+ order, pending, seen = [], [], set()
91
+ for item in raw:
92
+ if isinstance(item, str):
93
+ comp, label, title = item, COMPONENT_LABELS.get(item, item), None
94
+ elif isinstance(item, dict):
95
+ comp = item.get("component") or item.get("component_name") or ""
96
+ label = item.get("label") or COMPONENT_LABELS.get(comp, comp)
97
+ title = item.get("title") or None
98
+ else:
99
+ continue
100
+ if not comp or comp in STRUCTURAL:
101
+ continue
102
+ if comp in seen:
103
+ pending.append(f"{label}({comp}) 在模块清单里重复,只取首次出现")
104
+ continue
105
+ seen.add(comp)
106
+ order.append((comp, label, title))
107
+
108
+ if not order:
109
+ pending.append("待明确:模块清单未指定、为空或无可用组件,保持原首页,不自动补业务区块")
110
+ return [], "保留原首页(无明确模块清单)", pending
111
+ return order, f"方案模块清单({len(order)} 项,来自 {path})", pending
112
+
113
+
114
+ def set_switches(comp: dict, on: bool) -> None:
115
+ """三开关同设:is_show 字符串,pc/mobile 布尔;移动端专属组件不动 pc_show。"""
116
+ comp["is_show"] = "true" if on else "false"
117
+ props = comp.setdefault("props", {})
118
+ if (comp.get("component_name") or "") in MOBILE_ONLY:
119
+ props["mobile_show"] = bool(on)
120
+ else:
121
+ props["pc_show"] = bool(on)
122
+ props["mobile_show"] = bool(on)
123
+
124
+
125
+ def build(doc: dict, order):
126
+ """返回 (新 components 列表, 判定行, pending 列表, 开关变更)。"""
127
+ comps = load_components(doc)
128
+ work = copy.deepcopy(comps)
129
+ if not order:
130
+ return work, [], ["待明确:无明确模块清单,保留原首页顺序、标题与全部开关"], []
131
+ before_state = {
132
+ id(c): (str(c.get("is_show")), (c.get("props") or {}).get("pc_show"),
133
+ (c.get("props") or {}).get("mobile_show"))
134
+ for c in work
135
+ }
136
+
137
+ by_name: dict[str, list[dict]] = {}
138
+ for c in work:
139
+ by_name.setdefault(c.get("component_name") or "", []).append(c)
140
+
141
+ structural = [c for c in work if (c.get("component_name") or "") in STRUCTURAL]
142
+ used_ids = {id(c) for c in structural}
143
+
144
+ ordered, rows, pending = [], [], []
145
+
146
+ for seq, (name, label, title) in enumerate(order, start=1):
147
+ bucket = [c for c in by_name.get(name, []) if id(c) not in used_ids]
148
+ if not bucket:
149
+ pending.append(f"{label}({name}) 快照中不存在——平台无该组件,禁止新增(改挂首页可承载的同义组件或降级到导航/金刚区)")
150
+ rows.append({"seq": seq, "name": name, "label": label, "title": title, "state": "MISSING"})
151
+ continue
152
+ comp = bucket[0]
153
+ used_ids.add(id(comp))
154
+ if title:
155
+ comp.setdefault("props", {})["title"] = title
156
+ set_switches(comp, True)
157
+ ordered.append(comp)
158
+ rows.append({"seq": seq, "name": name, "label": label,
159
+ "title": (comp.get("props") or {}).get("title"), "state": "ON"})
160
+
161
+ rest = [c for c in work if id(c) not in used_ids]
162
+ for c in rest:
163
+ set_switches(c, False)
164
+
165
+ new_components = structural + ordered + rest
166
+ for i, row in enumerate(rows):
167
+ row["index"] = len(structural) + i
168
+
169
+ changed = []
170
+ for c in new_components:
171
+ prev = before_state.get(id(c))
172
+ cur = (str(c.get("is_show")), (c.get("props") or {}).get("pc_show"),
173
+ (c.get("props") or {}).get("mobile_show"))
174
+ if prev != cur:
175
+ changed.append(f"{(c.get('component_name') or '')}→{cur[0]}")
176
+
177
+ return new_components, rows, pending, changed
178
+
179
+
180
+ def apply(doc: dict, new_components: list[dict]) -> dict:
181
+ out = copy.deepcopy(doc)
182
+ if isinstance(out.get("config"), dict) and isinstance(out["config"].get("components"), list):
183
+ out["config"]["components"] = new_components
184
+ else:
185
+ out["components"] = new_components
186
+ return out
187
+
188
+
189
+ def print_rows(rows, pending, changed, source, total):
190
+ print(f"口径:{source}")
191
+ print(f"{'#':>2} {'component_name':<22}{'业务名':<12}{'标题':<14}状态")
192
+ for r in rows:
193
+ print(f"{r['seq']:>2} {r['name']:<22}{r['label']:<12}{str(r.get('title')):<14}{r['state']}")
194
+ print(f"\n开关变更:{len(changed)} 项 " + (", ".join(changed[:12]) + (" …" if len(changed) > 12 else "") if changed else ""))
195
+ if pending:
196
+ print("\n⚠️ 待处理:")
197
+ for p in pending:
198
+ print(" -", p)
199
+ on = len([r for r in rows if r["state"] == "ON"])
200
+ print(f"\n{'✅ OK' if not pending else '⚠️ PENDING'}:清单 {total} 项,实际落位 {on} 项,缺失 {total - on} 项")
201
+
202
+
203
+ def verify(expected_rows, doc: dict) -> int:
204
+ comps = load_components(doc)
205
+ names = [c.get("component_name") for c in comps]
206
+ structural_n = sum(1 for n in names if n in STRUCTURAL)
207
+ body = names[structural_n:]
208
+ bad = 0
209
+ print(f"{'#':>2} {'期望':<22}{'实际':<22}标题判定 开关判定")
210
+ for i, row in enumerate(expected_rows):
211
+ exp = row["name"]
212
+ act = body[i] if i < len(body) else "(空)"
213
+ comp = comps[structural_n + i] if structural_n + i < len(comps) else {}
214
+ props = comp.get("props") or {}
215
+ title_ok = (not row.get("title")) or props.get("title") == row["title"]
216
+ if exp in MOBILE_ONLY:
217
+ sw_ok = (comp.get("is_show") == "true" and props.get("mobile_show") is True)
218
+ else:
219
+ sw_ok = (comp.get("is_show") == "true" and props.get("pc_show") is True
220
+ and props.get("mobile_show") is True)
221
+ name_ok = exp == act
222
+ bad += 0 if (name_ok and title_ok and sw_ok) else 1
223
+ print(f"{row['seq']:>2} {exp:<22}{str(act):<22}{'OK' if title_ok else 'MISMATCH':<8}{'OK' if sw_ok else 'MISMATCH'}")
224
+ tail = body[len(expected_rows):]
225
+ off_bad = []
226
+ for name in tail:
227
+ idx = names.index(name)
228
+ c = comps[idx]
229
+ p = c.get("props") or {}
230
+ if c.get("is_show") != "false" or p.get("mobile_show") is not False:
231
+ off_bad.append(name)
232
+ print(f"\n清单外组件 {len(tail)} 项," + ("全部已关 ✅" if not off_bad else f"未关:{off_bad} ❌"))
233
+ print(f"\n{'✅ VERIFY PASS' if bad == 0 and not off_bad else '❌ VERIFY FAIL'}(顺序/标题/开关不符 {bad} 项)")
234
+ return 0 if bad == 0 and not off_bad else 1
235
+
236
+
237
+ def self_test() -> int:
238
+ """离线桩测试:三段纯逻辑(模块清单解析 / 重排与三开关 / apply 保留结构位)。
239
+
240
+ 对应的真实事故:只改 is_show 前端仍不显示(三开关)、nav 空就跳过、
241
+ 清单外组件没关(把方案要的模块关掉或把方案没写的留着)、ContainerView 被挪位。
242
+ """
243
+ import tempfile
244
+ cases = []
245
+
246
+ def ck(cond, label):
247
+ cases.append((bool(cond), label))
248
+
249
+ def snap(names, on=False):
250
+ return {"config": {"components": [
251
+ {"component_name": n, "is_show": "true" if on else "false",
252
+ "props": {"pc_show": on, "mobile_show": on}} for n in names]}}
253
+
254
+ # 1. set_switches 三开关
255
+ c = {"component_name": "banner", "props": {}}
256
+ set_switches(c, True)
257
+ ck(c["is_show"] == "true" and c["props"]["pc_show"] is True and c["props"]["mobile_show"] is True,
258
+ "set_switches 开=三开关同设")
259
+ set_switches(c, False)
260
+ ck(c["is_show"] == "false" and c["props"]["pc_show"] is False and c["props"]["mobile_show"] is False,
261
+ "set_switches 关=三开关同关")
262
+ m = {"component_name": "operateActive", "props": {}}
263
+ set_switches(m, True)
264
+ ck("pc_show" not in m["props"] and m["props"]["mobile_show"] is True, "移动端专属不动 pc_show")
265
+
266
+ # 2. load_components 两种结构 + 缺结构报错
267
+ ck(len(load_components({"config": {"components": [{"component_name": "a"}]}})) == 1, "load_components config.components")
268
+ ck(len(load_components({"components": [{"component_name": "a"}]})) == 1, "load_components 顶层 components")
269
+ try:
270
+ load_components({})
271
+ ck(False, "load_components 缺结构报错")
272
+ except SystemExit:
273
+ ck(True, "load_components 缺结构报错")
274
+
275
+ # 3. build:顺序 + 清单内开 + 清单外关 + 缺失记 pending
276
+ doc = snap(["banner", "ContainerView", "examListBox", "courseListBox", "lecturerLearnList"])
277
+ order = [("examListBox", "我的考试", None), ("courseListBox", "推荐课程", None),
278
+ ("learnMapList", "学习地图", None)]
279
+ comps, rows, pending, _ = build(doc, order)
280
+ names = [x["component_name"] for x in comps]
281
+ ck(names[0] == "ContainerView", "build 结构位 ContainerView 仍在首位")
282
+ ck(names[1:3] == ["examListBox", "courseListBox"], "build 按清单重排")
283
+ on_names = [r["name"] for r in rows if r["state"] == "ON"]
284
+ ck(on_names == ["examListBox", "courseListBox"], "build 清单内开启")
285
+ ck(any(r["state"] == "MISSING" for r in rows) and pending, "build 缺失组件记 MISSING+pending")
286
+ tail = [x for x in comps if x["component_name"] not in ("ContainerView", "examListBox", "courseListBox")]
287
+ ck(all(x["is_show"] == "false" for x in tail), "build 清单外全部关闭")
288
+ ck(rows[0].get("index") == 1, "build index 跳过结构位")
289
+
290
+ # 4. 标题:方案给了才覆盖,不给不动
291
+ doc2 = snap(["banner", "NewUser"])
292
+ _, rows2, _, _ = build(doc2, [("banner", "Banner", "品牌横幅"), ("NewUser", "新员工专区", None)])
293
+ ck(rows2[0]["title"] == "品牌横幅", "build 方案标题写入")
294
+ ck(rows2[1]["title"] in (None, "新员工专区"), "build 未指定标题不硬改")
295
+
296
+ # 5. load_order:字符串 / dict / 单门户模块 / 空 → 保留配置
297
+ with tempfile.TemporaryDirectory(prefix="home-layout-") as tmp:
298
+ p1 = os.path.join(tmp, "a.json")
299
+ p2 = os.path.join(tmp, "b.json")
300
+ p3 = os.path.join(tmp, "c.json")
301
+ p4 = os.path.join(tmp, "d.json")
302
+ json.dump(["banner", "examListBox"], open(p1, "w", encoding="utf-8"))
303
+ json.dump({"modules": [{"component": "courseListBox", "label": "推荐课程"}]},
304
+ open(p2, "w", encoding="utf-8"))
305
+ json.dump({"portals": [{"modules": [{"component": "learnMapList"}]}]},
306
+ open(p3, "w", encoding="utf-8"))
307
+ json.dump({"modules": []}, open(p4, "w", encoding="utf-8"))
308
+ o1, _, _ = load_order(p1)
309
+ o2, _, _ = load_order(p2)
310
+ o3, _, _ = load_order(p3)
311
+ o4, src4, _ = load_order(p4)
312
+ ck([x[0] for x in o1] == ["banner", "examListBox"], "load_order 字符串清单")
313
+ ck([x[0] for x in o2] == ["courseListBox"] and o2[0][1] == "推荐课程", "load_order dict 清单取 label")
314
+ ck([x[0] for x in o3] == ["learnMapList"], "load_order 取 portals[0].modules")
315
+ ck(o4 == [] and "保留" in src4, "load_order 空清单保留原配置")
316
+ o5, src5, pend5 = load_order(None)
317
+ ck(o5 == [] and "保留" in src5 and pend5, "load_order 无参数保留原配置并报告待明确")
318
+ json.dump({"portals": [{"modules": ["banner"]}, {"modules": ["MyExam"]}]},
319
+ open(p4, "w", encoding="utf-8"))
320
+ om, _, pm = load_order(p4)
321
+ ck(om == [] and any("单门户" in item for item in pm), "load_order 多门户不静默丢弃其余")
322
+ original = snap(["banner", "ContainerView", "TaskList"], on=True)
323
+ untouched, untouched_rows, untouched_pending, changes = build(original, [])
324
+ ck(untouched == load_components(original) and not untouched_rows and untouched_pending and not changes,
325
+ "build 空清单保留排序和原开关,不全关也不全开")
326
+ # 重复项只取首次
327
+ p5 = os.path.join(tmp, "e.json")
328
+ json.dump(["banner", "banner"], open(p5, "w", encoding="utf-8"))
329
+ o6, _, pend6 = load_order(p5)
330
+ ck([x[0] for x in o6] == ["banner"] and pend6, "load_order 重复项去重+pending")
331
+
332
+ # 6. build 幂等:同一快照连跑两次,第二次无开关变更
333
+ doc3 = snap(["banner", "examListBox"])
334
+ order3 = [("banner", "Banner", None), ("examListBox", "我的考试", None)]
335
+ c1, _, _, _ = build(doc3, order3)
336
+ doc3b = copy.deepcopy(doc3)
337
+ doc3b["config"]["components"] = c1
338
+ _, _, _, changed2 = build(doc3b, order3)
339
+ ck(changed2 == [], "build 幂等(二次无变更)")
340
+
341
+ # 7. apply 不改 count/其它字段
342
+ doc4 = snap(["banner"])
343
+ doc4["config"]["count"] = 3
344
+ comps, _, _, _ = build(doc4, [("banner", "Banner", None)])
345
+ out = apply(doc4, comps)
346
+ ck(out["config"]["count"] == 3 and out["config"]["components"][0]["component_name"] == "banner",
347
+ "apply 保留其它字段")
348
+
349
+ failed = [label for ok_, label in cases if not ok_]
350
+ for ok_, label in cases:
351
+ print(" %s %s" % ("PASS" if ok_ else "FAIL", label))
352
+ print(json.dumps({"ok": not failed, "assertions": len(cases)}, ensure_ascii=False))
353
+ return 0 if not failed else 1
354
+
355
+
356
+ def main() -> int:
357
+ if "--self-test" in sys.argv[1:]:
358
+ return self_test()
359
+ ap = argparse.ArgumentParser()
360
+ ap.add_argument("--in", dest="src", required=True, help="home-export 导出的快照 JSON")
361
+ ap.add_argument("--modules", help="单门户 BLUEPRINT 或模块清单 JSON(缺省保留原首页并待明确)")
362
+ ap.add_argument("--out", dest="dst", help="改后落盘路径(默认 <in>.layout.json)")
363
+ ap.add_argument("--dry-run", action="store_true", help="只打印判定表,不落盘")
364
+ ap.add_argument("--verify", dest="verify_path", help="apply 后回读 JSON:核对顺序/标题/三开关")
365
+ args = ap.parse_args()
366
+
367
+ order, source, order_pending = load_order(args.modules)
368
+
369
+ if args.verify_path:
370
+ if not order:
371
+ for item in order_pending:
372
+ print(item)
373
+ print("PENDING:无明确模块清单,未执行目标布局验证")
374
+ return 3
375
+ _, rows, _, _ = build(json.load(open(args.src, encoding="utf-8")), order)
376
+ return verify([r for r in rows if r["state"] == "ON"],
377
+ json.load(open(args.verify_path, encoding="utf-8")))
378
+
379
+ doc = json.load(open(args.src, encoding="utf-8"))
380
+ new_components, rows, pending, changed = build(doc, order)
381
+ print_rows(rows, pending + order_pending, changed, source, len(order))
382
+ if args.dry_run:
383
+ print("\n[dry-run] 未落盘")
384
+ return 0
385
+
386
+ dst = args.dst or (args.src.rsplit(".json", 1)[0] + ".layout.json")
387
+ with open(dst, "w", encoding="utf-8") as f:
388
+ json.dump(apply(doc, new_components), f, ensure_ascii=False, indent=2)
389
+ print(f"\n落盘:{dst}")
390
+ if not order:
391
+ print("PENDING:原配置已原样保留;先明确模块需求,不执行 home-apply")
392
+ return 3
393
+ print("下一步:\"$SOKE_CLI\" portal +home-apply --id <uuid> --file '%s' --force --format json" % dst)
394
+ return 0
395
+
396
+
397
+ if __name__ == "__main__":
398
+ sys.exit(main())