@sokeai/cli 1.0.115 → 1.0.117

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 (64) hide show
  1. package/package.json +1 -1
  2. package/skills/multi/demo-init/CHANGELOG.md +1241 -0
  3. package/skills/multi/demo-init/README.md +137 -0
  4. package/skills/multi/demo-init/SKILL.legacy.md +307 -0
  5. package/skills/multi/demo-init/assets/placeholder.pptx +0 -0
  6. package/skills/multi/demo-init/references/anti-patterns.md +83 -0
  7. package/skills/multi/demo-init/references/asset-design.md +230 -0
  8. package/skills/multi/demo-init/references/asset-spec.md +94 -0
  9. package/skills/multi/demo-init/references/blueprint-schema.md +174 -0
  10. package/skills/multi/demo-init/references/cli-onboarding.md +207 -0
  11. package/skills/multi/demo-init/references/cli-shared.md +183 -0
  12. package/skills/multi/demo-init/references/contracts.md +34 -0
  13. package/skills/multi/demo-init/references/course-setup.md +265 -0
  14. package/skills/multi/demo-init/references/demo-defaults.md +132 -0
  15. package/skills/multi/demo-init/references/demo-verify.md +355 -0
  16. package/skills/multi/demo-init/references/exam-setup.md +245 -0
  17. package/skills/multi/demo-init/references/gates-matrix.md +38 -0
  18. package/skills/multi/demo-init/references/map-setup.md +283 -0
  19. package/skills/multi/demo-init/references/plan-parse.md +185 -0
  20. package/skills/multi/demo-init/references/platform-access.md +55 -0
  21. package/skills/multi/demo-init/references/platform-commands.md +510 -0
  22. package/skills/multi/demo-init/references/point-setup.md +308 -0
  23. package/skills/multi/demo-init/references/portal-modules.md +130 -0
  24. package/skills/multi/demo-init/references/portal-setup.md +342 -0
  25. package/skills/multi/demo-init/references/project-setup.md +173 -0
  26. package/skills/multi/demo-init/references/run-protocol.md +208 -0
  27. package/skills/multi/demo-init/references/taxonomy-setup.md +101 -0
  28. package/skills/multi/demo-init/scripts/assign_backfill.py +281 -0
  29. package/skills/multi/demo-init/scripts/blueprint_lint.py +693 -0
  30. package/skills/multi/demo-init/scripts/blueprint_write.py +390 -0
  31. package/skills/multi/demo-init/scripts/category_bind.py +303 -0
  32. package/skills/multi/demo-init/scripts/category_create.py +748 -0
  33. package/skills/multi/demo-init/scripts/category_reassign.py +405 -0
  34. package/skills/multi/demo-init/scripts/category_verify.py +373 -0
  35. package/skills/multi/demo-init/scripts/cli_kit.py +597 -0
  36. package/skills/multi/demo-init/scripts/cli_probe.py +205 -0
  37. package/skills/multi/demo-init/scripts/course_build.py +857 -0
  38. package/skills/multi/demo-init/scripts/course_cover_repair.py +243 -0
  39. package/skills/multi/demo-init/scripts/doc_lint.py +619 -0
  40. package/skills/multi/demo-init/scripts/dup_cleanup.py +299 -0
  41. package/skills/multi/demo-init/scripts/dup_scan.py +368 -0
  42. package/skills/multi/demo-init/scripts/exam_build.py +551 -0
  43. package/skills/multi/demo-init/scripts/extract_docx.py +370 -0
  44. package/skills/multi/demo-init/scripts/gen_assets.py +1366 -0
  45. package/skills/multi/demo-init/scripts/guard.py +1272 -0
  46. package/skills/multi/demo-init/scripts/map_rebuild.py +391 -0
  47. package/skills/multi/demo-init/scripts/oss_image_upload.py +367 -0
  48. package/skills/multi/demo-init/scripts/portal_build.py +450 -0
  49. package/skills/multi/demo-init/scripts/portal_home_apply.py +255 -0
  50. package/skills/multi/demo-init/scripts/portal_home_layout.py +398 -0
  51. package/skills/multi/demo-init/scripts/project_build.py +309 -0
  52. package/skills/multi/demo-init/scripts/rebuild_taxonomy_map.py +100 -0
  53. package/skills/multi/demo-init/scripts/scope_plan.py +387 -0
  54. package/skills/multi/demo-init/scripts/selftest_all.py +211 -0
  55. package/skills/multi/demo-init/scripts/stock_probe.py +452 -0
  56. package/skills/multi/demo-init/scripts/taxonomy_build.py +512 -0
  57. package/skills/multi/demo-init-4.1.0.zip +0 -0
  58. package/skills/multi/demo-init-4.1.1.zip +0 -0
  59. package/skills/multi/demo-init-4.1.2.zip +0 -0
  60. package/skills/multi/demo-init-4.1.3.zip +0 -0
  61. package/skills/multi/ziQIJJpL +0 -0
  62. package/skills/multi/ziRsINis +0 -0
  63. package/skills/multi/ziUjKWRm +0 -0
  64. package/skills/multi/zipFWfuj +0 -0
@@ -0,0 +1,748 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """category_create.py — 授客AI 三类分类树幂等构建器(soke-category-builder v1.0.0)
4
+
5
+ 覆盖三棵树,命令与语义各不相同(详见 references/cli-reference.md):
6
+
7
+ 正式考试分类 exam +create-category --title / --parent-id 1(根)/ --path ["祖先uuid",...]
8
+ 学习地图分类 learning-map +create-category --title / --parent-id 0(根,且只支持一级)
9
+ 培训班分类 training-class +category-create --title / --path '["祖先uuid",...]'(根不传 path)
10
+
11
+ 核心约束(全部由 2026-10-20 实测得出,不是推断):
12
+ ① 第一条 CLI 永远是 create,不做建前全量预检;撞 [11004] 才做同层惰性回读复用
13
+ ② 平台会二次生成 uuid,收尾必须回读校准,映射表写校准值
14
+ ③ [12000] 无操作权限是账号级拦截 —— 立刻停掉整棵树,不要重试刷日志
15
+ ④ 培训班删除/列表偶发 10s 超时,需幂等重试
16
+
17
+ 用法:
18
+ PY scripts/category_create.py --spec spec.json --out-dir <dir>
19
+ PY scripts/category_create.py --tree training_class --names "01 新员工培养,02 认证项目" --out-dir <dir>
20
+ PY scripts/category_create.py --spec spec.json --out-dir <dir> --dry-run # 不发请求
21
+ PY scripts/category_create.py --spec spec.json --out-dir <dir> --verify-only # 只回读校验
22
+ PY scripts/category_create.py --out-dir <dir> --cleanup --yes # 删掉本脚本建过的节点
23
+ PY scripts/category_create.py --self-test # 桩响应自证,不连平台
24
+ """
25
+
26
+ import argparse
27
+ import json
28
+ import os
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+ import time
34
+ from datetime import datetime
35
+
36
+ # ---------------------------------------------------------------- 常量与树定义
37
+
38
+ DUP_MARKS = ("11004", "分类名已存在", "已存在", "already exist")
39
+ PERM_MARKS = ("12000", "无操作权限", "无权访问", "无权限")
40
+ TIMEOUT_MARKS = ("timeout", "timed out", "CURL error [28]", "[500]")
41
+
42
+ TREE_LABEL = {
43
+ "exam": "正式考试分类",
44
+ "learning_map": "学习地图分类",
45
+ "training_class": "培训班分类",
46
+ }
47
+
48
+ # 读侧根父 ID 三棵树统一为 "1";写侧根语义各不相同,见各 create_argv
49
+ ROOT_PARENT_READ = "1"
50
+
51
+ MAX_DEPTH = {"exam": 3, "learning_map": 1, "training_class": 5}
52
+
53
+
54
+ # ---------------------------------------------------------------- 基础工具
55
+
56
+ def jload(s):
57
+ """从带 banner 的 stdout 里取第一个 JSON 对象(禁止贪婪正则截取)。"""
58
+ i = s.find("{")
59
+ if i < 0:
60
+ return None
61
+ try:
62
+ return json.JSONDecoder().raw_decode(s, i)[0]
63
+ except Exception:
64
+ return None
65
+
66
+
67
+ def rows_of(data):
68
+ """兼容 data / data.rows / data.list / data.list.all 四种返回形态。"""
69
+ if isinstance(data, list):
70
+ return data
71
+ if not isinstance(data, dict):
72
+ return []
73
+ for k in ("rows", "list", "all"):
74
+ v = data.get(k)
75
+ if isinstance(v, list):
76
+ return v
77
+ if isinstance(v, dict):
78
+ for k2 in ("rows", "list", "all"):
79
+ if isinstance(v.get(k2), list):
80
+ return v[k2]
81
+ return []
82
+
83
+
84
+ def title_of(row):
85
+ return (row.get("title") or row.get("name")) if isinstance(row, dict) else None
86
+
87
+
88
+ def pick_uuid(obj):
89
+ """create 返回结构不统一:data.uuid / data.info.uuid / data.id。"""
90
+ d = obj.get("data") if isinstance(obj, dict) else None
91
+ if isinstance(d, dict):
92
+ info = d.get("info")
93
+ cands = [d.get("uuid")]
94
+ if isinstance(info, dict):
95
+ cands.append(info.get("uuid"))
96
+ cands.append(d.get("id"))
97
+ for cand in cands:
98
+ if isinstance(cand, str) and cand.strip() and cand.strip() != "empty":
99
+ return cand.strip()
100
+ if isinstance(d, str) and d.strip():
101
+ return d.strip()
102
+ return None
103
+
104
+
105
+ def hit(blob_tuple, marks):
106
+ blob = (blob_tuple[0] or "") + (blob_tuple[1] or "")
107
+ return any(m in blob for m in marks)
108
+
109
+
110
+ def resp_ok(out, err):
111
+ """成功判定不能看 stderr 是否为空:CLI 会把「发现新版本可用」banner 打到 stderr。"""
112
+ if "Error:" in (out or "") and not jload(out or ""):
113
+ return False
114
+ obj = jload(out or "") or {}
115
+ code = str(obj.get("code") or "")
116
+ if code in ("200", "201", "202", "204"):
117
+ return True
118
+ if isinstance(obj.get("data"), int) and obj.get("data") >= 1:
119
+ return True
120
+ return False
121
+
122
+
123
+ def short(s, n=120):
124
+ s = (s or "").replace("\n", " ").strip()
125
+ return s if len(s) <= n else s[:n] + "…"
126
+
127
+
128
+ def now():
129
+ return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
130
+
131
+
132
+ # ---------------------------------------------------------------- CLI 封装
133
+
134
+ def _default_runner(argv, timeout=90):
135
+ p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
136
+ return p.returncode, p.stdout or "", p.stderr or ""
137
+
138
+
139
+ _RUNNER = _default_runner
140
+
141
+
142
+ class Cli:
143
+ def __init__(self, exe, log_path=None, dry=False):
144
+ self.exe = exe
145
+ self.log_path = log_path
146
+ self.dry = dry
147
+ self.calls = 0
148
+
149
+ def log(self, module, msg):
150
+ line = "[%s] [%s] %s" % (now(), module, short(msg, 200))
151
+ print(line)
152
+ if self.log_path:
153
+ with open(self.log_path, "a", encoding="utf-8") as f:
154
+ f.write(line + "\n")
155
+
156
+ def run(self, args, timeout=90, retries=0, sleep=2.0):
157
+ """retries 仅用于超时类错误(培训班接口偶发 10s 超时)。"""
158
+ if self.dry:
159
+ return 0, "", ""
160
+ last = (0, "", "")
161
+ for i in range(retries + 1):
162
+ self.calls += 1
163
+ try:
164
+ rc, out, err = _RUNNER([self.exe] + args, timeout)
165
+ except subprocess.TimeoutExpired:
166
+ rc, out, err = 124, "", "timeout after %ss" % timeout
167
+ last = (rc, out, err)
168
+ if not (rc != 0 and hit((out, err), TIMEOUT_MARKS)):
169
+ return last
170
+ if i < retries:
171
+ time.sleep(sleep * (i + 1))
172
+ return last
173
+
174
+
175
+ # ---------------------------------------------------------------- 树适配器
176
+
177
+ class Tree:
178
+ """三棵树的差异全部收敛在这里:根语义 / 创建 argv / 同层回读 / 删除。"""
179
+
180
+ def __init__(self, name, cli):
181
+ self.name = name
182
+ self.cli = cli
183
+ self._child_cache = {}
184
+
185
+ # ---- 读:同层子节点 {title: uuid}
186
+ def children(self, parent_uuid, refresh=False):
187
+ key = parent_uuid or ROOT_PARENT_READ
188
+ if key in self._child_cache and not refresh:
189
+ return self._child_cache[key]
190
+ if self.name == "exam":
191
+ idx = self._children_exam(key)
192
+ elif self.name == "learning_map":
193
+ idx = self._children_map(key)
194
+ else:
195
+ idx = self._children_training_class(key)
196
+ self._child_cache[key] = idx
197
+ return idx
198
+
199
+ def _children_exam(self, parent):
200
+ rc, out, err = self.cli.run(
201
+ ["exam", "+list-categories", "--page-size", "200", "--format", "json"])
202
+ obj = jload(out) or {}
203
+ idx = {}
204
+ for r in rows_of(obj.get("data")):
205
+ if str(r.get("parent_id") or ROOT_PARENT_READ) != str(parent):
206
+ continue
207
+ t, u = title_of(r), (r.get("uuid") or r.get("id"))
208
+ if t and u:
209
+ idx[t] = u
210
+ return idx
211
+
212
+ def _children_map(self, parent):
213
+ idx, page = {}, 1
214
+ while page <= 10:
215
+ rc, out, err = self.cli.run(
216
+ ["learning-map", "+list-categories", "--page", str(page),
217
+ "--page-size", "100", "--format", "json"])
218
+ obj = jload(out) or {}
219
+ data = obj.get("data") or {}
220
+ rows = rows_of(data)
221
+ for r in rows:
222
+ if str(r.get("parent_id") or ROOT_PARENT_READ) != str(parent):
223
+ continue
224
+ t, u = title_of(r), (r.get("uuid") or r.get("id"))
225
+ if t and u:
226
+ idx[t] = u
227
+ # has_more 只在平台侧翻页时出现;rows 不足一页即停
228
+ if not data.get("has_more") or len(rows) < 100:
229
+ break
230
+ page += 1
231
+ return idx
232
+
233
+ def _children_training_class(self, parent):
234
+ rc, out, err = self.cli.run(
235
+ ["training-class", "+category-tree", "--id", str(parent), "--format", "json"])
236
+ obj = jload(out) or {}
237
+ idx = {}
238
+ for r in rows_of(obj.get("data")):
239
+ t, u = title_of(r), (r.get("uuid") or r.get("id"))
240
+ if t and u:
241
+ idx[t] = u
242
+ return idx
243
+
244
+ # ---- 写:创建 argv(parent_uuid 为 None 表示根)
245
+ def create_argv(self, title, parent_uuid, ancestors):
246
+ if self.name == "exam":
247
+ if not parent_uuid:
248
+ return ["exam", "+create-category", "--title", title,
249
+ "--parent-id", "1", "--format", "json"]
250
+ # 多级以完整祖先路径为准(CLI 帮助明确建议),parent-id 作兜底
251
+ return ["exam", "+create-category", "--title", title,
252
+ "--path", json.dumps(ancestors, ensure_ascii=False), "--format", "json"]
253
+ if self.name == "learning_map":
254
+ return ["learning-map", "+create-category", "--title", title,
255
+ "--parent-id", "0", "--format", "json"]
256
+ # training_class:根必须完全不传 --path,子级传祖先 uuid 数组
257
+ if not parent_uuid:
258
+ return ["training-class", "+category-create", "--title", title]
259
+ return ["training-class", "+category-create", "--title", title,
260
+ "--path", json.dumps(ancestors, ensure_ascii=False)]
261
+
262
+ def create_fallback_argv(self, title, parent_uuid, ancestors):
263
+ """主 argv 非撞名失败时的第二条路(仅 exam 有意义)。"""
264
+ if self.name == "exam" and parent_uuid:
265
+ return ["exam", "+create-category", "--title", title,
266
+ "--parent-id", parent_uuid, "--format", "json"]
267
+ return None
268
+
269
+ # ---- 删:仅 --cleanup 使用
270
+ def delete_argv(self, uuid):
271
+ if self.name == "exam":
272
+ return ["exam", "+delete-category", "--category-id", uuid, "--format", "json"]
273
+ if self.name == "learning_map":
274
+ return ["learning-map", "+delete-category", "--uuid", uuid, "--format", "json"]
275
+ return ["training-class", "+category-delete", "--id", uuid]
276
+
277
+
278
+ # ---------------------------------------------------------------- 规格解析
279
+
280
+ def load_spec(path, tree_name, names):
281
+ """返回 (tree, nodes)。nodes 为 DFS 顺序,含 depth / ancestors / group。"""
282
+ if names:
283
+ raw = {"tree": tree_name, "nodes": [n.strip() for n in names.split(",") if n.strip()]}
284
+ else:
285
+ raw = json.load(open(path, encoding="utf-8"))
286
+
287
+ if isinstance(raw, list):
288
+ tree, body = tree_name, raw
289
+ else:
290
+ tree = raw.get("tree") or tree_name
291
+ body = raw.get("nodes") or raw.get("categories") or []
292
+ if not tree:
293
+ raise SystemExit("spec 缺少 tree 字段,且未用 --tree 指定")
294
+ if tree not in TREE_LABEL:
295
+ raise SystemExit("tree 只能是 %s,收到 %r" % ("/".join(TREE_LABEL), tree))
296
+
297
+ nodes, seq = [], 0
298
+
299
+ def walk(items, depth, ancestors, group_path):
300
+ nonlocal seq
301
+ for it in items:
302
+ if isinstance(it, str):
303
+ # 支持 "一级/二级/三级" 斜杠路径写法
304
+ parts = [p.strip() for p in it.split("/") if p.strip()]
305
+ if len(parts) > 1:
306
+ walk([{"name": parts[0], "children": ["/".join(parts[1:])]}],
307
+ depth, ancestors, group_path)
308
+ continue
309
+ name, kids = it.strip(), []
310
+ else:
311
+ name, kids = (it.get("name") or it.get("title") or "").strip(), it.get("children") or []
312
+ if not name:
313
+ continue
314
+ seq += 1
315
+ gpath = group_path + [name]
316
+ nodes.append({"seq": seq, "name": name, "depth": depth,
317
+ "ancestors": [dict(a) for a in ancestors], "group": "/".join(gpath)})
318
+ if kids:
319
+ walk(kids, depth + 1, ancestors + [{"seq": seq, "name": name}], gpath)
320
+
321
+ walk(body, 1, [], [])
322
+ return tree, nodes
323
+
324
+
325
+ def check_depth(tree, nodes, allow_flat):
326
+ """学习地图分类平台只支持一级:--parent-id 会被忽略(实测)。"""
327
+ deep = [n for n in nodes if n["depth"] > MAX_DEPTH[tree]]
328
+ if not deep:
329
+ return True
330
+ if tree != "learning_map":
331
+ return False
332
+ return bool(allow_flat)
333
+
334
+
335
+ # ---------------------------------------------------------------- 主流程
336
+
337
+ def run(args):
338
+ out_dir = os.path.abspath(args.out_dir)
339
+ os.makedirs(out_dir, exist_ok=True)
340
+ log_path = os.path.join(out_dir, "run.log")
341
+ cli = Cli(args.soke, log_path=log_path, dry=args.dry_run)
342
+ tree_name, nodes = load_spec(args.spec, args.tree, args.names)
343
+
344
+ if not check_depth(tree_name, nodes, args.allow_flat):
345
+ msg = ("%s 最大支持 %d 级,规格里有更深层节点。"
346
+ % (TREE_LABEL[tree_name], MAX_DEPTH[tree_name]))
347
+ if tree_name == "learning_map":
348
+ msg += (" 平台 create 接口忽略 --parent-id(实测 parent_id 恒为 1),"
349
+ "只能建一级;确需多级请在后台 UI 建,或加 --allow-flat 压平执行。")
350
+ print("[error] " + msg)
351
+ cli.log("category-setup", "ABORT depth-exceeded tree=%s" % tree_name)
352
+ return 3
353
+
354
+ plan_path = os.path.join(out_dir, "category-plan.jsonl")
355
+ with open(plan_path, "w", encoding="utf-8") as f:
356
+ for n in nodes:
357
+ f.write(json.dumps(n, ensure_ascii=False) + "\n")
358
+
359
+ by_depth = {}
360
+ for n in nodes:
361
+ by_depth[n["depth"]] = by_depth.get(n["depth"], 0) + 1
362
+ cli.log("category-setup", "plan tree=%s total=%d depth=%s dry_run=%s"
363
+ % (tree_name, len(nodes), dict(sorted(by_depth.items())), args.dry_run))
364
+
365
+ if args.dry_run:
366
+ preview = Tree(tree_name, cli)
367
+ for n in nodes:
368
+ # 预演时祖先还没有 uuid,用名字占位,别把占位符当真参数发给平台
369
+ ph = ["<L%d:%s>" % (n["depth"] - len(n["ancestors"]) + i, a["name"])
370
+ for i, a in enumerate(n["ancestors"])]
371
+ argv = preview.create_argv(n["name"], "P" if n["depth"] > 1 else None, ph)
372
+ print(" %2d L%d %-32s %s" % (n["seq"], n["depth"], n["group"], " ".join(argv)))
373
+ return 0
374
+
375
+ result_path = os.path.join(out_dir, "category-result.jsonl")
376
+ done = {}
377
+ if os.path.exists(result_path):
378
+ for line in open(result_path, encoding="utf-8"):
379
+ line = line.strip()
380
+ if not line:
381
+ continue
382
+ try:
383
+ r = json.loads(line)
384
+ except Exception:
385
+ continue
386
+ if r.get("uuid"):
387
+ done[r["seq"]] = r
388
+ cli.log("category-setup", "resume: category-result.jsonl 已记 %d 条" % len(done))
389
+
390
+ tree = Tree(tree_name, cli)
391
+ stats = {"created": 0, "reused": 0, "failed": 0, "blocked": 0}
392
+ failed, blocked = [], False
393
+
394
+ for node in nodes:
395
+ if node["seq"] in done:
396
+ continue
397
+ if blocked:
398
+ stats["blocked"] += 1
399
+ continue
400
+
401
+ # 父解析:depth1 无父;更深层按祖先链顺序反查已建 uuid
402
+ parent_uuid, ancestors = None, []
403
+ if node["depth"] > 1:
404
+ ok = True
405
+ for a in node["ancestors"]:
406
+ rec = done.get(a["seq"])
407
+ if not rec or not rec.get("uuid"):
408
+ ok = False
409
+ break
410
+ ancestors.append(rec["uuid"])
411
+ parent_uuid = rec["uuid"]
412
+ if not ok or not parent_uuid:
413
+ stats["failed"] += 1
414
+ failed.append((node["seq"], node["group"], "parent-missing"))
415
+ cli.log("category-setup", "FAIL %s parent-missing" % node["group"])
416
+ continue
417
+
418
+ argv = tree.create_argv(node["name"], parent_uuid, ancestors)
419
+ rc, out, err = cli.run(argv, retries=1)
420
+ uuid = pick_uuid(jload(out) or {}) if (out or "").strip() else None
421
+ source = "created"
422
+
423
+ # ---- 权限拦截:账号级,立刻停整棵树
424
+ if not uuid and hit((out, err), PERM_MARKS):
425
+ source = "blocked_permission"
426
+ stats["blocked"] += 1
427
+ blocked = True
428
+ remaining = len(nodes) - node["seq"] + 1
429
+ cli.log("category-setup", "BLOCKED [12000] 无权限建 %s —— 整棵树停,本节点起 %d 个未建;"
430
+ "请用有该模块分类管理权限的账号,或改复用既有分类"
431
+ % (TREE_LABEL[tree_name], remaining))
432
+ with open(result_path, "a", encoding="utf-8") as f:
433
+ f.write(json.dumps({"seq": node["seq"], "name": node["name"], "group": node["group"],
434
+ "uuid": None, "source": source,
435
+ "reason": short(err or out, 100)}, ensure_ascii=False) + "\n")
436
+ continue
437
+
438
+ # ---- 撞名 → 同层惰性回读复用
439
+ if not uuid and hit((out, err), DUP_MARKS):
440
+ uuid = tree.children(parent_uuid, refresh=True).get(node["name"])
441
+ source = "reused"
442
+
443
+ # ---- 主 argv 失败且非撞名 → 兜底 argv(exam 的 parent-id 路径)
444
+ if not uuid and not hit((out, err), DUP_MARKS):
445
+ fb = tree.create_fallback_argv(node["name"], parent_uuid, ancestors)
446
+ if fb:
447
+ rc2, out2, err2 = cli.run(fb, retries=1)
448
+ uuid = pick_uuid(jload(out2) or {}) if (out2 or "").strip() else None
449
+ if not uuid and hit((out2, err2), DUP_MARKS):
450
+ uuid = tree.children(parent_uuid, refresh=True).get(node["name"])
451
+ source = "reused"
452
+ if not uuid:
453
+ out, err = out2, err2
454
+
455
+ if uuid:
456
+ rec = {"seq": node["seq"], "name": node["name"], "group": node["group"],
457
+ "depth": node["depth"], "uuid": uuid, "source": source,
458
+ "parent_uuid": parent_uuid}
459
+ with open(result_path, "a", encoding="utf-8") as f:
460
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
461
+ done[node["seq"]] = rec
462
+ stats["created" if source == "created" else "reused"] += 1
463
+ if source == "reused":
464
+ cli.log("category-setup", "reuse L%d %-28s uuid=%s" % (node["depth"], node["group"], uuid))
465
+ else:
466
+ stats["failed"] += 1
467
+ failed.append((node["seq"], node["group"], short(err or out or "empty", 80)))
468
+ cli.log("category-setup", "FAIL L%d %-28s rc=%s out=%s err=%s"
469
+ % (node["depth"], node["group"], rc, short(out, 80), short(err, 80)))
470
+
471
+ time.sleep(args.sleep)
472
+
473
+ # ---- 收尾校准:平台可能二次生成 uuid,一律以回读为准(按父批量刷新,省接口)
474
+ calibrated, drift = 0, 0
475
+ parents = {(r.get("parent_uuid") or None) for r in done.values()}
476
+ for pu in parents:
477
+ try:
478
+ tree.children(pu, refresh=True)
479
+ except Exception as ex:
480
+ cli.log("category-setup", "calibrate read fail parent=%s %s" % (pu, short(str(ex), 60)))
481
+ for node in nodes:
482
+ rec = done.get(node["seq"])
483
+ if not rec or not rec.get("uuid"):
484
+ continue
485
+ actual = tree.children(rec.get("parent_uuid")).get(node["name"])
486
+ if actual:
487
+ calibrated += 1
488
+ if actual != rec["uuid"]:
489
+ drift += 1
490
+ rec["uuid"] = actual
491
+ if calibrated:
492
+ cli.log("category-setup", "calibrate %d/%d drift=%d" % (calibrated, len(nodes), drift))
493
+
494
+ # ---- 落树 + 报告
495
+ tmap = {"tree": tree_name, "tree_label": TREE_LABEL[tree_name],
496
+ "generated_at": now(), "nodes": [], "missing": [], "stats": stats}
497
+ for node in nodes:
498
+ rec = done.get(node["seq"])
499
+ entry = {"name": node["name"], "group": node["group"], "depth": node["depth"],
500
+ "uuid": (rec or {}).get("uuid"), "source": (rec or {}).get("source"),
501
+ "parent_uuid": (rec or {}).get("parent_uuid")}
502
+ tmap["nodes"].append(entry)
503
+ if not entry["uuid"]:
504
+ tmap["missing"].append(node["group"])
505
+
506
+ map_path = os.path.join(out_dir, "category-tree.json")
507
+ with open(map_path, "w", encoding="utf-8") as f:
508
+ json.dump(tmap, f, ensure_ascii=False, indent=2)
509
+
510
+ filled = len(nodes) - len(tmap["missing"])
511
+ report = {"tree": tree_name, "total": len(nodes), "filled": filled,
512
+ "missing": len(tmap["missing"]), "stats": stats,
513
+ "calibrated": calibrated, "drift": drift,
514
+ "calls": cli.calls, "generated_at": now()}
515
+ with open(os.path.join(out_dir, "category-report.json"), "w", encoding="utf-8") as f:
516
+ json.dump(report, f, ensure_ascii=False, indent=2)
517
+
518
+ cli.log("category-setup",
519
+ "END tree=%s total=%d created=%d reused=%d failed=%d blocked=%d calibrated=%d drift=%d calls=%d"
520
+ % (tree_name, len(nodes), stats["created"], stats["reused"], stats["failed"],
521
+ stats["blocked"], calibrated, drift, cli.calls))
522
+ print("[summary] tree=%s total=%d created=%d reused=%d failed=%d failed_total=%d filled=%d/%d -> %s"
523
+ % (tree_name, len(nodes), stats["created"], stats["reused"], stats["failed"],
524
+ stats["failed"] + stats["blocked"], filled, len(nodes), map_path))
525
+ if tmap["missing"]:
526
+ print("[missing] " + ", ".join(tmap["missing"]))
527
+ if failed:
528
+ print("[failed] " + "; ".join("%s(%s)" % (g, r) for _, g, r in failed))
529
+ if blocked:
530
+ print("[hint] 权限拦截:换有「%s管理」权限的账号,或先复用既有分类" % TREE_LABEL[tree_name])
531
+ return 4
532
+ return 0 if filled == len(nodes) else 2
533
+
534
+
535
+ # ---------------------------------------------------------------- 校验 / 清理
536
+
537
+ def verify(args):
538
+ """只读回读:确认树里每个节点真实存在,且父链正确。"""
539
+ tree_name = args.tree
540
+ map_path = os.path.join(os.path.abspath(args.out_dir), "category-tree.json")
541
+ if not os.path.exists(map_path):
542
+ print("[error] 找不到 %s,先跑一次构建或用 --tree 重建" % map_path)
543
+ return 2
544
+ tmap = json.load(open(map_path, encoding="utf-8"))
545
+ tree_name = tmap.get("tree") or tree_name
546
+ cli = Cli(args.soke)
547
+ tree = Tree(tree_name, cli)
548
+ bad = []
549
+ for n in tmap["nodes"]:
550
+ if not n.get("uuid"):
551
+ bad.append((n["group"], "no-uuid"))
552
+ continue
553
+ sibs = tree.children(n.get("parent_uuid"), refresh=True)
554
+ if sibs.get(n["name"]) != n["uuid"]:
555
+ bad.append((n["group"], "uuid-drift" if sibs.get(n["name"]) else "not-found"))
556
+ print("[verify] %s total=%d ok=%d bad=%d calls=%d"
557
+ % (TREE_LABEL.get(tree_name, tree_name), len(tmap["nodes"]),
558
+ len(tmap["nodes"]) - len(bad), len(bad), cli.calls))
559
+ for g, r in bad:
560
+ print(" BAD %-40s %s" % (g, r))
561
+ return 0 if not bad else 2
562
+
563
+
564
+ def cleanup(args):
565
+ """倒序删除本脚本建过的节点(结果文件里的 uuid),深层先删。"""
566
+ out_dir = os.path.abspath(args.out_dir)
567
+ result_path = os.path.join(out_dir, "category-result.jsonl")
568
+ if not os.path.exists(result_path):
569
+ print("[error] 找不到 %s" % result_path)
570
+ return 2
571
+ recs = []
572
+ for line in open(result_path, encoding="utf-8"):
573
+ line = line.strip()
574
+ if not line:
575
+ continue
576
+ try:
577
+ r = json.loads(line)
578
+ except Exception:
579
+ continue
580
+ if r.get("uuid") and r.get("source") == "created":
581
+ recs.append(r)
582
+ recs.sort(key=lambda r: r.get("depth") or 1, reverse=True)
583
+ if not recs:
584
+ print("[cleanup] 没有本脚本创建的节点(只删 source=created,保护既有分类)")
585
+ return 0
586
+ print("[cleanup] 待删 %d 个(仅 source=created):" % len(recs))
587
+ for r in recs:
588
+ print(" L%s %-40s %s" % (r.get("depth"), r.get("group"), r["uuid"]))
589
+ if not args.yes:
590
+ print("[cleanup] 未加 --yes,仅预览")
591
+ return 0
592
+ cli = Cli(args.soke)
593
+ tree = Tree(args.tree, cli)
594
+ ok = 0
595
+ for r in recs:
596
+ rc, out, err = cli.run(tree.delete_argv(r["uuid"]), retries=2)
597
+ good = rc == 0 and resp_ok(out, err)
598
+ print((" DEL " if good else " FAIL ") + r.get("group", "") + " "
599
+ + ("" if good else short(err or out, 80)))
600
+ ok += 1 if good else 0
601
+ time.sleep(max(args.sleep, 1.0))
602
+ print("[cleanup] deleted=%d/%d calls=%d" % (ok, len(recs), cli.calls))
603
+ return 0 if ok == len(recs) else 2
604
+
605
+
606
+ # ---------------------------------------------------------------- 自检
607
+
608
+ def self_test():
609
+ """桩响应覆盖:新建 / [11004] 复用 / 子级父链 / [12000] 权限拦截 / 续跑。"""
610
+ store = {} # parent -> {title: uuid}
611
+ seq = {"n": 0}
612
+
613
+ def fake(argv, timeout=90):
614
+ cmd = " ".join(argv)
615
+ if "category-create" in cmd or "create-category" in cmd:
616
+ title = argv[argv.index("--title") + 1]
617
+ if "training-class" in cmd:
618
+ parent = "1"
619
+ if "--path" in argv:
620
+ parent = json.loads(argv[argv.index("--path") + 1])[-1]
621
+ elif "learning-map" in cmd:
622
+ parent = "1" # 平台实测:parent-id 被忽略
623
+ else:
624
+ parent = "1"
625
+ if "--path" in argv and json.loads(argv[argv.index("--path") + 1]):
626
+ parent = json.loads(argv[argv.index("--path") + 1])[-1]
627
+ if title in store.get(parent, {}):
628
+ return 1, "", "Error: [11004] 分类名已存在"
629
+ seq["n"] += 1
630
+ uid = "U-%d" % seq["n"]
631
+ store.setdefault(parent, {})[title] = uid
632
+ return 0, json.dumps({"code": "201", "data": {"uuid": uid}}, ensure_ascii=False), ""
633
+ if "category-tree" in cmd:
634
+ pid = argv[argv.index("--id") + 1]
635
+ return 0, json.dumps({"code": "200", "data": [
636
+ {"title": t, "uuid": u} for t, u in store.get(pid, {}).items()]}, ensure_ascii=False), ""
637
+ if "list-categories" in cmd:
638
+ rows = []
639
+ for p, d in store.items():
640
+ rows += [{"title": t, "uuid": u, "parent_id": p} for t, u in d.items()]
641
+ return 0, json.dumps({"code": "200", "data": {"list": rows}}, ensure_ascii=False), ""
642
+ return 0, json.dumps({"code": "200", "data": {}}), ""
643
+
644
+ global _RUNNER
645
+ _RUNNER = fake
646
+ tmp = tempfile.mkdtemp(prefix="category-selftest-")
647
+ ok = True
648
+
649
+ # 1) 培训班:两级树,含一个撞名复用
650
+ store.clear()
651
+ store["1"] = {"01 新员工培养": "U-EXIST"}
652
+ spec = {"tree": "training_class",
653
+ "nodes": [{"name": "01 新员工培养", "children": [{"name": "校招生"}, {"name": "社招"}]},
654
+ {"name": "02 认证项目"}]}
655
+ p = os.path.join(tmp, "spec.json")
656
+ json.dump(spec, open(p, "w", encoding="utf-8"), ensure_ascii=False)
657
+
658
+ class A:
659
+ blueprint = None
660
+ spec = p
661
+ out_dir = os.path.join(tmp, "tc")
662
+ soke = "soke-cli"
663
+ sleep = 0
664
+ dry_run = False
665
+ tree = None
666
+ names = None
667
+ allow_flat = False
668
+
669
+ rc = run(A)
670
+ tm = json.load(open(os.path.join(A.out_dir, "category-tree.json"), encoding="utf-8"))
671
+ checks = [
672
+ ("培训班 4 节点全填充", len(tm["missing"]) == 0 and len(tm["nodes"]) == 4),
673
+ ("L1 复用既有 uuid", next(n for n in tm["nodes"] if n["name"] == "01 新员工培养")["uuid"] == "U-EXIST"),
674
+ ("L2 父链挂在 L1 下", len(store.get("U-EXIST", {})) == 2),
675
+ ("stats.reused>=1", tm["stats"]["reused"] >= 1),
676
+ ]
677
+
678
+ # 2) 学习地图多级 → 应拒绝
679
+ spec2 = {"tree": "learning_map", "nodes": [{"name": "A", "children": [{"name": "A1"}]}]}
680
+ p2 = os.path.join(tmp, "spec2.json")
681
+ json.dump(spec2, open(p2, "w", encoding="utf-8"), ensure_ascii=False)
682
+ A.spec, A.out_dir = p2, os.path.join(tmp, "lm")
683
+ rc2 = run(A)
684
+ checks.append(("地图多级被拒(rc=3)", rc2 == 3))
685
+
686
+ # 3) 权限拦截 → rc=4 且不刷满日志
687
+ store.clear()
688
+
689
+ def fake_deny(argv, timeout=90):
690
+ if "create-category" in " ".join(argv):
691
+ return 1, "", "Error: [12000] 无操作权限:无权访问"
692
+ return 0, json.dumps({"code": "200", "data": {"list": []}}), ""
693
+
694
+ _RUNNER = fake_deny
695
+ spec3 = {"tree": "exam", "nodes": ["A", "B", "C"]}
696
+ p3 = os.path.join(tmp, "spec3.json")
697
+ json.dump(spec3, open(p3, "w", encoding="utf-8"), ensure_ascii=False)
698
+ A.spec, A.out_dir = p3, os.path.join(tmp, "exam")
699
+ rc3 = run(A)
700
+ rep = json.load(open(os.path.join(A.out_dir, "category-report.json"), encoding="utf-8"))
701
+ checks.append(("权限拦截 rc=4", rc3 == 4))
702
+ checks.append(("权限拦截 calls<=2(不刷接口)", rep["calls"] <= 2))
703
+
704
+ for name, passed in checks:
705
+ print((" PASS " if passed else " FAIL ") + name)
706
+ ok = ok and passed
707
+ print("[self-test]", "PASS" if ok else "FAIL", "| tmp=", tmp)
708
+ _RUNNER = _default_runner
709
+ return 0 if ok else 1
710
+
711
+
712
+ def main():
713
+ ap = argparse.ArgumentParser(description="授客AI 三类分类树幂等构建器")
714
+ ap.add_argument("--spec", help="树规格 JSON(见 references/spec-format.md)")
715
+ ap.add_argument("--tree", choices=list(TREE_LABEL),
716
+ help="exam | learning_map | training_class")
717
+ ap.add_argument("--names", help="逗号分隔的平铺名称,替代 --spec")
718
+ ap.add_argument("--out-dir", help="产物目录(plan/result/tree/report/run.log)")
719
+ ap.add_argument("--soke", default=os.environ.get("SOKE_CLI") or shutil.which("soke-cli") or "soke-cli")
720
+ ap.add_argument("--sleep", type=float, default=3.0, help="节点间隔秒数,默认 3")
721
+ ap.add_argument("--allow-flat", action="store_true",
722
+ help="学习地图多级时压平执行(默认拒绝,因平台忽略 parent-id)")
723
+ ap.add_argument("--dry-run", action="store_true", help="只打印待发请求,不调用接口")
724
+ ap.add_argument("--verify-only", action="store_true", help="只回读校验 category-tree.json")
725
+ ap.add_argument("--cleanup", action="store_true", help="倒序删除本脚本 source=created 的节点")
726
+ ap.add_argument("--yes", action="store_true", help="--cleanup 的执行确认")
727
+ ap.add_argument("--self-test", action="store_true", help="桩响应自检,不连平台")
728
+ a = ap.parse_args()
729
+
730
+ if a.self_test:
731
+ return self_test()
732
+ if a.verify_only:
733
+ if not a.out_dir:
734
+ ap.error("--verify-only 需要 --out-dir")
735
+ return verify(a)
736
+ if a.cleanup:
737
+ if not a.out_dir or not a.tree:
738
+ ap.error("--cleanup 需要 --out-dir 与 --tree")
739
+ return cleanup(a)
740
+ if not a.out_dir or (not a.spec and not a.names):
741
+ ap.error("需要 --out-dir 且(--spec 或 --names);或用 --self-test / --verify-only / --cleanup")
742
+ if not a.tree and not a.spec:
743
+ ap.error("--names 必须配 --tree")
744
+ return run(a)
745
+
746
+
747
+ if __name__ == "__main__":
748
+ sys.exit(main())