@sokeai/cli 1.0.116 → 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,857 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """DEMO 建课流水线:一门课一轮内完成「挂分类 → 挂课件 → 绑图库封面 → 发布 → 六项回读 → 指派创建者」。
4
+
5
+ 背景(2026-10-20 三态实测,soke-cli 1.0.108 + opendev):
6
+ 1) `course +update --image` 会把 imgObj 序列化成 Go map 字符串
7
+ 落到 `picture`(形如 ["map[h:270 image:... w:480 x:0 y:0]"]),
8
+ 平台解析不到封面 → `img_url` 回落默认占位图 → 前端显示默认图,
9
+ 这就是"封面传不上去"的直接原因。**本脚本禁用该命令**。
10
+ 2) `api PUT` 带 imgObj 但裁剪参数非 0 时,平台生成
11
+ `<photoUri>/crop,x_0,y_0,w_480,h_270` → CDN 返回 404(裂图)。
12
+ 3) 唯一可用形态:api PUT 全载荷 + imgObj 裁剪参数全 0 →
13
+ `picture` 为合法对象、`img_url` 直接等于 photoUri(HTTP 200)。
14
+
15
+ 用法:
16
+ python3 course_build.py --blueprint <BLUEPRINT.json> [--dry-run]
17
+ python3 course_build.py --blueprint <BLUEPRINT.json> --only "经验萃取四步法"
18
+ python3 course_build.py --blueprint <BLUEPRINT.json> --assign-user manager7024 --assign-name 张三
19
+
20
+ 指派(v3.10.1 起为**必做环节**,不是可选项):
21
+ · --assign-user 缺省时自动取 `soke-cli config show` 的「用户ID」(= dept_user_id),
22
+ 这正好对应 demo-defaults 的「指派给创建者」默认;取不到且没显式传参 → 本门课判 assigned=false。
23
+ · 每门课 publish 回读通过后立刻 `assign +create --module course`,随后 `assign +list` 回读
24
+ count≥1 且 assign_key=user|<dept_user_id> 才算 assigned=true。
25
+ · ⚠️ 重跑时「已发布但未指派」的课只走**仅补指派**分支,绝不重建课程(否则平台上翻倍)。
26
+
27
+ 依赖同目录产物:taxonomy-map.json(分类 uuid)、photo-map.json(用途键 → photoUri)。
28
+ 输出:course-ids.json / cover-bindings.json 逐门增量落盘(可中断续跑),stdout 打印汇总 JSON。
29
+ 退出码:0=全部成功;2=有课程未达标(含未指派);1=执行失败(环境/参数)。
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import os
37
+ import shutil
38
+ import subprocess
39
+ import sys
40
+ import time
41
+ import urllib.request
42
+
43
+ from cli_kit import CreateJournal, pick_uuid
44
+
45
+ DEFAULT_CLI_CANDIDATES = [
46
+ os.environ.get("SOKE_CLI", ""),
47
+ os.path.expanduser("~/.workbuddy/binaries/node/cli-connector-packages/bin/soke-cli"),
48
+ "/usr/local/bin/soke-cli",
49
+ "/opt/homebrew/bin/soke-cli",
50
+ os.path.expanduser("~/.npm-global/bin/soke-cli"),
51
+ ]
52
+
53
+ DEFAULT_PPTX = os.environ.get("DEMO_PPTX") or ""
54
+
55
+
56
+ # ---------------------------------------------------------------- 基础工具
57
+
58
+ def resolve_cli() -> str:
59
+ for cand in DEFAULT_CLI_CANDIDATES:
60
+ if cand and os.path.isfile(cand) and os.access(cand, os.X_OK):
61
+ return cand
62
+ found = shutil.which("soke-cli")
63
+ if found:
64
+ return found
65
+ raise SystemExit("未找到 soke-cli,请先安装:npm i -g @sokeai/cli")
66
+
67
+
68
+ def parse_json(raw: str) -> dict:
69
+ """CLI 输出常混有升级广告/提示,取首个 '{' 起 raw_decode。"""
70
+ idx = raw.find("{")
71
+ if idx < 0:
72
+ raise ValueError(f"响应不是 JSON:{raw[:200]}")
73
+ obj, _ = json.JSONDecoder().raw_decode(raw[idx:])
74
+ if not isinstance(obj, dict):
75
+ raise ValueError(f"响应不是对象:{raw[:200]}")
76
+ return obj
77
+
78
+
79
+ def is_ok(resp: dict) -> bool:
80
+ return str(resp.get("code")) == "200" and str(resp.get("status", "ok")).lower() in ("ok", "success")
81
+
82
+
83
+ def config_dept_user_id(cli: str) -> str:
84
+ """从 `config show` 取「用户ID」(= dept_user_id = managerXXXX 形态),失败返回空串。
85
+
86
+ ⛔ 不要用 `contact +get-user` 反查(URL 拼接有缺陷);⛔ 不要拿它去
87
+ `assign +list-users --keyword` 搜(keyword 只匹配姓名/工号,恒空且不报错)。
88
+ """
89
+ try:
90
+ proc = subprocess.run([cli, "config", "show"], capture_output=True, text=True, timeout=60)
91
+ except Exception:
92
+ return ""
93
+ for line in (proc.stdout or "").splitlines():
94
+ for sep in (":", ":"):
95
+ head = "用户ID" + sep
96
+ if line.strip().startswith(head):
97
+ return line.strip()[len(head):].strip()
98
+ return ""
99
+
100
+
101
+ def read_json(path: str, default=None):
102
+ if not path or not os.path.isfile(path):
103
+ return default
104
+ with open(path, "r", encoding="utf-8") as fh:
105
+ return json.load(fh)
106
+
107
+
108
+ def write_json(path: str, data) -> None:
109
+ tmp = f"{path}.tmp"
110
+ with open(tmp, "w", encoding="utf-8") as fh:
111
+ json.dump(data, fh, ensure_ascii=False, indent=2)
112
+ os.replace(tmp, path)
113
+
114
+
115
+ # ---------------------------------------------------------------- 主流程
116
+
117
+ class Builder:
118
+ def __init__(self, args):
119
+ self.args = args
120
+ self.cli = args.cli or resolve_cli()
121
+ self.out_dir = os.path.abspath(args.out_dir)
122
+ os.makedirs(self.out_dir, exist_ok=True)
123
+ self.run_log = os.path.join(self.out_dir, "run.log")
124
+
125
+ self.blueprint = read_json(args.blueprint, {}) or {}
126
+ self.taxonomy = read_json(args.taxonomy_map) or read_json(
127
+ os.path.join(os.path.dirname(os.path.abspath(args.blueprint)), "taxonomy-map.json"), {}
128
+ )
129
+ self.photo_map = read_json(args.photo_map) or read_json(
130
+ os.path.join(os.path.dirname(os.path.abspath(args.blueprint)), "photo-map.json"), {}
131
+ )
132
+ self.course_ids_path = os.path.join(self.out_dir, "course-ids.json")
133
+ self.bindings_path = os.path.join(self.out_dir, "cover-bindings.json")
134
+ self.creates = CreateJournal(os.path.join(self.out_dir, "course-create-attempts.json"), "course")
135
+ self.course_ids = read_json(self.course_ids_path, {"blueprint_id": self.blueprint.get("meta", {}).get("blueprint_id", ""), "courses": []})
136
+ self.bindings = read_json(self.bindings_path, {"blueprint_id": self.course_ids.get("blueprint_id", ""), "bindings": []})
137
+ self.done_titles = {c.get("title") for c in self.course_ids.get("courses", [])
138
+ if c.get("status") == "published" and not c.get("error")}
139
+ self.prev_by_title = {
140
+ c.get("title"): c for c in self.course_ids.get("courses", [])
141
+ if c.get("course_id") and c.get("status") in ("published", "done") and not c.get("error")
142
+ }
143
+ # 指派对象 = 创建者(demo-defaults 全局默认):缺省取 config 的用户ID(dept_user_id)
144
+ self.assign_user = (getattr(args, "assign_user", "") or "").strip() or config_dept_user_id(self.cli)
145
+ self.assign_name = (getattr(args, "assign_name", "") or "").strip()
146
+ self.lesson = None
147
+
148
+ # -------------------------------------------------- 日志 / 调用
149
+
150
+ def log(self, module: str, msg: str) -> None:
151
+ line = f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] [{module}] {msg}\n"
152
+ with open(self.run_log, "a", encoding="utf-8") as fh:
153
+ fh.write(line)
154
+ fh.flush()
155
+
156
+ # -------------------------------------------------- 会话锁 / 失败恢复诊断
157
+
158
+ def guard(self, *argv: str) -> int:
159
+ """调 scripts/guard.py(单实例锁的唯一实现,禁止在本脚本内另写一套)。"""
160
+ script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "guard.py")
161
+ try:
162
+ return subprocess.run([sys.executable, script] + list(argv),
163
+ capture_output=True, text=True, timeout=60).returncode
164
+ except Exception as exc:
165
+ self.log("guard", f"FAIL guard {argv[0]} err={exc}")
166
+ return 1
167
+
168
+ def acquire_lock(self) -> None:
169
+ """⚠️ 2026-10-21 事故:上一轮脚本没死透,两个进程并发建课 → 同名课 ×2。
170
+ 开工前必须拿到锁;拿不到 = 已有活进程在写,立即停。"""
171
+ rc = self.guard("acquire", "--demo-root", self.out_dir, "--module", "course-setup")
172
+ if rc != 0:
173
+ raise SystemExit("未取得 DEMO 模块锁,停止写入;先用 guard.py status 核查,不自动抢占")
174
+ # 必须在持锁后重读,防止等待锁之前加载的尝试记录过期。
175
+ self.creates = CreateJournal(os.path.join(self.out_dir, "course-create-attempts.json"), "course")
176
+
177
+ def candidates(self, title: str) -> list:
178
+ """仅无 UUID 的失败恢复时按完整标题诊断;命中不代表本次归属,不复用/删除。"""
179
+ rows = []
180
+ for st in ("1", "0"):
181
+ try:
182
+ resp = self.call(["course", "+list-courses", "--keyword", title,
183
+ "--page-size", "50", "--status", st, "--format", "json"])
184
+ except SystemExit:
185
+ break
186
+ for row in self._rows(resp):
187
+ if str(row.get("title") or "").strip() == title:
188
+ uid = str(row.get("uuid") or row.get("id") or "").strip()
189
+ if uid:
190
+ rows.append({"uuid": uid, "status": row.get("status")})
191
+ if rows:
192
+ break
193
+ return rows
194
+
195
+ @staticmethod
196
+ def _rows(resp: dict) -> list:
197
+ """从响应里捞出对象行列表(data.list / data.list.all / data 直挂列表 都覆盖)。"""
198
+ found = []
199
+
200
+ def walk(node):
201
+ if isinstance(node, dict):
202
+ for key, val in node.items():
203
+ if isinstance(val, list) and val and isinstance(val[0], dict) \
204
+ and ("title" in val[0] or "uuid" in val[0]):
205
+ found.extend(val)
206
+ elif isinstance(val, (dict, list)):
207
+ walk(val)
208
+ elif isinstance(node, list):
209
+ for item in node:
210
+ walk(item)
211
+ walk(resp)
212
+ # 去重(同一行可能被 list 与父级各命中一次)
213
+ seen, uniq = set(), []
214
+ for row in found:
215
+ uid = str(row.get("uuid") or row.get("id") or "") or repr(sorted(row.keys()))
216
+ if uid in seen:
217
+ continue
218
+ seen.add(uid)
219
+ uniq.append(row)
220
+ return uniq
221
+
222
+ def lesson_count(self, course_id: str) -> int:
223
+ try:
224
+ resp = self.call(["course", "+lesson-list", "--course-id", course_id, "--format", "json"])
225
+ except SystemExit:
226
+ return -1
227
+ return len(self._rows(resp)) if is_ok(resp) else -1
228
+
229
+ def call(self, args: list[str], expect_json: bool = True) -> dict:
230
+ proc = subprocess.run([self.cli] + args, capture_output=True, text=True, timeout=90)
231
+ if not expect_json:
232
+ return {"_rc": proc.returncode, "_out": proc.stdout, "_err": proc.stderr}
233
+ try:
234
+ return parse_json(proc.stdout)
235
+ except ValueError:
236
+ raise SystemExit(
237
+ f"命令失败(exit={proc.returncode}):{' '.join(args)}\n"
238
+ f"stdout={proc.stdout[:400]}\nstderr={proc.stderr[:400]}"
239
+ )
240
+
241
+ # -------------------------------------------------- 资源解析
242
+
243
+ def l2_uuid(self, category_path) -> str:
244
+ """category_path 支持三种形态:'L1/L2' 字符串、['L1','L2'] 数组、{l1,l2} 对象。
245
+
246
+ v4.2.0:旧版只认字符串,`(category_path or "").strip()` 遇到数组直接
247
+ AttributeError → **本脚本在 blueprint-schema v2 上根本跑不起来**,
248
+ 2026-10-22 的 10 门课因此全是手工建的(也就没有 course-ids.json)。
249
+ """
250
+ if isinstance(category_path, (list, tuple)):
251
+ parts = [str(x).strip() for x in category_path if str(x).strip()]
252
+ path = "/".join(parts)
253
+ elif isinstance(category_path, dict):
254
+ path = "%s/%s" % ((category_path.get("l1") or "").strip(),
255
+ (category_path.get("l2") or "").strip())
256
+ path = path.strip("/")
257
+ else:
258
+ path = (category_path or "").strip()
259
+ if not path:
260
+ return ""
261
+ l1_name, _, l2_name = path.partition("/")
262
+ for node in self.taxonomy.get("course", []) or []:
263
+ if node.get("l1") != l1_name:
264
+ continue
265
+ if not l2_name:
266
+ return node.get("l1_uuid", "")
267
+ for leaf in node.get("l2", []) or []:
268
+ if leaf.get("name") == l2_name:
269
+ return leaf.get("uuid", "")
270
+ # 退化匹配:只按 l2 名跨 L1 找(分类名被平台改写时兜底)
271
+ if l2_name:
272
+ for node in self.taxonomy.get("course", []) or []:
273
+ for leaf in node.get("l2", []) or []:
274
+ if leaf.get("name") == l2_name:
275
+ return leaf.get("uuid", "")
276
+ return ""
277
+
278
+ def photo_uri(self, asset_key: str) -> str:
279
+ items = self.photo_map.get("items")
280
+ if isinstance(items, dict): # 兼容 {key: {...}} 形态
281
+ items = [dict(v, key=k) for k, v in items.items()]
282
+ for item in items or []:
283
+ if item.get("key") == asset_key:
284
+ return item.get("photo_uri") or ""
285
+ return ""
286
+
287
+ # -------------------------------------------------- 单步动作
288
+
289
+ def upload_lesson(self) -> dict:
290
+ resp = self.call(["file", "+upload", "--file", self.args.pptx, "--type", "document",
291
+ "--length", "120", "--format", "json"])
292
+ if not is_ok(resp):
293
+ raise SystemExit(f"课件上传失败:{resp.get('message')}")
294
+ data = resp.get("data") or {}
295
+ need = ("uuid", "object", "filesize")
296
+ if not all(data.get(k) for k in need):
297
+ raise SystemExit(f"课件三件套不全:{json.dumps(data, ensure_ascii=False)[:300]}")
298
+ self.log("course-build", f"lesson upload uuid={data['uuid']}")
299
+ return data
300
+
301
+ def inspect_created_course(self, course_id):
302
+ data = self.read_course(course_id)
303
+ uid = data.get("uuid") or data.get("id")
304
+ return {"state": "exists" if str(uid or "") == str(course_id) else "unknown",
305
+ "unpublished": str(data.get("is_hide")) == "1"
306
+ and str(data.get("publish_time") or "").startswith("1970"),
307
+ "data": data}
308
+
309
+ def delete_failed_course(self, course_id):
310
+ # 复用 dup_cleanup 的已验证通道;仅 journal 安全护栏通过后触发。
311
+ resp = self.call(["course", "+update", "--action", "close", "--course-id", course_id,
312
+ "--format", "json"])
313
+ if not is_ok(resp):
314
+ raise RuntimeError("失败课程关闭未确认,停止删除")
315
+ resp = self.call(["course", "+delete", "--course-id", course_id, "--format", "json"])
316
+ if not is_ok(resp):
317
+ raise RuntimeError("失败课程删除未确认,等待回读")
318
+
319
+ def create_course(self, title: str, category_id: str, description: str) -> str:
320
+ self.creates.begin(title, title)
321
+ resp = self.call(["course", "+create", "--title", title, "--category-id", category_id,
322
+ "--description", description, "--format", "json"])
323
+ uuid = self.creates.returned(title, is_ok(resp), resp, resp.get("message") or "")
324
+ if not is_ok(resp):
325
+ raise RuntimeError(f"+create 失败:{resp.get('message')}")
326
+ data = resp.get("data") or {}
327
+ if not uuid:
328
+ raise RuntimeError(f"+create 未返回 uuid:{json.dumps(data, ensure_ascii=False)[:200]}")
329
+ if str(data.get("category_id", category_id)) != category_id:
330
+ raise RuntimeError(f"建课分类不一致:期望 {category_id},回读 {data.get('category_id')}")
331
+ return uuid
332
+
333
+ def add_lesson(self, course_id: str) -> None:
334
+ resp = self.call(["course", "+lesson-create", "--course-id", course_id,
335
+ "--title", "占位课件", "--type", "document",
336
+ "--media-id", self.lesson["uuid"], "--filename", "placeholder.pptx",
337
+ "--ext", "pptx", "--length", "120", "--object", self.lesson["object"],
338
+ "--filesize", str(self.lesson["filesize"]), "--sort", "1",
339
+ "--format", "json"])
340
+ if not is_ok(resp):
341
+ raise RuntimeError(f"+lesson-create 失败:{resp.get('message')}")
342
+
343
+ def bind_cover(self, course_id: str, title: str, description: str, category_id: str, photo_uri: str) -> dict:
344
+ """封面+分类同批。⛔ 裁剪参数全 0:图片本地已 16:9,平台无需二次裁剪。"""
345
+ payload = {
346
+ "action": "update",
347
+ "uuid": course_id,
348
+ "title": title,
349
+ "description": description,
350
+ "category_id": category_id,
351
+ "categories": [category_id],
352
+ "category_path": [category_id],
353
+ "img_picked": 0,
354
+ "imgObj": {"image": photo_uri, "w": 0, "h": 0, "x": 0, "y": 0},
355
+ }
356
+ resp = self.call(["api", "PUT", f"/skills/course/update/{course_id}", "--as", "user",
357
+ "--data", json.dumps(payload, ensure_ascii=False)])
358
+ if not is_ok(resp) or resp.get("data") in (0, None, False):
359
+ raise RuntimeError(f"封面绑定失败:{resp.get('message')}")
360
+ return resp
361
+
362
+ def publish(self, course_id: str) -> None:
363
+ resp = self.call(["course", "+publish", "--course-id", course_id, "--format", "json"])
364
+ if not is_ok(resp):
365
+ raise RuntimeError(f"+publish 失败:{resp.get('message')}")
366
+
367
+ def read_course(self, course_id: str) -> dict:
368
+ resp = self.call(["course", "+get-course", "--course-id", course_id, "--format", "json"])
369
+ if not is_ok(resp):
370
+ raise RuntimeError(f"+get-course 失败:{resp.get('message')}")
371
+ return resp.get("data") or {}
372
+
373
+ # -------------------------------------------------- 指派(v3.10.1 必做)
374
+
375
+ def list_assign(self, course_id: str) -> dict:
376
+ """回读指派:count + 已指派 uuid 列表(assign_key 形态 user|<uuid>)。"""
377
+ resp = self.call(["assign", "+list", "--module", "course", "--target-id", course_id, "--format", "json"])
378
+ data = resp.get("data") or {}
379
+ uuids = []
380
+ if isinstance(data, dict):
381
+ for row in data.get("list") or []:
382
+ key = str(row.get("assign_key") or "")
383
+ uuids.append(key.split("|", 1)[1] if key.startswith("user|") else str(row.get("uuid") or ""))
384
+ return {"count": int(data.get("count") or 0), "uuids": [u for u in uuids if u]}
385
+ return {"count": 0, "uuids": []}
386
+
387
+ def assign_course(self, course_id: str) -> dict:
388
+ """指派给创建者;幂等(已指派直接返回),判据只看回读,不看 +create 返回值。"""
389
+ if not self.assign_user:
390
+ raise RuntimeError("未取到创建者 dept_user_id:请传 --assign-user 或确保 config show 有「用户ID」")
391
+ cur = self.list_assign(course_id)
392
+ if self.assign_user in cur["uuids"]:
393
+ return cur
394
+ self.call(["assign", "+create", "--module", "course", "--target-id", course_id,
395
+ "--learn-type", "required",
396
+ "--user-ids", self.assign_user,
397
+ "--user-names", self.assign_name or self.assign_user,
398
+ "--format", "json"])
399
+ self.log("course-assign", f"assign sent course={course_id} user={self.assign_user}")
400
+ got = {"count": 0, "uuids": []}
401
+ for wait in (2, 4): # 回读限流:两次降级重试
402
+ time.sleep(wait)
403
+ got = self.list_assign(course_id)
404
+ if self.assign_user in got["uuids"]:
405
+ return got
406
+ raise RuntimeError(f"指派回读未命中:count={got['count']} uuids={got['uuids']}(期望 {self.assign_user})")
407
+
408
+ # -------------------------------------------------- 校验
409
+
410
+ @staticmethod
411
+ def http_ok(url: str) -> int:
412
+ try:
413
+ req = urllib.request.Request(url, method="HEAD")
414
+ with urllib.request.urlopen(req, timeout=15) as resp:
415
+ return resp.status
416
+ except Exception:
417
+ try:
418
+ with urllib.request.urlopen(url, timeout=15) as resp:
419
+ resp.read(1)
420
+ return resp.status
421
+ except Exception:
422
+ return 0
423
+
424
+ def verify(self, data: dict, category_id: str, photo_uri: str) -> dict:
425
+ pic = data.get("picture")
426
+ if isinstance(pic, list) and pic:
427
+ pic = pic[0]
428
+ pic_image = pic.get("image") if isinstance(pic, dict) else ("" if not pic else str(pic))
429
+ img_url = data.get("img_url") or ""
430
+
431
+ if not photo_uri:
432
+ cover_state = "no_asset"
433
+ elif isinstance(pic, str) and pic.startswith("map["):
434
+ cover_state = "false_go_map" # CLI --image 写出的脏数据
435
+ elif img_url and "/crop," in img_url:
436
+ cover_state = "false_crop404" # 平台裁剪死链
437
+ elif img_url and img_url.endswith("course-cover-two.png"):
438
+ cover_state = "false_default" # 回落默认占位图
439
+ elif img_url and img_url == photo_uri:
440
+ cover_state = "ok" if self.http_ok(img_url) == 200 else "false_unreachable"
441
+ elif img_url:
442
+ cover_state = "ok" if (pic_image == photo_uri and self.http_ok(img_url) == 200) else "false_mismatch"
443
+ else:
444
+ cover_state = "false_empty"
445
+
446
+ return {
447
+ "is_hide": data.get("is_hide"),
448
+ "purpose": data.get("purpose"),
449
+ "publish_time": data.get("publish_time"),
450
+ "published": (str(data.get("is_hide")) == "0"
451
+ and str(data.get("purpose")) == "0"
452
+ and not str(data.get("publish_time", "")).startswith("1970")),
453
+ "category_ok": str(data.get("category_id") or "") == category_id,
454
+ "picture_image": pic_image,
455
+ "img_url": img_url,
456
+ "cover_state": cover_state,
457
+ "cover_displayable": cover_state == "ok",
458
+ }
459
+
460
+ # -------------------------------------------------- 逐门执行
461
+
462
+ def build_one(self, course: dict) -> dict:
463
+ title = course.get("title") or ""
464
+ description = (course.get("demo_fields") or {}).get("description") or "(演示数据)本课程用于 DEMO 演示。"
465
+ asset_key = course.get("asset_key") or ""
466
+ category_id = self.l2_uuid(course.get("category_path", ""))
467
+ photo_uri = self.photo_uri(asset_key)
468
+
469
+ record = {"title": title, "asset_key": asset_key, "category_id": category_id,
470
+ "cover": {"photo_uri": photo_uri}}
471
+
472
+ if not category_id:
473
+ record.update(status="failed", error="分类未在 taxonomy-map 中匹配到 uuid")
474
+ return record
475
+
476
+ if self.args.dry_run:
477
+ record.update(status="planned", lesson_ok=True,
478
+ payload_preview={"api": f"PUT /skills/course/update/<uuid>",
479
+ "imgObj": {"image": photo_uri, "w": 0, "h": 0, "x": 0, "y": 0}})
480
+ return record
481
+
482
+ try:
483
+ # 只续用本地已登记的成功对象,绝不在首次 create 前查同名。
484
+ legacy = [r for r in self.course_ids.get("courses", [])
485
+ if r.get("title") == title and r.get("course_id")]
486
+ if legacy and not self.creates.get(title):
487
+ record.update(status="pending", course_id=legacy[-1]["course_id"],
488
+ error="发现旧 ID 清单但无创建尝试归属记录;保留对象,禁止自动重建或删除")
489
+ return record
490
+ action, course_id, reason = self.creates.prepare(
491
+ title, self.inspect_created_course, discover=self.candidates,
492
+ delete=self.delete_failed_course)
493
+ if action == "pending":
494
+ record.update(status="pending", error=reason, course_id=course_id)
495
+ return record
496
+ if action in ("repair", "done"):
497
+ record.update(course_id=course_id, reused_existing=True)
498
+ self.log("course-build", f"repair own title={title} uuid={course_id}")
499
+ else:
500
+ course_id = self.create_course(title, category_id, description)
501
+ record["course_id"] = course_id
502
+ self.log("course-build", f"create ok title={title} uuid={course_id}")
503
+ time.sleep(self.args.sleep)
504
+
505
+ count = self.lesson_count(course_id) if record.get("reused_existing") else 0
506
+ if count < 0:
507
+ raise RuntimeError("课件回读失败,禁止重复挂载")
508
+ if count > 0:
509
+ self.creates.step(title, "lesson", "success")
510
+ self.log("course-build", f"lesson skip(本次课程已有课件)title={title}")
511
+ elif self.creates.step(title, "lesson"):
512
+ raise RuntimeError("上次挂课件请求结果不明,当前回读未确认,保留课程待核验,不重复发送")
513
+ else:
514
+ self.creates.step(title, "lesson", "requested")
515
+ self.add_lesson(course_id)
516
+ self.creates.step(title, "lesson", "success")
517
+ time.sleep(self.args.sleep)
518
+
519
+ if photo_uri:
520
+ self.bind_cover(course_id, title, description, category_id, photo_uri)
521
+ self.log("course-build", f"cover bound title={title} uri={photo_uri}")
522
+ time.sleep(self.args.sleep)
523
+
524
+ self.publish(course_id)
525
+ time.sleep(self.args.sleep)
526
+
527
+ data = self.read_course(course_id)
528
+ checks = self.verify(data, category_id, photo_uri)
529
+ record.update(checks)
530
+ record["status"] = "published" if checks["published"] and checks["category_ok"] else "failed"
531
+ if not checks["published"]:
532
+ record["error"] = "假发布或分类被洗,见 is_hide/purpose/publish_time/category_ok"
533
+ elif photo_uri and not checks["cover_displayable"]:
534
+ record["error"] = f"封面未生效({checks['cover_state']}),课程本身已发布"
535
+ record["cover"]["photo_uuid"] = self.photo_uuid_of(asset_key)
536
+ record["cover"]["displayable"] = checks["cover_displayable"]
537
+ record["cover"]["img_url"] = checks["img_url"]
538
+
539
+ # 指派创建者:发布回读通过才派(未发布态派了学员端也看不见)
540
+ if record["status"] == "published":
541
+ try:
542
+ got = self.assign_course(course_id)
543
+ record["assigned"] = True
544
+ record["assign_user"] = self.assign_user
545
+ record["assign_count"] = got["count"]
546
+ self.log("course-assign", f"ok title={title} user={self.assign_user}")
547
+ except (RuntimeError, SystemExit) as exc:
548
+ record["assigned"] = False
549
+ record["assign_error"] = str(exc)[:200]
550
+ self.log("course-assign", f"FAIL title={title} err={str(exc)[:160]}")
551
+ else:
552
+ record["assigned"] = False
553
+ record["assign_error"] = "课程未真发布,跳过指派"
554
+
555
+ self.bindings["bindings"].append({
556
+ "course_id": course_id, "course_title": title, "asset_key": asset_key,
557
+ "photo_uuid": record["cover"]["photo_uuid"], "photo_uri": photo_uri,
558
+ "img_url": checks["img_url"], "http": self.http_ok(checks["img_url"]) if checks["img_url"] else 0,
559
+ "displayable": checks["cover_displayable"], "state": checks["cover_state"],
560
+ "bound_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
561
+ })
562
+ write_json(self.bindings_path, self.bindings)
563
+ if record.get("status") == "published" and record.get("assigned") and not record.get("error"):
564
+ self.creates.complete(title)
565
+ except (RuntimeError, SystemExit, OSError, subprocess.TimeoutExpired) as exc:
566
+ self.creates.failure(title, str(exc))
567
+ attempt = self.creates.get(title) or {}
568
+ record.update(status="pending" if attempt.get("state") in ("requested", "create_failed") else "failed",
569
+ error=str(exc)[:300], course_id=record.get("course_id") or attempt.get("uuid"))
570
+ self.log("course-build", f"FAIL title={title} err={str(exc)[:200]}")
571
+ return record
572
+
573
+ def photo_uuid_of(self, asset_key: str) -> str:
574
+ items = self.photo_map.get("items")
575
+ if isinstance(items, dict):
576
+ items = [dict(v, key=k) for k, v in items.items()]
577
+ for item in items or []:
578
+ if item.get("key") == asset_key:
579
+ return item.get("photo_uuid") or item.get("uuid") or ""
580
+ return ""
581
+
582
+ def assign_only(self, prev: dict) -> dict:
583
+ """存量课「已发布但未指派」:只补指派。⛔ 绝不重新 create(否则平台上同名课翻倍)。"""
584
+ title = prev.get("title") or ""
585
+ cid = prev.get("course_id") or ""
586
+ if self.args.dry_run:
587
+ return {"title": title, "status": "planned_assign_only", "course_id": cid}
588
+ try:
589
+ got = self.assign_course(cid)
590
+ prev.update(assigned=True, assign_user=self.assign_user, assign_count=got["count"])
591
+ prev.pop("assign_error", None)
592
+ self.log("course-assign", f"assign-only ok title={title} user={self.assign_user}")
593
+ return {"title": title, "status": "assign_only_ok", "course_id": cid,
594
+ "assigned": True, "assign_count": got["count"]}
595
+ except (RuntimeError, SystemExit) as exc:
596
+ prev["assigned"] = False
597
+ prev["assign_error"] = str(exc)[:200]
598
+ self.log("course-assign", f"assign-only FAIL title={title} err={str(exc)[:160]}")
599
+ return {"title": title, "status": "assign_only_failed", "course_id": cid,
600
+ "assigned": False, "error": str(exc)[:200]}
601
+
602
+ def run(self) -> int:
603
+ courses = self.blueprint.get("courses") or []
604
+ if self.args.only:
605
+ courses = [c for c in courses if c.get("title") == self.args.only]
606
+ if not courses:
607
+ print(json.dumps({"ok": False, "error": "BLUEPRINT.courses 为空或 --only 未命中"}, ensure_ascii=False))
608
+ return 1
609
+
610
+ if not self.args.dry_run:
611
+ self.acquire_lock()
612
+ self.log("course-setup", f"START total={len(courses)} "
613
+ f"assign_user={self.assign_user or '-'} "
614
+ f"allow_dup={bool(self.args.allow_dup)}")
615
+ self.lesson = self.upload_lesson()
616
+ time.sleep(self.args.sleep)
617
+
618
+ results = []
619
+ for idx, course in enumerate(courses, 1):
620
+ title = course.get("title") or ""
621
+ prev = self.prev_by_title.get(title)
622
+ # 已发布但未指派 → 只补指派,绝不重建(2026-10-20 事故:整批课没指派)
623
+ if prev and not prev.get("assigned") and not prev.get("error"):
624
+ results.append(self.assign_only(prev))
625
+ if not self.args.dry_run:
626
+ write_json(self.course_ids_path, self.course_ids)
627
+ if idx < len(courses):
628
+ time.sleep(self.args.sleep)
629
+ continue
630
+ if title in self.done_titles and not self.args.force:
631
+ results.append({"title": title, "status": "skipped_done",
632
+ "assigned": bool((self.prev_by_title.get(title) or {}).get("assigned"))})
633
+ continue
634
+ rec = self.build_one(course)
635
+ results.append(rec)
636
+ if not self.args.dry_run:
637
+ self.course_ids["courses"].append(rec)
638
+ write_json(self.course_ids_path, self.course_ids)
639
+ if idx < len(courses):
640
+ time.sleep(self.args.sleep)
641
+
642
+ published = [r for r in results if r.get("status") in ("published", "done")]
643
+ displayable = [r for r in results if r.get("cover_displayable")]
644
+ unassigned = [r.get("title") for r in results
645
+ if r.get("status") not in ("planned", "planned_assign_only") and r.get("assigned") is not True]
646
+ reused = [r for r in results if r.get("reused_existing")]
647
+ failed = [r for r in results if r.get("status") not in (
648
+ "published", "done", "skipped_done", "planned", "assign_only_ok", "planned_assign_only")]
649
+ summary = {
650
+ "ok": all(r.get("status") in ("published", "done", "skipped_done", "planned",
651
+ "assign_only_ok", "planned_assign_only") for r in results)
652
+ and not unassigned,
653
+ "total": len(results),
654
+ "published": len(published),
655
+ "reused_existing": len(reused),
656
+ "failed": len(failed),
657
+ "cover_displayable": len(displayable),
658
+ "assigned": sum(1 for r in results if r.get("assigned") is True),
659
+ "unassigned": unassigned,
660
+ "assign_user": self.assign_user,
661
+ "course_ids": self.course_ids_path,
662
+ "cover_bindings": self.bindings_path,
663
+ "results": results,
664
+ }
665
+ if not self.args.dry_run:
666
+ created_n = len([r for r in published if not r.get("reused_existing")])
667
+ fail_n = len(failed)
668
+ self.log("course-setup",
669
+ f"END created={created_n} reused={len(reused)} failed={fail_n} "
670
+ f"published={len(published)}/{len(results)} "
671
+ f"assigned={summary['assigned']}/{len(results)} "
672
+ f"cover_ok={len(displayable)}/{len(results)}")
673
+ self.log("course-setup",
674
+ f"RUN SUMMARY created={created_n} reused={len(reused)} "
675
+ f"failed={fail_n} unassigned={len(unassigned)} → "
676
+ f"{'OK' if summary['ok'] else 'FAIL'}")
677
+ self.guard("release", "--demo-root", self.out_dir, "--module", "course-setup",
678
+ "--status", "ok" if summary["ok"] else "failed")
679
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
680
+ if self.args.dry_run:
681
+ return 0
682
+ return 0 if summary["ok"] else 2
683
+
684
+
685
+ def self_test() -> int:
686
+ """离线桩测试:不连平台,仅在临时目录写入测试产物。
687
+
688
+ 覆盖建课链路里最容易静默出错的四段纯逻辑:
689
+ 1. parse_json —— CLI 日志前缀 + 字段值含花括号(`map[...]`、permissions)不许截错
690
+ 2. is_ok —— code/status 双判据(返回 data:1 但 status=error 必须判失败)
691
+ 3. _rows —— data.list / data.list.all / data 直挂列表三种形态 + 去重
692
+ 4. l2_uuid / photo_uri —— 分类路径解析、退化匹配、图片用途键取值
693
+ 5. verify —— 封面五态判定(ok / 脏 map / crop 404 / 回落默认图 / 空),http 用桩替身
694
+ """
695
+ import tempfile
696
+ cases = []
697
+
698
+ def ck(cond, label):
699
+ cases.append((bool(cond), label))
700
+
701
+ # 1. parse_json
702
+ raw = '[info] 检查更新完成\n{"code":200,"data":{"note":"a{b}c","picture":["map[h:270 x:0]"]}}'
703
+ obj = parse_json(raw)
704
+ ck(obj["data"]["note"] == "a{b}c", "parse_json 跳过日志前缀")
705
+ ck(obj["data"]["picture"] == ["map[h:270 x:0]"], "parse_json 保留字段内花括号")
706
+ ck(parse_json('{"code": "200"}')["code"] == "200", "parse_json 字符串 code")
707
+ for bad in ("", "no json here"):
708
+ try:
709
+ parse_json(bad)
710
+ ck(False, "parse_json 拒非 JSON(%r)" % bad)
711
+ except ValueError:
712
+ ck(True, "parse_json 拒非 JSON(%r)" % bad)
713
+
714
+ # 2. is_ok
715
+ ck(is_ok({"code": 200}), "is_ok 200 无 status")
716
+ ck(is_ok({"code": "200", "status": "ok"}), "is_ok 200+ok")
717
+ ck(is_ok({"code": 200, "status": "success"}), "is_ok 200+success")
718
+ ck(not is_ok({"code": 200, "status": "error"}), "is_ok 拒 status=error")
719
+ ck(not is_ok({"code": None, "data": 1}), "is_ok 拒 code=None")
720
+
721
+ # 3. _rows 三形态 + 去重
722
+ ck(len(Builder._rows({"data": {"list": [{"uuid": "a"}, {"uuid": "b"}]}})) == 2, "_rows data.list")
723
+ ck(len(Builder._rows({"data": {"list": {"all": [{"title": "x"}]}}})) == 1, "_rows data.list.all")
724
+ ck(len(Builder._rows({"data": [{"title": "y"}]})) == 1, "_rows data 直挂列表")
725
+ ck(len(Builder._rows({"data": {"rows": [{"uuid": "a"}, {"uuid": "a"}]}})) == 1, "_rows 去重")
726
+
727
+ # 4/5. 依赖文件与 http 桩
728
+ with tempfile.TemporaryDirectory(prefix="course-build-") as tmp:
729
+ bp = os.path.join(tmp, "DEMO-BLUEPRINT.json")
730
+ tax = os.path.join(tmp, "taxonomy-map.json")
731
+ photo = os.path.join(tmp, "photo-map.json")
732
+ write_json(bp, {"meta": {"blueprint_id": "bp-test"}, "courses": []})
733
+ write_json(tax, {"course": [
734
+ {"l1": "01 新员工必修课", "l1_uuid": "L1A",
735
+ "l2": [{"name": "文化与制度", "uuid": "L2A"}, {"name": "产品入门", "uuid": "L2B"}]},
736
+ {"l1": "02 产品知识", "l1_uuid": "L1B", "l2": [{"name": "产品基础", "uuid": "L2C"}]},
737
+ ]})
738
+ write_json(photo, {"items": [
739
+ {"key": "cover.course.c1", "photo_uri": "https://cdn/x.png", "photo_uuid": "P1"},
740
+ ]})
741
+
742
+ class A:
743
+ pass
744
+ a = A()
745
+ a.blueprint, a.out_dir, a.taxonomy_map, a.photo_map = bp, tmp, tax, photo
746
+ a.cli = sys.executable # 任何可执行文件即可:本测试不真的调平台
747
+ a.assign_user, a.assign_name = "manager0001", "张三"
748
+ a.pptx, a.only, a.force = "", None, False
749
+ a.allow_dup, a.dry_run, a.sleep = False, True, 0.0
750
+ b = Builder(a)
751
+
752
+ ck(b.l2_uuid("01 新员工必修课/文化与制度") == "L2A", "l2_uuid 精确命中")
753
+ ck(b.l2_uuid("02 产品知识") == "L1B", "l2_uuid 只给 L1 取 L1 uuid")
754
+ ck(b.l2_uuid("99 不存在/产品入门") == "L2B", "l2_uuid 退化跨 L1 匹配")
755
+ ck(b.l2_uuid("") == "", "l2_uuid 空路径返回空")
756
+ ck(b.photo_uri("cover.course.c1") == "https://cdn/x.png", "photo_uri 命中")
757
+ ck(b.photo_uri("cover.course.none") == "", "photo_uri 未命中返回空")
758
+
759
+ uri = "https://cdn/x.png"
760
+ b.http_ok = staticmethod(lambda url: 200)
761
+ ok = b.verify({"img_url": uri, "picture": {"image": uri}, "is_hide": 0,
762
+ "purpose": 0, "publish_time": "2026-10-22 10:00:00",
763
+ "category_id": "L2A"}, "L2A", uri)
764
+ ck(ok["cover_state"] == "ok" and ok["cover_displayable"], "verify 封面 ok")
765
+ ck(ok["published"] and ok["category_ok"], "verify 发布+分类判定")
766
+
767
+ dirty = b.verify({"img_url": "https://cdn/default.png",
768
+ "picture": ["map[h:270 image:x]"], "category_id": "L2A"}, "L2A", uri)
769
+ ck(dirty["cover_state"] == "false_go_map", "verify 抓 CLI 脏 map 串")
770
+ crop = b.verify({"img_url": uri + "/crop,x_0,y_0,w_480,h_270", "picture": {"image": uri}}, "L2A", uri)
771
+ ck(crop["cover_state"] == "false_crop404", "verify 抓 crop 死链")
772
+ default = b.verify({"img_url": "https://cdn/course-cover-two.png", "picture": {"image": uri}}, "L2A", uri)
773
+ ck(default["cover_state"] == "false_default", "verify 抓回落默认图")
774
+ empty = b.verify({"img_url": "", "picture": {}}, "L2A", uri)
775
+ ck(empty["cover_state"] == "false_empty", "verify 抓空封面")
776
+ noasset = b.verify({"img_url": "", "picture": {}}, "L2A", "")
777
+ ck(noasset["cover_state"] == "no_asset", "verify 无资产单独态")
778
+
779
+ b.http_ok = staticmethod(lambda url: 0)
780
+ dead = b.verify({"img_url": uri, "picture": {"image": uri}}, "L2A", uri)
781
+ ck(dead["cover_state"] == "false_unreachable", "verify 抓 CDN 不可达")
782
+
783
+ # 续跑前置:published 记录不许被当成待建
784
+ ck(b.done_titles == set() and b.prev_by_title == {}, "空清单时无已完成记录")
785
+
786
+ # 离线模拟首次创建、配置失败修补、超时恢复,不调用真实平台。
787
+ from unittest.mock import Mock, patch
788
+ a.dry_run = False
789
+ course = {"title": "首次直建", "category_path": "01 新员工必修课/文化与制度"}
790
+ detail = {"uuid": "own-course", "title": course["title"], "is_hide": 0,
791
+ "purpose": 0, "publish_time": "2026-10-22", "category_id": "L2A"}
792
+ b.call = Mock(return_value={"code": 200, "data": {"uuid": "own-course"}})
793
+ b.candidates = Mock(return_value=[{"uuid": "unowned"}])
794
+ b.add_lesson = Mock(side_effect=RuntimeError("配置失败"))
795
+ with patch("time.sleep"):
796
+ first = b.build_one(course)
797
+ ck(first["course_id"] == "own-course" and not b.candidates.called
798
+ and b.call.call_count == 1, "首次零同名查询且 create 仅一次")
799
+ b.read_course = Mock(return_value=detail)
800
+ b.lesson_count = Mock(return_value=1)
801
+ b.publish = Mock()
802
+ b.assign_course = Mock(return_value={"count": 1})
803
+ b.call.reset_mock()
804
+ with patch("time.sleep"):
805
+ resumed = b.build_one(course)
806
+ ck(resumed["status"] == "published" and resumed.get("reused_existing")
807
+ and not b.call.called and not b.candidates.called, "创建成功配置失败续跑仅修补本次 UUID")
808
+ b.call = Mock(side_effect=subprocess.TimeoutExpired("unused", 90))
809
+ with patch("time.sleep"):
810
+ unknown = b.build_one({**course, "title": "超时对象"})
811
+ ck(unknown["status"] == "pending" and b.call.call_count == 1, "超时创建只发一次且保存 pending")
812
+ b.call.reset_mock()
813
+ with patch("time.sleep"):
814
+ unknown_retry = b.build_one({**course, "title": "超时对象"})
815
+ ck(unknown_retry["status"] == "pending" and not b.call.called
816
+ and b.candidates.called, "无 UUID 恢复只精确诊断不新建")
817
+
818
+ failed = [label for ok_, label in cases if not ok_]
819
+ for ok_, label in cases:
820
+ print(" %s %s" % ("PASS" if ok_ else "FAIL", label))
821
+ print(json.dumps({"ok": not failed, "assertions": len(cases)}, ensure_ascii=False))
822
+ return 0 if not failed else 1
823
+
824
+
825
+ def main() -> int:
826
+ if "--self-test" in sys.argv[1:]:
827
+ return self_test()
828
+ ap = argparse.ArgumentParser(description="DEMO 建课流水线(分类+图库封面+课件+发布+六项回读)")
829
+ ap.add_argument("--blueprint", required=True, help="DEMO-BLUEPRINT.json 绝对路径")
830
+ ap.add_argument("--out-dir", help="产物目录,默认 = BLUEPRINT 所在目录")
831
+ ap.add_argument("--taxonomy-map", help="分类树映射表,默认同目录 taxonomy-map.json")
832
+ ap.add_argument("--photo-map", help="图片库绑定表,默认同目录 photo-map.json")
833
+ ap.add_argument("--cli", help="soke-cli 路径,默认自动探测")
834
+ ap.add_argument("--pptx", default=DEFAULT_PPTX, help="文档或用户显式指定的课件路径;缺失时待明确,不上传默认占位课件")
835
+ ap.add_argument("--only", help="只建指定标题的课程")
836
+ ap.add_argument("--force", action="store_true", help="回读修补已登记对象;不绕过创建尝试记录、不强制重建")
837
+ ap.add_argument("--allow-dup", action="store_true",
838
+ help="已停用:不允许绕过本次创建恢复护栏")
839
+ ap.add_argument("--assign-user", help="指派对象 dept_user_id(默认取 config show 的「用户ID」=创建者)")
840
+ ap.add_argument("--assign-name", help="指派对象姓名(仅回显用,缺省同 --assign-user)")
841
+ ap.add_argument("--dry-run", action="store_true", help="只打印计划,不写平台")
842
+ ap.add_argument("--sleep", type=float, default=3.0, help="写调用间隔秒数(限流护栏)")
843
+ args = ap.parse_args()
844
+
845
+ if not os.path.isfile(args.blueprint):
846
+ raise SystemExit(f"BLUEPRINT 不存在:{args.blueprint}")
847
+ if not args.pptx or not os.path.isfile(args.pptx):
848
+ print(json.dumps({"ok": False, "status": "pending",
849
+ "reason": "课件待明确:请按文档显式指定有效 --pptx 或 DEMO_PPTX;未执行平台写入,不自动挂占位课件或发布空课",
850
+ "blueprint": os.path.abspath(args.blueprint)}, ensure_ascii=False))
851
+ return 2
852
+ args.out_dir = args.out_dir or os.path.dirname(os.path.abspath(args.blueprint))
853
+ return Builder(args).run()
854
+
855
+
856
+ if __name__ == "__main__":
857
+ sys.exit(main())