@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,512 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """taxonomy_build.py — 课程/题库分类构建与三模块已有默认分类解析
4
+
5
+ 针对 2026-10-20 dx 实战日志的三处塌陷重修:
6
+ ① 26 个节点直建撞 [11004] 后,脚本拿不到父 uuid → 12 个 L2 全部 "parent L1 missing, skip"
7
+ ② 建完才手工回读校准,多花一轮脚本重写
8
+ ③ 无汇总,日志里看不出 created / reused / failed 各多少
9
+
10
+ 课程/题库分类遵守「直建不比对」,撞名才惰性回读复用。地图/考试/培训班
11
+ 不创建分类树,仅按模块查询一次已有默认分类并缓存,缺失记pending。
12
+
13
+ 用法:
14
+ "<PY>" taxonomy_build.py --blueprint <DEMO-BLUEPRINT.json> --out-dir <demo 目录>
15
+ --dry-run 只打印待建清单,不发任何请求
16
+ --self-test 用桩响应自证解析/复用/续跑逻辑(不连平台)
17
+ --only course|pool|map
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import re
24
+ import shutil
25
+ import subprocess
26
+ import sys
27
+ import tempfile
28
+ import time
29
+ from datetime import datetime
30
+
31
+ from category_bind import resolve_default_categories
32
+
33
+ DUP_MARKS = ("11004", "分类名已存在", "已存在", "already exist")
34
+ KIND_ORDER = {"course_l1": 0, "course_l2": 1, "pool": 2, "map": 3}
35
+
36
+
37
+ # ---------------------------------------------------------------- 基础工具
38
+
39
+ def jload(s):
40
+ """从带 banner 的 stdout 里取第一个 JSON 对象(禁用 re.search 贪婪截取)。"""
41
+ i = s.find("{")
42
+ if i < 0:
43
+ return None
44
+ try:
45
+ return json.JSONDecoder().raw_decode(s, i)[0]
46
+ except Exception:
47
+ return None
48
+
49
+
50
+ def rows_of(data):
51
+ """兼容 data / data.rows / data.list / data.list.all 四种返回形态。"""
52
+ if isinstance(data, list):
53
+ return data
54
+ if not isinstance(data, dict):
55
+ return []
56
+ for k in ("rows", "list", "all"):
57
+ v = data.get(k)
58
+ if isinstance(v, list):
59
+ return v
60
+ if isinstance(v, dict):
61
+ for k2 in ("rows", "list", "all"):
62
+ if isinstance(v.get(k2), list):
63
+ return v[k2]
64
+ return []
65
+
66
+
67
+ def title_of(row):
68
+ if not isinstance(row, dict):
69
+ return None
70
+ return row.get("title") or row.get("name")
71
+
72
+
73
+ def pick_uuid(obj):
74
+ """create 返回结构不统一:data.uuid / data.info.uuid / data.id。"""
75
+ d = obj.get("data") if isinstance(obj, dict) else None
76
+ if isinstance(d, dict):
77
+ info = d.get("info")
78
+ for cand in (d.get("uuid"), (info or {}).get("uuid") if isinstance(info, dict) else None, d.get("id")):
79
+ if isinstance(cand, str) and cand.strip() and cand != "empty":
80
+ return cand.strip()
81
+ if isinstance(d, str) and d.strip():
82
+ return d.strip()
83
+ return None
84
+
85
+
86
+ def is_dup(out, err):
87
+ blob = (out or "") + (err or "")
88
+ return any(m in blob for m in DUP_MARKS)
89
+
90
+
91
+ def short(s, n=120):
92
+ s = (s or "").replace("\n", " ").strip()
93
+ return s if len(s) <= n else s[:n] + "…"
94
+
95
+
96
+ def now():
97
+ return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
98
+
99
+
100
+ # ---------------------------------------------------------------- CLI 调用
101
+
102
+ class Cli:
103
+ def __init__(self, exe, log_path=None, dry=False):
104
+ self.exe = exe
105
+ self.log_path = log_path
106
+ self.dry = dry
107
+ self.calls = 0
108
+
109
+ def log(self, module, msg):
110
+ line = "[%s] [%s] %s" % (now(), module, msg)
111
+ print(line)
112
+ if self.log_path:
113
+ with open(self.log_path, "a", encoding="utf-8") as f:
114
+ f.write(line + "\n")
115
+
116
+ def run(self, args, timeout=90):
117
+ if self.dry:
118
+ return 0, "", ""
119
+ self.calls += 1
120
+ return _RUNNER([self.exe] + args, timeout)
121
+
122
+
123
+ def _default_runner(argv, timeout=90):
124
+ p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
125
+ return p.returncode, p.stdout or "", p.stderr or ""
126
+
127
+
128
+ _RUNNER = _default_runner
129
+
130
+
131
+ # ---------------------------------------------------------------- 惰性回读
132
+
133
+ class Lookup:
134
+ """撞名时才查的同层兄弟索引(不是建前全量预检)。"""
135
+
136
+ def __init__(self, cli):
137
+ self.cli = cli
138
+ self._course = {}
139
+ self._pool = None
140
+
141
+ def course_children(self, parent, refresh=False):
142
+ if parent in self._course and not refresh:
143
+ return self._course[parent]
144
+ rc, out, err = self.cli.run(["course", "+category-tree", "--parent-id", str(parent), "--format", "json"])
145
+ obj = jload(out) or {}
146
+ idx = {}
147
+ for row in rows_of(obj.get("data")):
148
+ t, u = title_of(row), (row.get("uuid") or row.get("id"))
149
+ if t and u:
150
+ idx[t] = u
151
+ self._course[parent] = idx
152
+ return idx
153
+
154
+ def pool_all(self, refresh=False):
155
+ if self._pool is not None and not refresh:
156
+ return self._pool
157
+ rc, out, err = self.cli.run(["exam", "+list-pool-categories", "--format", "json"])
158
+ obj = jload(out) or {}
159
+ self._pool = {title_of(r): (r.get("uuid") or r.get("id"))
160
+ for r in rows_of(obj.get("data")) if title_of(r)}
161
+ return self._pool
162
+
163
+
164
+ # ---------------------------------------------------------------- 待建清单
165
+
166
+ def build_plan(tax, only=None):
167
+ todo, seq = [], 0
168
+ if only in (None, "course"):
169
+ for t in tax.get("course") or []:
170
+ l1 = t.get("l1")
171
+ if not l1:
172
+ continue
173
+ seq += 1
174
+ todo.append({"seq": seq, "kind": "course_l1", "name": l1, "parent": "1", "group": l1})
175
+ for l2 in t.get("l2") or []:
176
+ seq += 1
177
+ todo.append({"seq": seq, "kind": "course_l2", "name": l2,
178
+ "parent": "L1:" + l1, "group": l1})
179
+ if only in (None, "pool"):
180
+ for q in tax.get("question_pool") or []:
181
+ name = q.get("name") if isinstance(q, dict) else q
182
+ if not name:
183
+ continue
184
+ seq += 1
185
+ todo.append({"seq": seq, "kind": "pool", "name": name, "parent": "1", "group": None})
186
+ # 学习地图、培训班、考试仅复用平台已有默认分类,不进入待建清单。
187
+ return todo
188
+
189
+
190
+ def create_argv(node, parent_uuid, desc):
191
+ k, name = node["kind"], node["name"]
192
+ if k == "course_l1":
193
+ # 一级根节点传 1(传 0 成幽灵分类,见偏差表 #22)
194
+ return ["course", "+category-create", "--title", name, "--path", "1", "--format", "json"]
195
+ if k == "course_l2":
196
+ return ["course", "+category-create", "--title", name, "--path", str(parent_uuid), "--format", "json"]
197
+ if k == "pool":
198
+ return ["exam", "+create-pool-category", "--title", name, "--parent-id", "1", "--format", "json"]
199
+ raise ValueError("仅课程/题库分类允许创建:%s" % k)
200
+
201
+
202
+ def reuse_lookup(node, parent_uuid, lk):
203
+ """撞名后的唯一补救路径:查同层兄弟,按 title 精确取 uuid。"""
204
+ k = node["kind"]
205
+ if k == "course_l1":
206
+ return lk.course_children("1", refresh=True).get(node["name"])
207
+ if k == "course_l2":
208
+ return lk.course_children(str(parent_uuid), refresh=True).get(node["name"])
209
+ if k == "pool":
210
+ return lk.pool_all(refresh=True).get(node["name"])
211
+ raise ValueError("不允许为三模块创建或撞名回读分类:%s" % k)
212
+
213
+
214
+ # ---------------------------------------------------------------- 主流程
215
+
216
+ def run(args):
217
+ bp = json.load(open(args.blueprint, encoding="utf-8"))
218
+ tax = bp.get("taxonomies") or {}
219
+ out_dir = os.path.abspath(args.out_dir)
220
+ os.makedirs(out_dir, exist_ok=True)
221
+ log_path = os.path.join(out_dir, "run.log")
222
+
223
+ todo = build_plan(tax, args.only)
224
+ plan_path = os.path.join(out_dir, "categories.jsonl")
225
+ with open(plan_path, "w", encoding="utf-8") as f:
226
+ for row in todo:
227
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
228
+
229
+ cli = Cli(args.soke, log_path=log_path, dry=args.dry_run)
230
+ cli.log("taxonomy-setup", "plan total=%d (course=%d pool=%d map=%d) dry_run=%s"
231
+ % (len(todo),
232
+ sum(1 for t in todo if t["kind"].startswith("course")),
233
+ sum(1 for t in todo if t["kind"] == "pool"),
234
+ sum(1 for t in todo if t["kind"] == "map"),
235
+ args.dry_run))
236
+
237
+ if args.dry_run:
238
+ for t in todo:
239
+ print(" %2d %-10s %-28s parent=%s" % (t["seq"], t["kind"], t["name"], t["parent"]))
240
+ return 0
241
+
242
+ cur_path = os.path.join(out_dir, "categories-cur.jsonl")
243
+ done = {}
244
+ if os.path.exists(cur_path):
245
+ for line in open(cur_path, encoding="utf-8"):
246
+ line = line.strip()
247
+ if not line:
248
+ continue
249
+ try:
250
+ r = json.loads(line)
251
+ except Exception:
252
+ continue
253
+ if r.get("uuid") and any(n["seq"] == r.get("seq") and n["kind"] == r.get("kind")
254
+ and n["name"] == r.get("name") for n in todo):
255
+ done[r["seq"]] = r
256
+ cli.log("taxonomy-setup", "resume: categories-cur.jsonl 已记 %d 条" % len(done))
257
+
258
+ l1_uuid = {r["name"]: r["uuid"] for r in done.values() if r["kind"] == "course_l1"}
259
+ lk = Lookup(cli)
260
+ stats = {"created": 0, "reused": 0, "failed": 0}
261
+ failed = []
262
+
263
+ for node in todo:
264
+ if node["seq"] in done:
265
+ if node["kind"] == "course_l1":
266
+ l1_uuid[node["name"]] = done[node["seq"]]["uuid"]
267
+ continue
268
+
269
+ parent_uuid = None
270
+ if node["kind"] == "course_l2":
271
+ parent_uuid = l1_uuid.get(node["group"])
272
+ if not parent_uuid:
273
+ # 父缺失也先惰性回读根层补齐,绝不再 "skip"
274
+ parent_uuid = lk.course_children("1", refresh=True).get(node["group"])
275
+ if parent_uuid:
276
+ l1_uuid[node["group"]] = parent_uuid
277
+ cli.log("taxonomy-setup", "lazy-parent %s -> %s" % (node["group"], parent_uuid))
278
+ if not parent_uuid:
279
+ stats["failed"] += 1
280
+ failed.append((node["seq"], node["name"], "parent-missing"))
281
+ cli.log("taxonomy-setup", "FAIL %s parent-missing(%s)" % (node["name"], node["group"]))
282
+ continue
283
+
284
+ argv = create_argv(node, parent_uuid, args.map_desc)
285
+ rc, out, err = cli.run(argv)
286
+ uuid = pick_uuid(jload(out) or {}) if out.strip() else None
287
+ source = "created"
288
+
289
+ if not uuid:
290
+ if is_dup(out, err):
291
+ uuid = reuse_lookup(node, parent_uuid, lk)
292
+ source = "reused"
293
+ if uuid:
294
+ cli.log("taxonomy-setup", "reuse %-10s %-28s uuid=%s" % (node["kind"], node["name"], uuid))
295
+ if not uuid:
296
+ # 撞名但回读也没命中 / 空输出 / 其它错误:重试 1 次
297
+ time.sleep(args.sleep)
298
+ rc, out, err = cli.run(argv)
299
+ uuid = pick_uuid(jload(out) or {}) if out.strip() else None
300
+ if not uuid and is_dup(out, err):
301
+ uuid = reuse_lookup(node, parent_uuid, lk)
302
+ source = "reused" if uuid else source
303
+
304
+ if uuid:
305
+ rec = {"seq": node["seq"], "kind": node["kind"], "name": node["name"],
306
+ "requested_name": node["name"], "uuid": uuid, "source": source}
307
+ with open(cur_path, "a", encoding="utf-8") as f:
308
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
309
+ done[node["seq"]] = rec
310
+ if node["kind"] == "course_l1":
311
+ l1_uuid[node["name"]] = uuid
312
+ stats["created" if source == "created" else "reused"] += 1
313
+ else:
314
+ stats["failed"] += 1
315
+ failed.append((node["seq"], node["name"], (err or out or "empty").strip()[:80]))
316
+ cli.log("taxonomy-setup", "FAIL %-10s %-28s %s | out=%s | err=%s"
317
+ % (node["kind"], node["name"], rc, short(out, 80), short(err, 80)))
318
+
319
+ time.sleep(args.sleep)
320
+
321
+ # ---- 收尾校准(平台会二次生成 uuid,映射表一律写校准值)
322
+ calibrated, drift = 0, 0
323
+ if args.only in (None, "course"):
324
+ root = lk.course_children("1", refresh=True)
325
+ for node in todo:
326
+ if node["kind"] != "course_l1" or node["seq"] not in done:
327
+ continue
328
+ hit = root.get(node["name"])
329
+ if hit:
330
+ calibrated += 1
331
+ if hit != done[node["seq"]]["uuid"]:
332
+ drift += 1
333
+ done[node["seq"]]["uuid"] = hit
334
+ l1_uuid[node["name"]] = hit
335
+ for node in todo:
336
+ if node["kind"] != "course_l2" or node["seq"] not in done:
337
+ continue
338
+ pu = l1_uuid.get(node["group"])
339
+ if not pu:
340
+ continue
341
+ hit = lk.course_children(pu, refresh=True).get(node["name"])
342
+ if hit:
343
+ calibrated += 1
344
+ if hit != done[node["seq"]]["uuid"]:
345
+ drift += 1
346
+ done[node["seq"]]["uuid"] = hit
347
+
348
+ # ---- 落 taxonomy-map.json
349
+ map_path = os.path.join(out_dir, "taxonomy-map.json")
350
+ tmap = json.load(open(map_path, encoding="utf-8")) if os.path.exists(map_path) else {}
351
+ tmap.update({"blueprint_id": bp.get("meta", {}).get("blueprint_id"),
352
+ "generated_at": now(), "missing": [], "stats": stats})
353
+ for segment in ("course", "question_pool", "learning_map", "exam", "training_class"):
354
+ tmap.setdefault(segment, [])
355
+ if args.only in (None, "course"):
356
+ tmap["course"] = []
357
+ if args.only in (None, "pool"):
358
+ tmap["question_pool"] = []
359
+ groups = {"maps"} if args.only == "map" else None
360
+ if args.only in (None, "map"):
361
+ resolve_default_categories(bp, tmap, cli, groups=groups)
362
+ tmap["pending"] = [{"tree": tree, "status": "pending", "reason": row.get("reason", "缺已有分类")}
363
+ for tree, row in (tmap.get("default_categories") or {}).items()
364
+ if not row.get("uuid")]
365
+ by_seq = done
366
+ seq_of = {n["seq"]: n for n in todo}
367
+ for node in todo:
368
+ if node["kind"] != "course_l1":
369
+ continue
370
+ rec = by_seq.get(node["seq"])
371
+ entry = {"l1": node["name"], "l1_uuid": rec["uuid"] if rec else None,
372
+ "reused": bool(rec and rec.get("source") == "reused"), "l2": []}
373
+ if not entry["l1_uuid"]:
374
+ tmap["missing"].append(node["name"])
375
+ for child in todo:
376
+ if child["kind"] == "course_l2" and child["group"] == node["name"]:
377
+ c = by_seq.get(child["seq"])
378
+ entry["l2"].append({"name": child["name"], "uuid": c["uuid"] if c else None})
379
+ if not (c and c["uuid"]):
380
+ tmap["missing"].append(node["name"] + "/" + child["name"])
381
+ tmap["course"].append(entry)
382
+ for node in todo:
383
+ if node["kind"] == "pool":
384
+ rec = by_seq.get(node["seq"])
385
+ tmap["question_pool"].append({"name": node["name"], "uuid": rec["uuid"] if rec else None,
386
+ "source": rec.get("source") if rec else None})
387
+
388
+ map_path = os.path.join(out_dir, "taxonomy-map.json")
389
+ with open(map_path, "w", encoding="utf-8") as f:
390
+ json.dump(tmap, f, ensure_ascii=False, indent=2)
391
+
392
+ total_nodes = sum(1 + len(e["l2"]) for e in tmap["course"]) + len(tmap["question_pool"])
393
+ filled = total_nodes - len(tmap["missing"])
394
+ cli.log("taxonomy-setup",
395
+ "END total=%d created=%d reused=%d failed=%d calibrated=%d/%d drift=%d uuid_filled=%d/%d calls=%d"
396
+ % (len(todo), stats["created"], stats["reused"], stats["failed"], calibrated,
397
+ len([n for n in todo if n["kind"].startswith("course")]), drift, filled, total_nodes, cli.calls))
398
+
399
+ print("[summary] total=%d created=%d reused=%d failed=%d uuid_filled=%d/%d -> %s"
400
+ % (len(todo), stats["created"], stats["reused"], stats["failed"], filled, total_nodes, map_path))
401
+ if tmap["missing"]:
402
+ print("[missing] " + ", ".join(tmap["missing"]))
403
+ if failed:
404
+ print("[failed] " + "; ".join("%s(%s)" % (n, r) for _, n, r in failed))
405
+ return 0 if filled == total_nodes else 2
406
+
407
+
408
+ # ---------------------------------------------------------------- 自检
409
+
410
+ def self_test():
411
+ """桩响应覆盖:create 成功 / [11004] 复用 / 父层惰性补齐 / 续跑 / 校准漂移。"""
412
+ calls = {"created": [], "reused": [], "argv": []}
413
+ existing = {"1": {"01 新员工必修课": "U-L1-1"}, "U-L1-1": {"文化与制度": "U-L2-1"}}
414
+ state = {"dup_l1": True}
415
+
416
+ def fake(argv, timeout=90):
417
+ calls["argv"].append(argv)
418
+ verb = " ".join(argv[1:3])
419
+ if "category-create" in verb:
420
+ title = argv[argv.index("--title") + 1]
421
+ path = argv[argv.index("--path") + 1]
422
+ if title in existing.get(path, {}):
423
+ return 1, "", "Error: [11004] 分类名已存在"
424
+ uid = "U-NEW-%d" % (len(calls["created"]) + 1)
425
+ calls["created"].append(title)
426
+ existing.setdefault(path, {})[title] = uid
427
+ return 0, json.dumps({"code": 200, "data": {"uuid": uid}}, ensure_ascii=False), ""
428
+ if "create-pool-category" in verb or "+create-category" in verb:
429
+ title = argv[argv.index("--title") + 1]
430
+ uid = "U-MISC-%d" % (len(calls["created"]) + 1)
431
+ calls["created"].append(title)
432
+ if "pool" in verb:
433
+ existing.setdefault("__pool__", {})[title] = uid
434
+ else:
435
+ existing.setdefault("__map__", {})[title] = uid
436
+ return 0, json.dumps({"code": 200, "data": {"uuid": uid}}, ensure_ascii=False), ""
437
+ if "list-pool-categories" in verb or "list-categories" in verb:
438
+ key = "__pool__" if "pool" in verb else "__map__"
439
+ rows = [{"title": t, "uuid": u} for t, u in existing.get(key, {}).items()]
440
+ return 0, json.dumps({"code": 200, "data": {"list": rows}}, ensure_ascii=False), ""
441
+ if "category-tree" in verb:
442
+ pid = argv[argv.index("--parent-id") + 1]
443
+ rows = [{"title": t, "uuid": u} for t, u in existing.get(pid, {}).items()]
444
+ return 0, json.dumps({"code": 200, "data": {"rows": rows}}, ensure_ascii=False), ""
445
+ return 0, json.dumps({"code": 200, "data": {"list": []}}), ""
446
+
447
+ global _RUNNER
448
+ _RUNNER = fake
449
+ tmp = tempfile.mkdtemp(prefix="taxonomy-selftest-")
450
+ bp = {"meta": {"blueprint_id": "selftest"},
451
+ "taxonomies": {"course": [{"l1": "01 新员工必修课", "l2": ["文化与制度", "产品入门"]}],
452
+ "question_pool": [{"name": "[DEMO] 通用题库分类"}],
453
+ "learning_map": [{"name": "新员工学习地图"}]},
454
+ "maps": [{"name": "地图A"}, {"name": "地图B"}],
455
+ "exams": [{"name": "考试A"}], "projects": [{"name": "培训班A"}]}
456
+ p = os.path.join(tmp, "DEMO-BLUEPRINT.json")
457
+ json.dump(bp, open(p, "w", encoding="utf-8"), ensure_ascii=False)
458
+
459
+ class A:
460
+ blueprint = p
461
+ out_dir = tmp
462
+ soke = "soke-cli"
463
+ sleep = 0
464
+ dry_run = False
465
+ only = None
466
+ map_desc = "selftest"
467
+
468
+ rc = run(A)
469
+ tmap = json.load(open(os.path.join(tmp, "taxonomy-map.json"), encoding="utf-8"))
470
+ l1 = tmap["course"][0]
471
+ checks = [
472
+ ("L1 复用既有分类", l1["l1_uuid"] == "U-L1-1"),
473
+ ("L1 未被 skip", l1["l1_uuid"] is not None),
474
+ ("L2 文化与制度 复用", any(x["uuid"] == "U-L2-1" for x in l1["l2"])),
475
+ ("L2 产品入门 已新建", all(x["uuid"] for x in l1["l2"])),
476
+ ("missing 为空", tmap["missing"] == []),
477
+ ("stats 有 reuse", tmap["stats"]["reused"] >= 1),
478
+ ("三模块分类不进入待建清单", not any(n["kind"] == "map" for n in build_plan(bp["taxonomies"]))),
479
+ ("三模块零分类create", not any(a[1:3] in (["learning-map", "+create-category"],
480
+ ["training-class", "+category-create"], ["exam", "+create-category"]) for a in calls["argv"])),
481
+ ("缺已有分类pending不阻塞课程题库", rc == 0 and len(tmap["pending"]) == 3),
482
+ ("默认分类各模块查询一次", sum(a[1:3] == ["learning-map", "+list-categories"] for a in calls["argv"]) == 1),
483
+ ]
484
+ ok = True
485
+ for name, passed in checks:
486
+ print((" PASS " if passed else " FAIL ") + name)
487
+ ok = ok and passed
488
+ print("[self-test]", "PASS" if ok else "FAIL", "| tmp=", tmp)
489
+ _RUNNER = _default_runner
490
+ return 0 if ok else 1
491
+
492
+
493
+ def main():
494
+ ap = argparse.ArgumentParser()
495
+ ap.add_argument("--blueprint")
496
+ ap.add_argument("--out-dir")
497
+ ap.add_argument("--soke", default=os.environ.get("SOKE_CLI") or shutil.which("soke-cli") or "soke-cli")
498
+ ap.add_argument("--sleep", type=float, default=3.0)
499
+ ap.add_argument("--only", choices=["course", "pool", "map"])
500
+ ap.add_argument("--map-desc", default="", help="兼容旧调用;地图分类不创建,此参数忽略")
501
+ ap.add_argument("--dry-run", action="store_true")
502
+ ap.add_argument("--self-test", action="store_true")
503
+ a = ap.parse_args()
504
+ if a.self_test:
505
+ return self_test()
506
+ if not a.blueprint or not a.out_dir:
507
+ ap.error("--blueprint 与 --out-dir 必填(或用 --self-test)")
508
+ return run(a)
509
+
510
+
511
+ if __name__ == "__main__":
512
+ sys.exit(main())
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file