@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,390 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """blueprint_write.py — DEMO-BLUEPRINT.json 的**唯一写入口**。
4
+
5
+ 为什么必须收口
6
+ --------------
7
+ 2026-10-22 的老乡鸡 DEMO 里,BLUEPRINT 被直接改写两次:17:58 写坏成非法 JSON
8
+ (第 300 行 `"name": "食安 {`),18:01 又整份重写才恢复。中间没有任何一次校验——
9
+ 因为写它的是人手/手写脚本,不是受控通道。蓝图是单源事实文件,一旦坏掉,
10
+ 下游(scope_plan / blueprint_lint / gen_assets / 全部构建器)同时失效,且没人知道坏在哪。
11
+
12
+ 本脚本做四件事,缺一不可:
13
+ 1. **合并**:patch 按 key/name/title 递归匹配,不整份覆盖
14
+ 2. **校验**:结构自检 + 调 blueprint_lint(可 --no-lint 跳过)
15
+ 3. **备份**:写前留 `<bp>.bak.<时间戳>`,可回滚
16
+ 4. **原子替换 + 回读**:tmp → os.replace → 重新 load 确认可解析
17
+
18
+ ⛔ 任何 `open(bp, "w")` 直写都属于违反本纪律,包括临时脚本。
19
+
20
+ 用法
21
+ ----
22
+ <PY> blueprint_write.py <bp.json> --check
23
+ <PY> blueprint_write.py <bp.json> --patch <patch.json>
24
+ <PY> blueprint_write.py <bp.json> --patch <patch.json> --no-lint
25
+ <PY> blueprint_write.py <bp.json> --patch <patch.json> --dry
26
+ <PY> blueprint_write.py --self-test
27
+
28
+ patch 形态(只写要改的部分,list 按 key 匹配):
29
+ {
30
+ "assets": [{"key": "cover.course.c1", "status": "ready", "photo_uri": "https://…"}],
31
+ "exams": [{"name": "食安月度考核", "uuid": "9E87…"}],
32
+ "meta": {"confirmed_at": "2026-10-22T17:39:45+08:00"}
33
+ }
34
+
35
+ 退出码
36
+ ------
37
+ 0 = 写入成功(或 --check 通过)
38
+ 2 = 被拒绝(非法 JSON / 结构不合 / lint 阻断);此时**原文件未被改动**
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import argparse
44
+ import copy
45
+ import json
46
+ import os
47
+ import shutil
48
+ import subprocess
49
+ import sys
50
+ from datetime import datetime
51
+
52
+ HERE = os.path.dirname(os.path.abspath(__file__))
53
+ LINT = os.path.join(HERE, "blueprint_lint.py")
54
+
55
+ # list 元素的匹配键,按优先级
56
+ MATCH_KEYS = ("key", "name", "title", "id")
57
+ # 顶层必需键(缺任一即拒绝——蓝图被截断/写坏的典型形态)
58
+ REQUIRED_TOP = ("meta", "customer", "assets")
59
+ # 这些键允许"整个替换"而不是按元素合并
60
+ REPLACE_LISTS = ("timeline",)
61
+
62
+
63
+ # ------------------------------------------------------------------ 合并
64
+
65
+ def _match_key(item):
66
+ if not isinstance(item, dict):
67
+ return None
68
+ for k in MATCH_KEYS:
69
+ v = item.get(k)
70
+ if isinstance(v, (str, int)) and str(v).strip():
71
+ return k, str(v)
72
+ return None
73
+
74
+
75
+ def merge(old, new, path=""):
76
+ """递归合并。dict 深合并;list 按 key 匹配后合并,未匹配的 append。"""
77
+ if isinstance(old, dict) and isinstance(new, dict):
78
+ out = dict(old)
79
+ for k, v in new.items():
80
+ p = "%s.%s" % (path, k) if path else k
81
+ out[k] = merge(old[k], v, p) if k in old else v
82
+ return out
83
+
84
+ if isinstance(old, list) and isinstance(new, list):
85
+ base = path.split(".")[-1]
86
+ if base in REPLACE_LISTS:
87
+ return list(new)
88
+
89
+ out = list(old)
90
+ index = {}
91
+ for i, it in enumerate(out):
92
+ mk = _match_key(it)
93
+ if mk:
94
+ index.setdefault(mk, i)
95
+ for it in new:
96
+ mk = _match_key(it)
97
+ if mk and mk in index:
98
+ i = index[mk]
99
+ out[i] = merge(out[i], it, path)
100
+ else:
101
+ out.append(it)
102
+ if mk:
103
+ index[mk] = len(out) - 1
104
+ return out
105
+
106
+ return new
107
+
108
+
109
+ def diff_keys(old, new, path="", acc=None):
110
+ """返回被改动的路径列表(用于写日志,不含值)。"""
111
+ if acc is None:
112
+ acc = []
113
+ if isinstance(old, dict) and isinstance(new, dict):
114
+ for k in set(old) | set(new):
115
+ p = "%s.%s" % (path, k) if path else k
116
+ if k not in old or k not in new:
117
+ acc.append(p)
118
+ else:
119
+ diff_keys(old[k], new[k], p, acc)
120
+ elif isinstance(old, list) and isinstance(new, list):
121
+ if len(old) != len(new):
122
+ acc.append("%s(len %d→%d)" % (path, len(old), len(new)))
123
+ else:
124
+ for i, (a, b) in enumerate(zip(old, new)):
125
+ diff_keys(a, b, "%s[%d]" % (path, i), acc)
126
+ elif old != new:
127
+ acc.append(path)
128
+ return acc
129
+
130
+
131
+ # ------------------------------------------------------------------ 校验
132
+
133
+ def check_structure(bp):
134
+ """结构自检:返回 (ok, [问题])。只查"坏档/missing"级别,业务闸门交给 lint。"""
135
+ bad = []
136
+ if not isinstance(bp, dict):
137
+ return False, ["顶层不是对象(可能是数组或截断)"]
138
+ for k in REQUIRED_TOP:
139
+ if k not in bp:
140
+ bad.append("缺少顶层键 %r" % k)
141
+ if not isinstance(bp.get("meta"), dict):
142
+ bad.append("meta 必须是对象")
143
+ else:
144
+ if not bp["meta"].get("blueprint_id"):
145
+ bad.append("meta.blueprint_id 缺失")
146
+ if "assets" in bp and not isinstance(bp["assets"], list):
147
+ bad.append("assets 必须是数组")
148
+ for a in (bp.get("assets") or []):
149
+ if not isinstance(a, dict) or not a.get("key"):
150
+ bad.append("assets 里有元素缺 key")
151
+ break
152
+ for c in (bp.get("courses") or []):
153
+ if isinstance(c, dict) and c.get("category_path") is not None:
154
+ if not isinstance(c["category_path"], (list, str)):
155
+ bad.append("courses[].category_path 必须是数组或字符串")
156
+ break
157
+ return (not bad), bad
158
+
159
+
160
+ def run_lint(bp_path):
161
+ """调 blueprint_lint.py;返回 (ok, 摘要)。lint 脚本缺失时不阻断(视为跳过)。"""
162
+ if not os.path.isfile(LINT):
163
+ return True, "blueprint_lint.py 不存在(跳过)"
164
+ try:
165
+ p = subprocess.run([sys.executable, LINT, bp_path, "--json"],
166
+ capture_output=True, text=True, timeout=180)
167
+ except Exception as exc: # noqa: BLE001
168
+ return True, "lint 调用异常(跳过):%s" % exc
169
+ out = p.stdout or ""
170
+ i = out.find("{")
171
+ if i >= 0:
172
+ try:
173
+ obj = json.JSONDecoder().raw_decode(out, i)[0]
174
+ # blueprint_lint --json 的形态:{"ok": bool, "rows": [{gate, ok, level, detail}]}
175
+ rows = obj.get("rows") or obj.get("items") or obj.get("results") or []
176
+ blocks = [x for x in rows if not x.get("ok", True)]
177
+ if obj.get("ok") and p.returncode == 0:
178
+ return True, "lint 通过(%d 闸门)" % len(rows)
179
+ names = ["%s %s" % (x.get("gate") or "?", (x.get("detail") or "")[:40])
180
+ for x in blocks][:4]
181
+ return False, "lint 阻断 %d 项:%s" % (len(blocks), ";".join(names))
182
+ except Exception: # noqa: BLE001
183
+ pass
184
+ return (p.returncode == 0), "lint rc=%d %s" % (p.returncode, (p.stderr or "")[:120])
185
+
186
+
187
+ # ------------------------------------------------------------------ 写入
188
+
189
+ def _stamp():
190
+ return datetime.now().strftime("%Y%m%d-%H%M%S")
191
+
192
+
193
+ def write_atomic(path, data, backup=True):
194
+ """备份 → tmp 写 → 回读校验 → os.replace。返回备份路径。"""
195
+ bak = None
196
+ if backup and os.path.isfile(path):
197
+ bak = "%s.bak.%s" % (path, _stamp())
198
+ shutil.copy2(path, bak)
199
+
200
+ tmp = path + ".tmp"
201
+ with open(tmp, "w", encoding="utf-8") as fh:
202
+ json.dump(data, fh, ensure_ascii=False, indent=2)
203
+ fh.write("\n")
204
+ fh.flush()
205
+ os.fsync(fh.fileno())
206
+ # 回读:确保落盘内容可解析且与内存一致,再替换
207
+ with open(tmp, encoding="utf-8") as fh:
208
+ again = json.load(fh)
209
+ if again != data:
210
+ os.remove(tmp)
211
+ raise SystemExit("回读不一致,已放弃写入(原文件未改动)")
212
+ os.replace(tmp, path)
213
+ return bak
214
+
215
+
216
+ def log(demo_root, msg):
217
+ try:
218
+ sys.path.insert(0, HERE)
219
+ import guard
220
+ guard.append_log(demo_root, "blueprint-write", msg, src="script")
221
+ except Exception: # noqa: BLE001
222
+ pass
223
+
224
+
225
+ # ------------------------------------------------------------------ 自测
226
+
227
+ def self_test():
228
+ n, bad = 0, []
229
+
230
+ def ck(cond, label):
231
+ nonlocal n
232
+ n += 1
233
+ if not cond:
234
+ bad.append(label)
235
+
236
+ # dict 深合并
237
+ a = {"meta": {"id": "x", "n": 1}, "keep": True}
238
+ b = merge(a, {"meta": {"n": 2}})
239
+ ck(b["meta"] == {"id": "x", "n": 2} and b["keep"] is True, "dict 深合并保留未提及字段")
240
+
241
+ # list 按 key 合并 + append
242
+ old = {"assets": [{"key": "a", "status": "pending"}, {"key": "b", "status": "pending"}]}
243
+ new = {"assets": [{"key": "b", "status": "ready"}, {"key": "c", "status": "ready"}]}
244
+ m = merge(old, new)
245
+ ck(len(m["assets"]) == 3, "list 未匹配 append")
246
+ ck([x for x in m["assets"] if x["key"] == "b"][0]["status"] == "ready", "list 按 key 合并")
247
+ ck([x for x in m["assets"] if x["key"] == "a"][0]["status"] == "pending", "未提及元素不动")
248
+
249
+ # name / title 也作为匹配键
250
+ m2 = merge({"exams": [{"name": "E1", "v": 1}]}, {"exams": [{"name": "E1", "v": 2}]})
251
+ ck(len(m2["exams"]) == 1 and m2["exams"][0]["v"] == 2, "按 name 匹配合并")
252
+
253
+ # 标量覆盖
254
+ ck(merge(1, 2) == 2 and merge("a", "b") == "b", "标量覆盖")
255
+
256
+ # 结构校验
257
+ ok, msgs = check_structure({"meta": {"blueprint_id": "x"}, "customer": "C", "assets": []})
258
+ ck(ok, "最小合法蓝图通过")
259
+ ok2, msgs2 = check_structure({"meta": {}, "assets": [{"x": 1}]})
260
+ ck(not ok2 and any("blueprint_id" in m for m in msgs2), "缺 blueprint_id 被拒")
261
+ ok3, _ = check_structure([])
262
+ ck(not ok3, "顶层数组被拒")
263
+ ok4, msgs4 = check_structure({"meta": {"blueprint_id": "x"}, "customer": "C",
264
+ "assets": [], "courses": [{"category_path": 5}]})
265
+ ck(not ok4 and any("category_path" in m for m in msgs4), "category_path 类型错被拒")
266
+
267
+ # diff
268
+ d = diff_keys({"a": 1, "b": {"c": 1}}, {"a": 1, "b": {"c": 2}})
269
+ ck(d == ["b.c"], "diff 只报变化路径")
270
+
271
+ # 原子写(临时目录)
272
+ import tempfile
273
+ with tempfile.TemporaryDirectory() as td:
274
+ p = os.path.join(td, "bp.json")
275
+ with open(p, "w", encoding="utf-8") as fh:
276
+ json.dump({"meta": {"blueprint_id": "x"}, "customer": "C", "assets": []}, fh)
277
+ bak = write_atomic(p, {"meta": {"blueprint_id": "x"}, "customer": "C",
278
+ "assets": [{"key": "a"}]})
279
+ ck(bak and os.path.isfile(bak), "生成备份")
280
+ with open(p, encoding="utf-8") as fh:
281
+ got = json.load(fh)
282
+ ck(got["assets"] == [{"key": "a"}], "写入生效且可解析")
283
+ # 原文件仍是合法 JSON(坏档不可能落盘)
284
+ ck(bool(bak), "备份路径非空")
285
+
286
+ for label in bad:
287
+ print(" ✗ %s" % label)
288
+ print("blueprint_write self-test: %d 项,%d 失败" % (n, len(bad)))
289
+ return 0 if not bad else 1
290
+
291
+
292
+ # ------------------------------------------------------------------ main
293
+
294
+ def main(argv=None):
295
+ ap = argparse.ArgumentParser(description="蓝图唯一写入口")
296
+ ap.add_argument("bp", nargs="?")
297
+ ap.add_argument("--patch")
298
+ ap.add_argument("--check", action="store_true")
299
+ ap.add_argument("--no-lint", action="store_true")
300
+ ap.add_argument("--dry", action="store_true")
301
+ ap.add_argument("--no-backup", action="store_true")
302
+ ap.add_argument("--self-test", action="store_true")
303
+ args = ap.parse_args(argv)
304
+
305
+ if args.self_test:
306
+ return self_test()
307
+ if not args.bp:
308
+ ap.error("需要蓝图路径(除 --self-test)")
309
+
310
+ bp_path = os.path.abspath(args.bp)
311
+ if not os.path.isfile(bp_path):
312
+ print("✗ 蓝图不存在:%s" % bp_path)
313
+ return 2
314
+
315
+ # 读原文件——不可解析就是"已经坏了",直接拒绝,不做自动修复
316
+ try:
317
+ with open(bp_path, encoding="utf-8") as fh:
318
+ old = json.load(fh)
319
+ except json.JSONDecodeError as exc:
320
+ print("✗ 蓝图当前已不可解析(%s),拒绝在其上再写。先人工/备份恢复。" % exc)
321
+ return 2
322
+
323
+ ok, msgs = check_structure(old)
324
+ if not ok:
325
+ print("✗ 蓝图结构不合:%s" % ";".join(msgs))
326
+ return 2
327
+
328
+ if args.check:
329
+ lok, lmsg = run_lint(bp_path)
330
+ print("结构 ✓ %s" % ("lint ✓ " + lmsg if lok else "lint ✗ " + lmsg))
331
+ return 0 if lok else 2
332
+
333
+ if not args.patch:
334
+ ap.error("需要 --patch 或 --check")
335
+
336
+ try:
337
+ with open(args.patch, encoding="utf-8") as fh:
338
+ patch = json.load(fh)
339
+ except Exception as exc: # noqa: BLE001
340
+ print("✗ patch 不可解析:%s" % exc)
341
+ return 2
342
+
343
+ new = merge(copy.deepcopy(old), patch)
344
+ new.setdefault("meta", {})
345
+ new["meta"]["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
346
+ new["meta"]["write_seq"] = int(old.get("meta", {}).get("write_seq") or 0) + 1
347
+ new["meta"]["last_writer"] = "blueprint_write.py"
348
+
349
+ ok, msgs = check_structure(new)
350
+ if not ok:
351
+ print("✗ 合并后结构不合,已放弃:%s" % ";".join(msgs))
352
+ return 2
353
+
354
+ changed = diff_keys(old, new)
355
+ demo_root = os.path.dirname(bp_path)
356
+
357
+ if args.dry:
358
+ print("DRY 将改动 %d 处:%s" % (len(changed), "、".join(changed[:12])))
359
+ return 0
360
+
361
+ bp_tmp = bp_path + ".candidate"
362
+ with open(bp_tmp, "w", encoding="utf-8") as fh:
363
+ json.dump(new, fh, ensure_ascii=False, indent=2)
364
+
365
+ if not args.no_lint:
366
+ lok, lmsg = run_lint(bp_tmp)
367
+ if not lok:
368
+ os.remove(bp_tmp)
369
+ print("✗ lint 阻断,已放弃写入(原文件未改动):%s" % lmsg)
370
+ return 2
371
+ else:
372
+ lmsg = "lint 已跳过(--no-lint)"
373
+ os.remove(bp_tmp)
374
+
375
+ bak = write_atomic(bp_path, new, backup=not args.no_backup)
376
+ log(demo_root, "write ok seq=%d changed=%d lint=%s bak=%s"
377
+ % (new["meta"]["write_seq"], len(changed), lmsg.split(" ")[0],
378
+ os.path.basename(bak or "-")))
379
+
380
+ print("✓ 已写入 %s(seq=%d,改动 %d 处,%s)"
381
+ % (os.path.basename(bp_path), new["meta"]["write_seq"], len(changed), lmsg))
382
+ if bak:
383
+ print(" 备份:%s" % os.path.basename(bak))
384
+ if changed:
385
+ print(" 字段:%s" % "、".join(changed[:12]))
386
+ return 0
387
+
388
+
389
+ if __name__ == "__main__":
390
+ sys.exit(main())