@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.
- package/package.json +1 -1
- package/skills/multi/demo-init/CHANGELOG.md +1241 -0
- package/skills/multi/demo-init/README.md +137 -0
- package/skills/multi/demo-init/SKILL.legacy.md +307 -0
- package/skills/multi/demo-init/assets/placeholder.pptx +0 -0
- package/skills/multi/demo-init/references/anti-patterns.md +83 -0
- package/skills/multi/demo-init/references/asset-design.md +230 -0
- package/skills/multi/demo-init/references/asset-spec.md +94 -0
- package/skills/multi/demo-init/references/blueprint-schema.md +174 -0
- package/skills/multi/demo-init/references/cli-onboarding.md +207 -0
- package/skills/multi/demo-init/references/cli-shared.md +183 -0
- package/skills/multi/demo-init/references/contracts.md +34 -0
- package/skills/multi/demo-init/references/course-setup.md +265 -0
- package/skills/multi/demo-init/references/demo-defaults.md +132 -0
- package/skills/multi/demo-init/references/demo-verify.md +355 -0
- package/skills/multi/demo-init/references/exam-setup.md +245 -0
- package/skills/multi/demo-init/references/gates-matrix.md +38 -0
- package/skills/multi/demo-init/references/map-setup.md +283 -0
- package/skills/multi/demo-init/references/plan-parse.md +185 -0
- package/skills/multi/demo-init/references/platform-access.md +55 -0
- package/skills/multi/demo-init/references/platform-commands.md +510 -0
- package/skills/multi/demo-init/references/point-setup.md +308 -0
- package/skills/multi/demo-init/references/portal-modules.md +130 -0
- package/skills/multi/demo-init/references/portal-setup.md +342 -0
- package/skills/multi/demo-init/references/project-setup.md +173 -0
- package/skills/multi/demo-init/references/run-protocol.md +208 -0
- package/skills/multi/demo-init/references/taxonomy-setup.md +101 -0
- package/skills/multi/demo-init/scripts/assign_backfill.py +281 -0
- package/skills/multi/demo-init/scripts/blueprint_lint.py +693 -0
- package/skills/multi/demo-init/scripts/blueprint_write.py +390 -0
- package/skills/multi/demo-init/scripts/category_bind.py +303 -0
- package/skills/multi/demo-init/scripts/category_create.py +748 -0
- package/skills/multi/demo-init/scripts/category_reassign.py +405 -0
- package/skills/multi/demo-init/scripts/category_verify.py +373 -0
- package/skills/multi/demo-init/scripts/cli_kit.py +597 -0
- package/skills/multi/demo-init/scripts/cli_probe.py +205 -0
- package/skills/multi/demo-init/scripts/course_build.py +857 -0
- package/skills/multi/demo-init/scripts/course_cover_repair.py +243 -0
- package/skills/multi/demo-init/scripts/doc_lint.py +619 -0
- package/skills/multi/demo-init/scripts/dup_cleanup.py +299 -0
- package/skills/multi/demo-init/scripts/dup_scan.py +368 -0
- package/skills/multi/demo-init/scripts/exam_build.py +551 -0
- package/skills/multi/demo-init/scripts/extract_docx.py +370 -0
- package/skills/multi/demo-init/scripts/gen_assets.py +1366 -0
- package/skills/multi/demo-init/scripts/guard.py +1272 -0
- package/skills/multi/demo-init/scripts/map_rebuild.py +391 -0
- package/skills/multi/demo-init/scripts/oss_image_upload.py +367 -0
- package/skills/multi/demo-init/scripts/portal_build.py +450 -0
- package/skills/multi/demo-init/scripts/portal_home_apply.py +255 -0
- package/skills/multi/demo-init/scripts/portal_home_layout.py +398 -0
- package/skills/multi/demo-init/scripts/project_build.py +309 -0
- package/skills/multi/demo-init/scripts/rebuild_taxonomy_map.py +100 -0
- package/skills/multi/demo-init/scripts/scope_plan.py +387 -0
- package/skills/multi/demo-init/scripts/selftest_all.py +211 -0
- package/skills/multi/demo-init/scripts/stock_probe.py +452 -0
- package/skills/multi/demo-init/scripts/taxonomy_build.py +512 -0
- package/skills/multi/demo-init-4.1.0.zip +0 -0
- package/skills/multi/demo-init-4.1.1.zip +0 -0
- package/skills/multi/demo-init-4.1.2.zip +0 -0
- package/skills/multi/demo-init-4.1.3.zip +0 -0
- package/skills/multi/ziQIJJpL +0 -0
- package/skills/multi/ziRsINis +0 -0
- package/skills/multi/ziUjKWRm +0 -0
- package/skills/multi/zipFWfuj +0 -0
|
@@ -0,0 +1,1272 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""DEMO 会话守卫:单实例锁 / 统一日志 / 状态单源台账 / 临时文件清理。
|
|
4
|
+
|
|
5
|
+
存在理由(2026-10-21 loong-20261021 实战事故):
|
|
6
|
+
1) 上一轮被打断的脚本没死透,用户以为已停,后台又跑了一遍建课
|
|
7
|
+
→ 平台上「民航安保与保密要求」「客舱失压与氧气处置」各 2 份;
|
|
8
|
+
2) 门户被建了 2 个同名「长龙学堂」(两个进程各建一次);
|
|
9
|
+
3) run.log 里同一秒出现 9 行 portal 记录、asset 的"上传"早于"渲染"
|
|
10
|
+
→ 日志事后回填,时间戳不可信,无法复盘;
|
|
11
|
+
4) progress-ledger.md 停在「plan-parse 待确认」,state.json 已是 done
|
|
12
|
+
→ 人读/机读双源不一致,续跑必错判;
|
|
13
|
+
5) 工作目录残留 10 个 .soke-portal-*.json 临时文件。
|
|
14
|
+
|
|
15
|
+
本脚本把上述五件事收敛成一条命令面:
|
|
16
|
+
acquire 开工取锁(flock 原子 + pid 存活判定,残留锁自动接管)
|
|
17
|
+
release 收工释放(--status ok|failed|interrupted)
|
|
18
|
+
state **唯一写 state.json 的入口**(v4.1.0:原子合并写 + 字段只增不删 + 自动重渲台账)
|
|
19
|
+
status 锁与人读/机读状态是否自洽
|
|
20
|
+
log 严格单行、实时、带 src 的日志写入(脚本/编排层共用)
|
|
21
|
+
ledger 从 state.json 渲染 progress-ledger.md(禁止手写双源)
|
|
22
|
+
clean 清理已知临时文件(默认 dry-run)
|
|
23
|
+
|
|
24
|
+
用法:
|
|
25
|
+
<PY> guard.py acquire --demo-root <dir> --module course-setup
|
|
26
|
+
<PY> guard.py state --demo-root <dir> --module course-setup --status done \
|
|
27
|
+
--outputs course-ids.json,course-verify.json --verify "六项回读 PASS"
|
|
28
|
+
<PY> guard.py release --demo-root <dir> --module course-setup --status ok
|
|
29
|
+
<PY> guard.py log --demo-root <dir> --module course-setup --msg "create ok title=… uuid=…" --src script
|
|
30
|
+
<PY> guard.py ledger --demo-root <dir>
|
|
31
|
+
<PY> guard.py clean --demo-root <dir> [--apply]
|
|
32
|
+
<PY> guard.py --self-test
|
|
33
|
+
|
|
34
|
+
⛔ v4.1.0 起 state.json **只允许**由 `state` 子命令写(含脚本内部调用)。手写 state 等于绕开
|
|
35
|
+
原子合并与台账重渲,是最常见的"续跑跑错模块"来源。
|
|
36
|
+
|
|
37
|
+
退出码:0 正常;3 锁被另一个活进程持有(禁止开工);4 参数/环境错误;1 自检失败。
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import argparse
|
|
43
|
+
import datetime
|
|
44
|
+
import glob
|
|
45
|
+
import json
|
|
46
|
+
import os
|
|
47
|
+
import re
|
|
48
|
+
import sys
|
|
49
|
+
|
|
50
|
+
LOCK_NAME = ".demo-init.lock"
|
|
51
|
+
RUN_LOG = "run.log"
|
|
52
|
+
STATE = "state.json"
|
|
53
|
+
LEDGER = "progress-ledger.md"
|
|
54
|
+
|
|
55
|
+
# 已知可安全清理的临时产物(只匹配 CLI/脚本自己拉出来的短命文件)
|
|
56
|
+
TEMP_PATTERNS = [
|
|
57
|
+
".soke-portal-*.json",
|
|
58
|
+
"*.tmp",
|
|
59
|
+
"nohup.out",
|
|
60
|
+
"*.json.tmp",
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
# 日志契约:一行一条、统一时间格式、模块名小写连字符
|
|
64
|
+
MODULE_RE = re.compile(r"^[a-z][a-z0-9-]{1,30}$")
|
|
65
|
+
# 模块名别名 → 规范名。2026-10-21 loong:同一模块在日志里写成 `category-setup`,
|
|
66
|
+
# state.json 里叫 `taxonomy-setup`,audit-log 因此报"缺 RUN SUMMARY"(假阳性)。
|
|
67
|
+
MODULE_ALIASES = {
|
|
68
|
+
"category-setup": "taxonomy-setup",
|
|
69
|
+
"category_setup": "taxonomy-setup",
|
|
70
|
+
"taxonomy": "taxonomy-setup",
|
|
71
|
+
"asset": "asset-design",
|
|
72
|
+
"assets": "asset-design",
|
|
73
|
+
"exam": "exam-setup",
|
|
74
|
+
"course": "course-setup",
|
|
75
|
+
"map": "map-setup",
|
|
76
|
+
"portal": "portal-setup",
|
|
77
|
+
"project": "project-setup",
|
|
78
|
+
"class": "project-setup",
|
|
79
|
+
"verify": "demo-verify",
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def canon_module(name: str) -> str:
|
|
84
|
+
"""把日志/state 里的模块名归一到同一套规范名(写入与审计都用它)。"""
|
|
85
|
+
low = (name or "").strip().lower().replace("_", "-")
|
|
86
|
+
return MODULE_ALIASES.get(low, low)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# 调度顺序(SKILL.md「子模块清单与调度顺序」)。state 里 seq 由它推导,
|
|
90
|
+
# 不再由模型手填——手填错 seq 会让"续跑从第一个未完成模块开始"跳错位置。
|
|
91
|
+
MODULE_ORDER = [
|
|
92
|
+
"cli-onboarding", "plan-parse", "asset-design", "portal-setup", "taxonomy-setup",
|
|
93
|
+
"course-setup", "exam-setup", "map-setup", "project-setup", "point-setup", "demo-verify",
|
|
94
|
+
]
|
|
95
|
+
MODULE_STATUS = ("pending", "running", "done", "failed", "skipped")
|
|
96
|
+
TS_FMT = "%Y-%m-%d %H:%M:%S"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def now_ts() -> str:
|
|
100
|
+
return datetime.datetime.now().strftime(TS_FMT)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def jload(path: str, default=None):
|
|
104
|
+
if not os.path.isfile(path):
|
|
105
|
+
return default
|
|
106
|
+
try:
|
|
107
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
108
|
+
return json.load(fh)
|
|
109
|
+
except Exception:
|
|
110
|
+
return default
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def jdump(path: str, data) -> None:
|
|
114
|
+
tmp = path + ".tmp"
|
|
115
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
116
|
+
json.dump(data, fh, ensure_ascii=False, indent=2)
|
|
117
|
+
os.replace(tmp, path)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def pid_alive(pid: int) -> bool:
|
|
121
|
+
if pid <= 0:
|
|
122
|
+
return False
|
|
123
|
+
try:
|
|
124
|
+
os.kill(pid, 0)
|
|
125
|
+
except ProcessLookupError:
|
|
126
|
+
return False
|
|
127
|
+
except PermissionError:
|
|
128
|
+
return True
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------------------ 日志
|
|
133
|
+
|
|
134
|
+
def append_log(demo_root: str, module: str, msg: str, src: str = "script") -> str:
|
|
135
|
+
"""单行实时追加。⛔ 禁换行、禁回填历史时间、禁整段 payload。"""
|
|
136
|
+
if not re.match(r"^[a-z][a-z0-9_-]{1,30}$", module or ""):
|
|
137
|
+
raise SystemExit(f"模块名不合契约(小写连字符):{module!r}")
|
|
138
|
+
module = canon_module(module)
|
|
139
|
+
if not MODULE_RE.match(module or ""):
|
|
140
|
+
raise SystemExit(f"模块名不合契约(小写连字符):{module!r}")
|
|
141
|
+
clean = " ".join(str(msg).split()) # 换行/多空格压成一行
|
|
142
|
+
if len(clean) > 200: # 前 120 字符是文档契约,留 200 防丢关键 id
|
|
143
|
+
clean = clean[:200] + "…"
|
|
144
|
+
line = f"[{now_ts()}] [{module}] {clean} (src={src})\n"
|
|
145
|
+
path = os.path.join(demo_root, RUN_LOG)
|
|
146
|
+
os.makedirs(demo_root, exist_ok=True)
|
|
147
|
+
with open(path, "a", encoding="utf-8") as fh:
|
|
148
|
+
fh.write(line)
|
|
149
|
+
fh.flush()
|
|
150
|
+
os.fsync(fh.fileno())
|
|
151
|
+
return line.rstrip("\n")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# ------------------------------------------------------------------ 锁
|
|
155
|
+
|
|
156
|
+
def lock_path(demo_root: str) -> str:
|
|
157
|
+
return os.path.join(demo_root, LOCK_NAME)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def read_lock(demo_root: str) -> dict:
|
|
161
|
+
return jload(lock_path(demo_root), {}) or {}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _acquire_fs_lock(fh):
|
|
165
|
+
"""跨平台非阻塞独占锁。
|
|
166
|
+
|
|
167
|
+
返回 (ok, unlock)。ok=False 表示已被别人持有。
|
|
168
|
+
- POSIX:fcntl.flock
|
|
169
|
+
- Windows:msvcrt.locking(v3.29.0 补,原实现只有 fcntl → Windows 上直接退化成 pid 判定,
|
|
170
|
+
两个进程同时开工时存在竞态窗口)
|
|
171
|
+
- 两者都没有:返回 (True, None),退化为既有 pid 判定行为
|
|
172
|
+
"""
|
|
173
|
+
try:
|
|
174
|
+
import fcntl
|
|
175
|
+
except ImportError:
|
|
176
|
+
fcntl = None
|
|
177
|
+
if fcntl:
|
|
178
|
+
try:
|
|
179
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
180
|
+
except (BlockingIOError, OSError):
|
|
181
|
+
return False, None
|
|
182
|
+
|
|
183
|
+
def _unlock():
|
|
184
|
+
try:
|
|
185
|
+
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
|
186
|
+
except Exception:
|
|
187
|
+
pass
|
|
188
|
+
return True, _unlock
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
import msvcrt
|
|
192
|
+
except ImportError:
|
|
193
|
+
return True, None
|
|
194
|
+
try:
|
|
195
|
+
fh.seek(0)
|
|
196
|
+
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
|
|
197
|
+
except OSError:
|
|
198
|
+
return False, None
|
|
199
|
+
|
|
200
|
+
def _unlock_win():
|
|
201
|
+
try:
|
|
202
|
+
fh.seek(0)
|
|
203
|
+
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
|
|
204
|
+
except OSError:
|
|
205
|
+
pass
|
|
206
|
+
return True, _unlock_win
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def cmd_acquire(args) -> int:
|
|
210
|
+
root = os.path.abspath(args.demo_root)
|
|
211
|
+
os.makedirs(root, exist_ok=True)
|
|
212
|
+
path = lock_path(root)
|
|
213
|
+
|
|
214
|
+
# 文件锁保证「读-判-写」原子;拿到后立即释放,后续以 pid 存活为所有权判据
|
|
215
|
+
fh = open(path, "a+", encoding="utf-8")
|
|
216
|
+
ok, unlock = _acquire_fs_lock(fh)
|
|
217
|
+
try:
|
|
218
|
+
if not ok:
|
|
219
|
+
cur = read_lock(root)
|
|
220
|
+
print(json.dumps({"ok": False, "reason": "locked",
|
|
221
|
+
"holder": cur}, ensure_ascii=False))
|
|
222
|
+
return 3
|
|
223
|
+
cur = read_lock(root)
|
|
224
|
+
holder_pid = int(cur.get("pid") or 0)
|
|
225
|
+
if holder_pid and holder_pid != os.getpid() and pid_alive(holder_pid) and not args.force:
|
|
226
|
+
print(json.dumps({"ok": False, "reason": "alive", "holder": cur,
|
|
227
|
+
"hint": "另一进程正在施工;确认要抢占请加 --force"},
|
|
228
|
+
ensure_ascii=False))
|
|
229
|
+
return 3
|
|
230
|
+
rec = {
|
|
231
|
+
"pid": os.getpid(),
|
|
232
|
+
"module": args.module or "",
|
|
233
|
+
"started_at": now_ts(),
|
|
234
|
+
"host": os.uname().nodename if hasattr(os, "uname") else "",
|
|
235
|
+
"stale_from": cur if holder_pid and not pid_alive(holder_pid) else None,
|
|
236
|
+
}
|
|
237
|
+
jdump(path, rec)
|
|
238
|
+
if rec["stale_from"]:
|
|
239
|
+
append_log(root, "guard", f"takeover stale lock pid={holder_pid} "
|
|
240
|
+
f"module={(rec['stale_from'] or {}).get('module')}", "script")
|
|
241
|
+
append_log(root, "guard", f"lock acquired pid={os.getpid()} module={args.module or '-'}", "script")
|
|
242
|
+
print(json.dumps({"ok": True, "lock": rec}, ensure_ascii=False))
|
|
243
|
+
return 0
|
|
244
|
+
finally:
|
|
245
|
+
if unlock:
|
|
246
|
+
unlock()
|
|
247
|
+
fh.close()
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def cmd_release(args) -> int:
|
|
251
|
+
root = os.path.abspath(args.demo_root)
|
|
252
|
+
cur = read_lock(root)
|
|
253
|
+
if int(cur.get("pid") or 0) not in (0, os.getpid()) and not args.force:
|
|
254
|
+
print(json.dumps({"ok": False, "reason": "not_owner", "holder": cur}, ensure_ascii=False))
|
|
255
|
+
return 3
|
|
256
|
+
if os.path.isfile(lock_path(root)):
|
|
257
|
+
os.remove(lock_path(root))
|
|
258
|
+
if args.status:
|
|
259
|
+
append_log(root, "guard", f"release module={args.module or '-'} status={args.status}", "script")
|
|
260
|
+
print(json.dumps({"ok": True, "released": True}, ensure_ascii=False))
|
|
261
|
+
return 0
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def cmd_status(args) -> int:
|
|
265
|
+
root = os.path.abspath(args.demo_root)
|
|
266
|
+
cur = read_lock(root)
|
|
267
|
+
pid = int(cur.get("pid") or 0)
|
|
268
|
+
alive = pid_alive(pid) if pid else False
|
|
269
|
+
state = jload(os.path.join(root, STATE), {}) or {}
|
|
270
|
+
# 换机/搬目录检测:state.json 记录的 demo_root 与实际目录不一致时,模型若照 state 里的
|
|
271
|
+
# 绝对路径续跑,会指向不存在的位置(表现为"整段重来")。以实际目录为准并回写。
|
|
272
|
+
recorded_root = (state.get("demo_root") or "").rstrip("/")
|
|
273
|
+
root_moved = bool(recorded_root) and os.path.normpath(recorded_root) != os.path.normpath(root)
|
|
274
|
+
mods = state.get("modules") or []
|
|
275
|
+
done = [m["name"] for m in mods if m.get("status") in ("done", "skipped")]
|
|
276
|
+
running = [m["name"] for m in mods if m.get("status") == "running"]
|
|
277
|
+
failed = [m["name"] for m in mods if m.get("status") == "failed"]
|
|
278
|
+
pending = [m["name"] for m in mods if m.get("status") == "pending"]
|
|
279
|
+
|
|
280
|
+
# 有 SUMMARY 但无待处理说明时疑似漏更新;明确缺口的 pending 属合法状态。
|
|
281
|
+
log_path = os.path.join(root, RUN_LOG)
|
|
282
|
+
logged = set()
|
|
283
|
+
if os.path.isfile(log_path):
|
|
284
|
+
with open(log_path, "r", encoding="utf-8", errors="replace") as fh:
|
|
285
|
+
for line in fh:
|
|
286
|
+
m = re.search(r"\] \[([a-z][a-z0-9-]*)\] RUN SUMMARY", line)
|
|
287
|
+
if m:
|
|
288
|
+
logged.add(m.group(1))
|
|
289
|
+
|
|
290
|
+
suspicious = []
|
|
291
|
+
for name in pending:
|
|
292
|
+
alias = {"course-setup": {"course-build"},
|
|
293
|
+
"exam-setup": {"exam-build", "exam-setup"},
|
|
294
|
+
"map-setup": {"map-build", "map-setup"},
|
|
295
|
+
"project-setup": {"project-build"}}.get(name, {name})
|
|
296
|
+
hit = alias & logged
|
|
297
|
+
entry = next(m for m in mods if m.get("name") == name)
|
|
298
|
+
explanation = " ".join(str(entry.get(k) or "") for k in ("note", "verify"))
|
|
299
|
+
explained = bool(re.search(r"pending|待明确|待处理|待补|待验|未发布|未完成|未施工|缺少|缺失|无法|不支持|受限",
|
|
300
|
+
explanation, re.I))
|
|
301
|
+
if hit and not explained:
|
|
302
|
+
suspicious.append({"module": name, "state": "pending",
|
|
303
|
+
"evidence": sorted(hit),
|
|
304
|
+
"why": "run.log 已有该模块 RUN SUMMARY,state.json 未更新"})
|
|
305
|
+
|
|
306
|
+
# 更强信号:run.log 有 RUN SUMMARY,而 state.json 里根本没有这个模块
|
|
307
|
+
# (2026-10-22:portal/exam/assign/project 干了 5 个模块,state 只有 3 条,上面那段抓不到)
|
|
308
|
+
known = {canon_module(m.get("name", "")) for m in mods}
|
|
309
|
+
for name in sorted(logged - known):
|
|
310
|
+
suspicious.append({"module": name, "state": "missing",
|
|
311
|
+
"evidence": [name],
|
|
312
|
+
"why": "run.log 已有该模块 RUN SUMMARY,state.json 无该模块记录"})
|
|
313
|
+
|
|
314
|
+
# 台账是否落后
|
|
315
|
+
ledger_stale = False
|
|
316
|
+
lpath = os.path.join(root, LEDGER)
|
|
317
|
+
if os.path.isfile(lpath) and mods:
|
|
318
|
+
with open(lpath, "r", encoding="utf-8", errors="replace") as fh:
|
|
319
|
+
text = fh.read()
|
|
320
|
+
for name in done:
|
|
321
|
+
if name in text and "⬜" in text.split(name, 1)[-1][:40]:
|
|
322
|
+
ledger_stale = True
|
|
323
|
+
break
|
|
324
|
+
|
|
325
|
+
out = {
|
|
326
|
+
"ok": not (alive or suspicious or ledger_stale),
|
|
327
|
+
"demo_root": root,
|
|
328
|
+
"root_moved": ({"recorded": recorded_root, "actual": root,
|
|
329
|
+
"hint": "state.demo_root 指向别处(换机/搬目录):以 actual 为准续跑,"
|
|
330
|
+
"并把 state.demo_root 回写为 actual(禁止照旧路径访问)"}
|
|
331
|
+
if root_moved else None),
|
|
332
|
+
"lock": {"holder": cur or None, "alive": alive,
|
|
333
|
+
"stale": bool(cur) and not alive,
|
|
334
|
+
"hint": ("锁残留(持有进程已退出):下个模块 acquire 会自动接管并记 stale_from"
|
|
335
|
+
if cur and not alive else None)},
|
|
336
|
+
"modules": {"done": done, "running": running, "failed": failed, "pending": pending},
|
|
337
|
+
"suspects": suspicious,
|
|
338
|
+
"ledger_stale": ledger_stale,
|
|
339
|
+
}
|
|
340
|
+
print(json.dumps(out, ensure_ascii=False, indent=2))
|
|
341
|
+
return 0 if out["ok"] or args.report_only else 5
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
# ------------------------------------------------------------------ 台账
|
|
345
|
+
|
|
346
|
+
LEDGER_TPL = """# DEMO 进度台账({bid})
|
|
347
|
+
|
|
348
|
+
> 本文件由 `scripts/guard.py ledger` 从 `state.json` 渲染,**禁止手写**(双源必然不一致)。
|
|
349
|
+
> 最近渲染:{ts}
|
|
350
|
+
|
|
351
|
+
| 模块 | 状态 | 产出物 | 回验结果 | 待处理 |
|
|
352
|
+
|---|---|---|---|---|
|
|
353
|
+
"""
|
|
354
|
+
|
|
355
|
+
ICON = {"done": "✅", "running": "🔄", "failed": "🔴", "pending": "⬜", "skipped": "⏭"}
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def render_ledger(root: str, state: dict) -> str:
|
|
359
|
+
"""从 state 渲染 progress-ledger.md,返回落盘路径。state 是唯一事实源。"""
|
|
360
|
+
mods = state.get("modules") or []
|
|
361
|
+
if not mods:
|
|
362
|
+
raise SystemExit(f"state.json 缺失或 modules 为空:{root}")
|
|
363
|
+
lines = [LEDGER_TPL.format(bid=state.get("blueprint_id", ""), ts=now_ts())]
|
|
364
|
+
pending_all = state.get("pending") or []
|
|
365
|
+
ordered = sorted(mods, key=lambda m: (m.get("seq") or 99, m.get("name") or ""))
|
|
366
|
+
for m in ordered:
|
|
367
|
+
outs = ", ".join(m.get("outputs") or []) or "—"
|
|
368
|
+
note = m.get("note") or ("—" if m.get("status") == "done" else
|
|
369
|
+
";".join(pending_all[:2]) if pending_all else "—")
|
|
370
|
+
lines.append(f"| {m['name']} | {ICON.get(m.get('status'), '?')} {m.get('status')} "
|
|
371
|
+
f"| {outs} | {m.get('verify') or '—'} | {note} |\n")
|
|
372
|
+
lines.append("\n## 待处理(不进正文,交付时并入手册)\n\n")
|
|
373
|
+
for i, p in enumerate(pending_all, 1):
|
|
374
|
+
lines.append(f"{i}. {p}\n")
|
|
375
|
+
path = os.path.join(root, LEDGER)
|
|
376
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
377
|
+
fh.write("".join(lines))
|
|
378
|
+
return path
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def cmd_ledger(args) -> int:
|
|
382
|
+
root = os.path.abspath(args.demo_root)
|
|
383
|
+
state = jload(os.path.join(root, STATE), {}) or {}
|
|
384
|
+
path = render_ledger(root, state)
|
|
385
|
+
print(json.dumps({"ok": True, "ledger": path,
|
|
386
|
+
"rows": len(state.get("modules") or [])}, ensure_ascii=False))
|
|
387
|
+
return 0
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# ------------------------------------------------------------------ 状态(唯一写入口)
|
|
391
|
+
|
|
392
|
+
def _merge_unique(old, new):
|
|
393
|
+
"""列表合并保序去重;old 在前(历史产物不能因重跑被抹掉)。"""
|
|
394
|
+
out = []
|
|
395
|
+
for x in list(old or []) + list(new or []):
|
|
396
|
+
if x not in out:
|
|
397
|
+
out.append(x)
|
|
398
|
+
return out
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def cmd_state(args) -> int:
|
|
402
|
+
"""原子合并写 state.json(v4.1.0)。
|
|
403
|
+
|
|
404
|
+
- 读-改-写全程持文件锁,落盘走 os.replace(读方永远看不到半个文件)
|
|
405
|
+
- 合并语义:字段只增不删;未提供的字段保持原值;outputs 追加去重(--replace-outputs 才覆盖)
|
|
406
|
+
- seq 由 MODULE_ORDER 推导,⛔ 不接受外部指定
|
|
407
|
+
- 写完自动重渲 progress-ledger.md,人读/机读不再有第二个写入口
|
|
408
|
+
"""
|
|
409
|
+
root = os.path.abspath(args.demo_root)
|
|
410
|
+
os.makedirs(root, exist_ok=True)
|
|
411
|
+
name = canon_module(args.module)
|
|
412
|
+
if not MODULE_RE.match(name or ""):
|
|
413
|
+
print(json.dumps({"ok": False, "reason": "bad_module", "module": args.module,
|
|
414
|
+
"hint": "模块名必须小写连字符(如 course-setup)"}, ensure_ascii=False))
|
|
415
|
+
return 4
|
|
416
|
+
status = args.status
|
|
417
|
+
if status not in MODULE_STATUS:
|
|
418
|
+
print(json.dumps({"ok": False, "reason": "bad_status", "status": status,
|
|
419
|
+
"allowed": list(MODULE_STATUS)}, ensure_ascii=False))
|
|
420
|
+
return 4
|
|
421
|
+
|
|
422
|
+
path = os.path.join(root, STATE)
|
|
423
|
+
lockfh = open(path + ".lock", "a+", encoding="utf-8")
|
|
424
|
+
ok, unlock = _acquire_fs_lock(lockfh)
|
|
425
|
+
try:
|
|
426
|
+
if not ok:
|
|
427
|
+
print(json.dumps({"ok": False, "reason": "state_locked",
|
|
428
|
+
"hint": "另一进程正在写 state.json,稍后重试"}, ensure_ascii=False))
|
|
429
|
+
return 3
|
|
430
|
+
state = jload(path, {}) or {}
|
|
431
|
+
if not isinstance(state, dict):
|
|
432
|
+
state = {}
|
|
433
|
+
if args.blueprint_id:
|
|
434
|
+
state["blueprint_id"] = args.blueprint_id
|
|
435
|
+
state["demo_root"] = root # 换机/搬目录后以实际目录为准
|
|
436
|
+
mods = state.get("modules")
|
|
437
|
+
if not isinstance(mods, list):
|
|
438
|
+
mods = []
|
|
439
|
+
|
|
440
|
+
entry = next((m for m in mods if canon_module(m.get("name", "")) == name), None)
|
|
441
|
+
created = entry is None
|
|
442
|
+
if created:
|
|
443
|
+
entry = {"seq": (MODULE_ORDER.index(name) + 1) if name in MODULE_ORDER else 99,
|
|
444
|
+
"name": name, "status": "pending", "outputs": []}
|
|
445
|
+
mods.append(entry)
|
|
446
|
+
entry["name"] = name
|
|
447
|
+
entry["status"] = status
|
|
448
|
+
entry["updated_at"] = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
|
|
449
|
+
if entry.get("seq") in (None, 99) and name in MODULE_ORDER:
|
|
450
|
+
entry["seq"] = MODULE_ORDER.index(name) + 1
|
|
451
|
+
if args.outputs is not None:
|
|
452
|
+
new_outs = [x.strip() for x in args.outputs.split(",") if x.strip()]
|
|
453
|
+
entry["outputs"] = (new_outs if args.replace_outputs
|
|
454
|
+
else _merge_unique(entry.get("outputs"), new_outs))
|
|
455
|
+
if args.verify is not None:
|
|
456
|
+
entry["verify"] = args.verify
|
|
457
|
+
if args.note is not None:
|
|
458
|
+
entry["note"] = args.note
|
|
459
|
+
for kv in args.set or []:
|
|
460
|
+
if "=" not in kv:
|
|
461
|
+
print(json.dumps({"ok": False, "reason": "bad_set", "item": kv,
|
|
462
|
+
"hint": "自定义字段用 k=v,值按 JSON 解析,失败则当字符串"},
|
|
463
|
+
ensure_ascii=False))
|
|
464
|
+
return 4
|
|
465
|
+
k, v = kv.split("=", 1)
|
|
466
|
+
raw = v.strip()
|
|
467
|
+
try:
|
|
468
|
+
v = json.loads(raw)
|
|
469
|
+
except Exception:
|
|
470
|
+
# 兼容 Python 风格字面量(True/False/None),否则按字符串
|
|
471
|
+
v = {"true": True, "false": False, "none": None}.get(raw.lower(), raw)
|
|
472
|
+
entry[k.strip()] = v
|
|
473
|
+
|
|
474
|
+
state["modules"] = mods
|
|
475
|
+
pending = state.get("pending")
|
|
476
|
+
if not isinstance(pending, list):
|
|
477
|
+
pending = []
|
|
478
|
+
for item in args.pending_add or []:
|
|
479
|
+
if item not in pending:
|
|
480
|
+
pending.append(item)
|
|
481
|
+
for item in args.pending_remove or []:
|
|
482
|
+
pending = [p for p in pending if p != item]
|
|
483
|
+
state["pending"] = pending
|
|
484
|
+
|
|
485
|
+
# ---- 外部可验证信号:done 必须有据可查(v4.2.0) --------------------
|
|
486
|
+
# 2026-10-22 的教训:asset-design 记 done 时还有 12 张图 pending、
|
|
487
|
+
# exam/project 的 verify.ok 明明是 false,state 却是"已完成"。
|
|
488
|
+
# 所有"完成"都来自自述 → 这里把它变成可机器核对的信号。
|
|
489
|
+
if status == "done":
|
|
490
|
+
problems = []
|
|
491
|
+
if getattr(args, "verify_file", None):
|
|
492
|
+
vp = args.verify_file
|
|
493
|
+
if not os.path.isabs(vp):
|
|
494
|
+
vp = os.path.join(root, vp)
|
|
495
|
+
vobj = jload(vp, None)
|
|
496
|
+
if not isinstance(vobj, dict):
|
|
497
|
+
problems.append("verify 文件缺失或不可解析:%s" % os.path.basename(vp))
|
|
498
|
+
elif vobj.get("ok") is not True:
|
|
499
|
+
c = vobj.get("counts") or {}
|
|
500
|
+
tail = " ".join("%s=%s" % (k, v) for k, v in c.items() if v)
|
|
501
|
+
problems.append("verify.ok!=true%s" % ("(%s)" % tail if tail else ""))
|
|
502
|
+
if getattr(args, "require_files", False):
|
|
503
|
+
for fn in entry.get("outputs") or []:
|
|
504
|
+
if not re.search(r"\.[A-Za-z0-9]{1,6}$", fn):
|
|
505
|
+
continue # 变量名形态(SOKE_CLI/corp_id)跳过
|
|
506
|
+
fp = fn if os.path.isabs(fn) else os.path.join(root, fn)
|
|
507
|
+
if not os.path.isfile(fp) or os.path.getsize(fp) == 0:
|
|
508
|
+
problems.append("产出物缺失或为空:%s" % fn)
|
|
509
|
+
if problems:
|
|
510
|
+
print(json.dumps({"ok": False, "reason": "unverified_done",
|
|
511
|
+
"module": name, "problems": problems,
|
|
512
|
+
"hint": "done 必须可外部验证;补 verify/产出物,或先记 running"},
|
|
513
|
+
ensure_ascii=False, indent=2))
|
|
514
|
+
return 6
|
|
515
|
+
|
|
516
|
+
jdump(path, state)
|
|
517
|
+
|
|
518
|
+
# 收工即重渲台账:人读文件永远派生自 state,不存在"忘了跑 ledger"
|
|
519
|
+
ledger = ""
|
|
520
|
+
try:
|
|
521
|
+
ledger = render_ledger(root, state)
|
|
522
|
+
except SystemExit:
|
|
523
|
+
pass
|
|
524
|
+
append_log(root, "guard",
|
|
525
|
+
f"state module={name} status={status} "
|
|
526
|
+
f"outputs={len(entry.get('outputs') or [])} created={int(created)}", "script")
|
|
527
|
+
print(json.dumps({"ok": True, "module": entry, "created": created,
|
|
528
|
+
"state": path, "ledger": ledger,
|
|
529
|
+
"modules": len(mods)}, ensure_ascii=False, indent=2))
|
|
530
|
+
return 0
|
|
531
|
+
finally:
|
|
532
|
+
if unlock:
|
|
533
|
+
unlock()
|
|
534
|
+
lockfh.close()
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
# ------------------------------------------------------------------ 清理
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def cmd_clean(args) -> int:
|
|
541
|
+
root = os.path.abspath(args.demo_root)
|
|
542
|
+
found = []
|
|
543
|
+
for pat in TEMP_PATTERNS:
|
|
544
|
+
found.extend(sorted(glob.glob(os.path.join(root, pat))))
|
|
545
|
+
found = [p for p in found if os.path.isfile(p)]
|
|
546
|
+
total = sum(os.path.getsize(p) for p in found)
|
|
547
|
+
if args.apply:
|
|
548
|
+
for p in found:
|
|
549
|
+
try:
|
|
550
|
+
os.remove(p)
|
|
551
|
+
except OSError as exc:
|
|
552
|
+
print(json.dumps({"ok": False, "error": f"{p}: {exc}"}, ensure_ascii=False))
|
|
553
|
+
return 1
|
|
554
|
+
if found:
|
|
555
|
+
append_log(root, "guard", f"clean removed={len(found)} bytes={total}", "script")
|
|
556
|
+
print(json.dumps({"ok": True, "applied": bool(args.apply),
|
|
557
|
+
"count": len(found), "bytes": total,
|
|
558
|
+
"files": [os.path.basename(p) for p in found]},
|
|
559
|
+
ensure_ascii=False, indent=2))
|
|
560
|
+
return 0
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
# ------------------------------------------------------------------ 自检
|
|
564
|
+
|
|
565
|
+
def self_test() -> int:
|
|
566
|
+
import tempfile
|
|
567
|
+
fails = []
|
|
568
|
+
|
|
569
|
+
def ck(cond, label):
|
|
570
|
+
if not cond:
|
|
571
|
+
fails.append(label)
|
|
572
|
+
|
|
573
|
+
with tempfile.TemporaryDirectory() as td:
|
|
574
|
+
root = os.path.join(td, "demo")
|
|
575
|
+
os.makedirs(root)
|
|
576
|
+
|
|
577
|
+
# 1) acquire 成功
|
|
578
|
+
class A:
|
|
579
|
+
demo_root = root
|
|
580
|
+
module = "course-setup"
|
|
581
|
+
force = False
|
|
582
|
+
ck(cmd_acquire(A) == 0, "acquire 应成功")
|
|
583
|
+
ck(os.path.isfile(lock_path(root)), "锁文件应存在")
|
|
584
|
+
|
|
585
|
+
# 2) 同进程重复 acquire 允许(pid 相同)
|
|
586
|
+
ck(cmd_acquire(A) == 0, "同 pid 重复 acquire 应允许")
|
|
587
|
+
|
|
588
|
+
# 3) 伪造活进程 → 拒绝
|
|
589
|
+
rec = read_lock(root)
|
|
590
|
+
rec["pid"] = 1 # init 恒活
|
|
591
|
+
jdump(lock_path(root), rec)
|
|
592
|
+
ck(cmd_acquire(A) == 3, "活进程持锁应返回 3")
|
|
593
|
+
|
|
594
|
+
# 4) 伪造死进程 → 接管
|
|
595
|
+
rec["pid"] = 999999
|
|
596
|
+
jdump(lock_path(root), rec)
|
|
597
|
+
ck(cmd_acquire(A) == 0, "死进程残留锁应可接管")
|
|
598
|
+
|
|
599
|
+
# 5) 日志单行 + 时间格式 + src
|
|
600
|
+
line = append_log(root, "course-build", "create ok title=X\n第二行 uuid=U1", "script")
|
|
601
|
+
ck("\n" not in line, "日志必须单行")
|
|
602
|
+
ck(re.match(r"^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] \[course-build\] ", line) is not None,
|
|
603
|
+
"日志格式/时间戳不合契约")
|
|
604
|
+
ck("src=script" in line, "日志应带 src")
|
|
605
|
+
|
|
606
|
+
# 6) 非法模块名拒绝
|
|
607
|
+
try:
|
|
608
|
+
append_log(root, "Course_Setup", "x")
|
|
609
|
+
ck(False, "非法模块名应拒绝")
|
|
610
|
+
except SystemExit:
|
|
611
|
+
pass
|
|
612
|
+
|
|
613
|
+
# 7) status 抓出「日志有 RUN SUMMARY 但 state=pending」
|
|
614
|
+
jdump(os.path.join(root, STATE), {
|
|
615
|
+
"blueprint_id": "t", "modules": [
|
|
616
|
+
{"name": "plan-parse", "status": "done", "outputs": []},
|
|
617
|
+
{"name": "exam-setup", "status": "pending", "outputs": []}]})
|
|
618
|
+
append_log(root, "exam-setup", "RUN SUMMARY created=5 → OK", "script")
|
|
619
|
+
|
|
620
|
+
class S:
|
|
621
|
+
demo_root = root
|
|
622
|
+
report_only = True
|
|
623
|
+
import io
|
|
624
|
+
from contextlib import redirect_stdout
|
|
625
|
+
buf = io.StringIO()
|
|
626
|
+
with redirect_stdout(buf):
|
|
627
|
+
cmd_status(S)
|
|
628
|
+
out = json.loads(buf.getvalue())
|
|
629
|
+
ck([s["module"] for s in out["suspects"]] == ["exam-setup"], "应捉到 exam-setup 状态失真")
|
|
630
|
+
for field, explanation, expected in (
|
|
631
|
+
("note", "缺少原文题目,待明确", False),
|
|
632
|
+
("verify", "pending:内容未发布", False),
|
|
633
|
+
("note", " ", True),
|
|
634
|
+
("verify", "PASS", True)):
|
|
635
|
+
state = jload(os.path.join(root, STATE))
|
|
636
|
+
state["modules"][1].pop("note", None)
|
|
637
|
+
state["modules"][1].pop("verify", None)
|
|
638
|
+
state["modules"][1][field] = explanation
|
|
639
|
+
jdump(os.path.join(root, STATE), state)
|
|
640
|
+
buf = io.StringIO()
|
|
641
|
+
with redirect_stdout(buf):
|
|
642
|
+
cmd_status(S)
|
|
643
|
+
ck(bool(json.loads(buf.getvalue())["suspects"]) == expected,
|
|
644
|
+
"pending 说明护栏:" + field + "=" + explanation)
|
|
645
|
+
|
|
646
|
+
# 8) ledger 从 state 渲染且标 done
|
|
647
|
+
class L:
|
|
648
|
+
demo_root = root
|
|
649
|
+
with redirect_stdout(io.StringIO()):
|
|
650
|
+
cmd_ledger(L)
|
|
651
|
+
text = open(os.path.join(root, LEDGER), encoding="utf-8").read()
|
|
652
|
+
ck("plan-parse" in text and "✅ done" in text, "台账应含完成行")
|
|
653
|
+
|
|
654
|
+
# 9) clean 默认 dry-run 不删
|
|
655
|
+
tmp = os.path.join(root, ".soke-portal-123.json")
|
|
656
|
+
open(tmp, "w").write("{}")
|
|
657
|
+
|
|
658
|
+
class C:
|
|
659
|
+
demo_root = root
|
|
660
|
+
apply = False
|
|
661
|
+
with redirect_stdout(io.StringIO()):
|
|
662
|
+
cmd_clean(C)
|
|
663
|
+
ck(os.path.isfile(tmp), "dry-run 不应删除")
|
|
664
|
+
|
|
665
|
+
class C2(C):
|
|
666
|
+
apply = True
|
|
667
|
+
with redirect_stdout(io.StringIO()):
|
|
668
|
+
cmd_clean(C2)
|
|
669
|
+
ck(not os.path.isfile(tmp), "apply 应删除临时文件")
|
|
670
|
+
|
|
671
|
+
# 10) 模块名别名归一(category-setup → taxonomy-setup,假阳性防护)
|
|
672
|
+
ck(canon_module("category-setup") == "taxonomy-setup", "别名应归一到 taxonomy-setup")
|
|
673
|
+
ck(canon_module("Exam_Setup") == "exam-setup", "下划线+大写输入应归一到 exam-setup")
|
|
674
|
+
|
|
675
|
+
# 11) 日志 uuid 可信来源必须含 state.json(否则 state.portal_uuid 被判幻影)
|
|
676
|
+
st = {"portal_uuid": "0C486AB7-EEFD-4447-873A-285D03E03C23"}
|
|
677
|
+
jdump(os.path.join(root, STATE), st)
|
|
678
|
+
k = log_uuids(root)
|
|
679
|
+
ck("0C486AB7-EEFD-4447-873A-285D03E03C23" in k, "state.json 里的 portal_uuid 应算可信")
|
|
680
|
+
|
|
681
|
+
# 12) state 原子合并写(v4.1.0:唯一写入口)
|
|
682
|
+
class S:
|
|
683
|
+
demo_root = root
|
|
684
|
+
module = "course-setup"
|
|
685
|
+
status = "done"
|
|
686
|
+
outputs = "course-ids.json,course-verify.json"
|
|
687
|
+
replace_outputs = False
|
|
688
|
+
verify = "六项回读 PASS"
|
|
689
|
+
note = "演示封面 2 门待补"
|
|
690
|
+
blueprint_id = "t"
|
|
691
|
+
pending_add = ["portal-setup: Banner 待补挂"]
|
|
692
|
+
pending_remove = None
|
|
693
|
+
set = ["assigned=10", "published=9", "assigned_eq=False"]
|
|
694
|
+
|
|
695
|
+
with redirect_stdout(io.StringIO()):
|
|
696
|
+
ck(cmd_state(S) == 0, "state 写入应成功")
|
|
697
|
+
doc = jload(os.path.join(root, STATE), {})
|
|
698
|
+
e = next(m for m in doc["modules"] if m["name"] == "course-setup")
|
|
699
|
+
ck(e["seq"] == 6, "seq 由调度顺序推导(course-setup=6)")
|
|
700
|
+
ck(e["status"] == "done" and e["verify"] == "六项回读 PASS", "status/verify 应落库")
|
|
701
|
+
ck(e["outputs"] == ["course-ids.json", "course-verify.json"], "outputs 首次写入")
|
|
702
|
+
ck(e["assigned"] == 10 and e["published"] == 9 and e["assigned_eq"] is False,
|
|
703
|
+
"--set 值按 JSON 解析(int/bool)")
|
|
704
|
+
ck(doc["pending"] == ["portal-setup: Banner 待补挂"], "pending 追加")
|
|
705
|
+
ck(doc["demo_root"] == root and doc["blueprint_id"] == "t", "demo_root/blueprint_id 落库")
|
|
706
|
+
ck("T" in (e["updated_at"] or ""), "updated_at 为 ISO8601 带时区")
|
|
707
|
+
|
|
708
|
+
# 13) 二次写入:outputs 追加去重、未提供字段保持、pending 可移除
|
|
709
|
+
class S2(S):
|
|
710
|
+
outputs = "course-verify.json,cover-bindings.json"
|
|
711
|
+
note = None
|
|
712
|
+
verify = None
|
|
713
|
+
pending_add = None
|
|
714
|
+
pending_remove = ["portal-setup: Banner 待补挂"]
|
|
715
|
+
set = None
|
|
716
|
+
|
|
717
|
+
with redirect_stdout(io.StringIO()):
|
|
718
|
+
ck(cmd_state(S2) == 0, "二次 state 写入应成功")
|
|
719
|
+
e2 = next(m for m in jload(os.path.join(root, STATE))["modules"]
|
|
720
|
+
if m["name"] == "course-setup")
|
|
721
|
+
ck(e2["outputs"] == ["course-ids.json", "course-verify.json", "cover-bindings.json"],
|
|
722
|
+
"outputs 追加去重(不覆盖历史产物)")
|
|
723
|
+
ck(e2.get("note") == "演示封面 2 门待补", "未提供的字段保持原值(只增不删)")
|
|
724
|
+
ck(e2["assigned"] == 10, "自定义字段不被后续写入抹掉")
|
|
725
|
+
ck(jload(os.path.join(root, STATE))["pending"] == [], "pending 可移除")
|
|
726
|
+
|
|
727
|
+
# 14) 非法输入拒绝
|
|
728
|
+
class BadMod(S):
|
|
729
|
+
module = "Course Setup"
|
|
730
|
+
with redirect_stdout(io.StringIO()):
|
|
731
|
+
ck(cmd_state(BadMod) == 4, "非法模块名应拒写")
|
|
732
|
+
class BadStatus(S):
|
|
733
|
+
status = "finished"
|
|
734
|
+
with redirect_stdout(io.StringIO()):
|
|
735
|
+
ck(cmd_state(BadStatus) == 4, "非法 status 应拒写")
|
|
736
|
+
|
|
737
|
+
# 15) 别名归一 + 台账自动重渲
|
|
738
|
+
class Alias(S):
|
|
739
|
+
module = "category-setup"
|
|
740
|
+
status = "done"
|
|
741
|
+
outputs = None
|
|
742
|
+
pending_add = None
|
|
743
|
+
set = None
|
|
744
|
+
with redirect_stdout(io.StringIO()):
|
|
745
|
+
ck(cmd_state(Alias) == 0, "别名应可写入")
|
|
746
|
+
names = [m["name"] for m in jload(os.path.join(root, STATE))["modules"]]
|
|
747
|
+
ck("taxonomy-setup" in names and "category-setup" not in names, "模块名应归一到 taxonomy-setup")
|
|
748
|
+
text = open(os.path.join(root, LEDGER), encoding="utf-8").read()
|
|
749
|
+
ck("course-setup" in text and "✅ done" in text, "state 写入后台账应自动重渲")
|
|
750
|
+
ck("Banner 待补挂" not in text, "已移除的待处理不应残留台账")
|
|
751
|
+
|
|
752
|
+
if fails:
|
|
753
|
+
print(json.dumps({"ok": False, "fails": fails}, ensure_ascii=False, indent=2))
|
|
754
|
+
return 1
|
|
755
|
+
print(json.dumps({"ok": True, "assertions": 38}, ensure_ascii=False))
|
|
756
|
+
return 0
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
# ------------------------------------------------------------------ main
|
|
760
|
+
|
|
761
|
+
# ------------------------------------------------------------------ 批量日志 / 机械摘要 / 日志审计
|
|
762
|
+
|
|
763
|
+
UUID_FULL = re.compile(r"\b[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}\b")
|
|
764
|
+
# 8 位短 id:必须至少含一个 A-F 字母,否则纯数字日期串(20261021)会误判成 uuid
|
|
765
|
+
UUID_SHORT = re.compile(r"\b(?=[0-9A-F]{0,7}[A-F])[0-9A-F]{8}\b")
|
|
766
|
+
|
|
767
|
+
# 统计摘要时认作「对象」的 ID 字段
|
|
768
|
+
ID_KEYS = ("uuid", "course_id", "exam_id", "map_id", "paper_id", "project_id",
|
|
769
|
+
"pool_id", "photo_uuid", "category_id")
|
|
770
|
+
NAME_KEYS = ("title", "name", "label")
|
|
771
|
+
# 摘要产物白名单(快照/布局文件含大量组件 id,会稀释统计,排除)
|
|
772
|
+
ARTIFACT_GLOBS = ("*-ids.json", "*-bindings.json", "taxonomy-map.json", "*-verify.json",
|
|
773
|
+
"photo-map.json", "asset-manifest.json", "category-tree.json", "dup-scan.json")
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def append_log_file(demo_root: str, module: str, path: str, src: str = "agent",
|
|
777
|
+
interval: float = 0.3) -> int:
|
|
778
|
+
"""按文件逐行实时写入日志,绕开 heredoc 内联 f-string 的花括号转义坑。
|
|
779
|
+
|
|
780
|
+
文件每行 = 一条日志正文;空行与 `#` 注释行跳过;单行超长由 append_log 截断。
|
|
781
|
+
`interval` 为行间间隔秒数:⛔ 不能为 0——同一秒挤 ≥5 行会被 `audit-log` 判成
|
|
782
|
+
事后回填(本轮真实踩过:8 行同秒 → 自审即告警)。返回写入条数。
|
|
783
|
+
"""
|
|
784
|
+
import time as _time
|
|
785
|
+
written = 0
|
|
786
|
+
with open(path, encoding="utf-8") as fh:
|
|
787
|
+
for raw in fh:
|
|
788
|
+
text = raw.strip()
|
|
789
|
+
if not text or text.startswith("#"):
|
|
790
|
+
continue
|
|
791
|
+
if written and interval > 0:
|
|
792
|
+
_time.sleep(interval)
|
|
793
|
+
append_log(demo_root, module, text, src)
|
|
794
|
+
written += 1
|
|
795
|
+
return written
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def _walk_objects(node):
|
|
799
|
+
"""递归产出「像业务对象」的 dict:有名字字段 + 有 ID 字段。"""
|
|
800
|
+
if isinstance(node, dict):
|
|
801
|
+
has_name = any(k in node for k in NAME_KEYS)
|
|
802
|
+
has_id = any(k in node for k in ID_KEYS)
|
|
803
|
+
if has_name and has_id:
|
|
804
|
+
yield node
|
|
805
|
+
for v in node.values():
|
|
806
|
+
yield from _walk_objects(v)
|
|
807
|
+
elif isinstance(node, list):
|
|
808
|
+
for v in node:
|
|
809
|
+
yield from _walk_objects(v)
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def artifact_stats(demo_root: str) -> dict:
|
|
813
|
+
"""从产物 JSON 机械统计 created/published/assigned,杜绝手写数字。"""
|
|
814
|
+
import glob as _glob
|
|
815
|
+
files = []
|
|
816
|
+
for pat in ARTIFACT_GLOBS:
|
|
817
|
+
files.extend(_glob.glob(os.path.join(demo_root, pat)))
|
|
818
|
+
files = sorted(set(files))
|
|
819
|
+
|
|
820
|
+
seen, per_file = set(), {}
|
|
821
|
+
for path in files:
|
|
822
|
+
try:
|
|
823
|
+
data = json.load(open(path, encoding="utf-8"))
|
|
824
|
+
except Exception as exc: # 坏文件不影响其它产物
|
|
825
|
+
per_file[os.path.basename(path)] = {"error": str(exc)[:80]}
|
|
826
|
+
continue
|
|
827
|
+
total = pub = asg = 0
|
|
828
|
+
for obj in _walk_objects(data):
|
|
829
|
+
key = str(obj.get("uuid") or obj.get("course_id") or obj.get("exam_id")
|
|
830
|
+
or obj.get("map_id") or obj.get("project_id")
|
|
831
|
+
or obj.get("paper_id") or obj.get("pool_id") or "")
|
|
832
|
+
if not key or key in seen:
|
|
833
|
+
continue
|
|
834
|
+
seen.add(key)
|
|
835
|
+
total += 1
|
|
836
|
+
if obj.get("published") is True or str(obj.get("status")) in ("published", "1", "done", "ok"):
|
|
837
|
+
pub += 1
|
|
838
|
+
if obj.get("assigned") is True or (isinstance(obj.get("assign_count"), int)
|
|
839
|
+
and obj["assign_count"] >= 1):
|
|
840
|
+
asg += 1
|
|
841
|
+
per_file[os.path.basename(path)] = {"objects": total, "published": pub, "assigned": asg}
|
|
842
|
+
return {"files": per_file, "objects": len(seen),
|
|
843
|
+
"published": sum(v.get("published", 0) for v in per_file.values()),
|
|
844
|
+
"assigned": sum(v.get("assigned", 0) for v in per_file.values())}
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
def cmd_summary(args) -> int:
|
|
848
|
+
st = artifact_stats(args.demo_root)
|
|
849
|
+
total = st["objects"]
|
|
850
|
+
text = (f"RUN SUMMARY(机械) objects={total} published={st['published']}/{total} "
|
|
851
|
+
f"assigned={st['assigned']}/{total} artifacts={len(st['files'])}")
|
|
852
|
+
append_log(args.demo_root, args.module, text, "script")
|
|
853
|
+
print(json.dumps({"summary": text, "detail": st}, ensure_ascii=False, indent=2))
|
|
854
|
+
return 0 if total else 2
|
|
855
|
+
|
|
856
|
+
|
|
857
|
+
def log_uuids(demo_root: str, include_history: bool = False) -> set:
|
|
858
|
+
"""产物里真实出现过的 uuid(全写与 8 位前缀),用于核对日志有没有写错对象。
|
|
859
|
+
|
|
860
|
+
⚠️ 2026-10-21 修正:原来只扫 ARTIFACT_GLOBS(ids/bindings/verify 等),**漏了 state.json**
|
|
861
|
+
—— 而 `state.portal_uuid` 往往只在 state.json 里,于是正确门户 uuid 被审计判成"幻影"。
|
|
862
|
+
现在把 state.json 也纳入可信来源。
|
|
863
|
+
|
|
864
|
+
`include_history=True` 时追加「历史/已删对象」来源(cleanup-backup / cleanup-report /
|
|
865
|
+
dup-scan-before):日志是历史事实,删掉对象后旧日志行不该变成"幻影 uuid";
|
|
866
|
+
但**手册必须用严格集**(include_history=False)——手册写已删对象就是过期内容。
|
|
867
|
+
"""
|
|
868
|
+
import glob as _glob
|
|
869
|
+
known = set()
|
|
870
|
+
files = [os.path.join(demo_root, STATE)]
|
|
871
|
+
for pat in ARTIFACT_GLOBS:
|
|
872
|
+
files.extend(_glob.glob(os.path.join(demo_root, pat)))
|
|
873
|
+
if include_history:
|
|
874
|
+
for name in ("cleanup-backup.json", "cleanup-report.json", "dup-scan-before.json"):
|
|
875
|
+
files.append(os.path.join(demo_root, name))
|
|
876
|
+
for path in set(files):
|
|
877
|
+
try:
|
|
878
|
+
raw = open(path, encoding="utf-8").read()
|
|
879
|
+
except Exception:
|
|
880
|
+
continue
|
|
881
|
+
for u in UUID_FULL.findall(raw):
|
|
882
|
+
known.add(u.upper())
|
|
883
|
+
known.add(u.upper().split("-")[0])
|
|
884
|
+
return known
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
def cmd_audit_log(args) -> int:
|
|
888
|
+
"""审计 run.log:① 同秒聚集(回填特征)② 模块缺 SUMMARY ③ uuid 在产物里查不到(虚构事实)。
|
|
889
|
+
|
|
890
|
+
`--since "YYYY-MM-DD HH:MM:SS"` 只审该时刻之后的行:历史回填**不改写**(改历史=造假),
|
|
891
|
+
但闸门只对「本次施工段」负责,否则旧日志会让交付永远卡住。
|
|
892
|
+
"""
|
|
893
|
+
path = os.path.join(args.demo_root, RUN_LOG)
|
|
894
|
+
if not os.path.isfile(path):
|
|
895
|
+
print(json.dumps({"ok": False, "error": "run.log 不存在"}, ensure_ascii=False))
|
|
896
|
+
return 2
|
|
897
|
+
|
|
898
|
+
rows, modules, seconds = [], set(), []
|
|
899
|
+
summary_ts = {} # 全量:模块 → 最近一次 RUN SUMMARY 时间
|
|
900
|
+
for line in open(path, encoding="utf-8"):
|
|
901
|
+
m = re.match(r"^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] \[([a-z-]+)\] (.*)$", line.rstrip("\n"))
|
|
902
|
+
if not m:
|
|
903
|
+
continue
|
|
904
|
+
ts, mod, msg = m.groups()
|
|
905
|
+
mod = canon_module(mod)
|
|
906
|
+
if "RUN SUMMARY" in msg:
|
|
907
|
+
summary_ts[mod] = ts
|
|
908
|
+
if args.since and ts < args.since:
|
|
909
|
+
continue
|
|
910
|
+
seconds.append(ts)
|
|
911
|
+
modules.add(mod)
|
|
912
|
+
rows.append((ts, mod, msg))
|
|
913
|
+
|
|
914
|
+
# ① 同秒聚集
|
|
915
|
+
bursts = []
|
|
916
|
+
i = 0
|
|
917
|
+
while i < len(seconds):
|
|
918
|
+
j = i
|
|
919
|
+
while j + 1 < len(seconds) and seconds[j + 1] == seconds[i]:
|
|
920
|
+
j += 1
|
|
921
|
+
n = j - i + 1
|
|
922
|
+
if n >= args.gap:
|
|
923
|
+
bursts.append({"second": seconds[i], "lines": n})
|
|
924
|
+
i = j + 1
|
|
925
|
+
|
|
926
|
+
# ② 模块缺 RUN SUMMARY
|
|
927
|
+
# 只对「窗口内出现过的模块」追收尾行;SUMMARY 落在窗口外(模块更早收过尾)不算缺失
|
|
928
|
+
no_summary = sorted({mod for mod in modules if mod not in summary_ts})
|
|
929
|
+
|
|
930
|
+
# ③ uuid 不在产物里(日志容忍已删对象,见 log_uuids 的 include_history)
|
|
931
|
+
known = log_uuids(args.demo_root, include_history=True)
|
|
932
|
+
phantom = {}
|
|
933
|
+
for ts, mod, msg in rows:
|
|
934
|
+
for u in UUID_FULL.findall(msg) + UUID_SHORT.findall(msg):
|
|
935
|
+
u = u.upper()
|
|
936
|
+
short = u.split("-")[0]
|
|
937
|
+
if short in known or u in known:
|
|
938
|
+
continue
|
|
939
|
+
phantom.setdefault(u, {"first_seen": ts, "module": mod})
|
|
940
|
+
break
|
|
941
|
+
|
|
942
|
+
ok = not bursts and not no_summary and not phantom
|
|
943
|
+
report = {"ok": ok, "lines": len(rows), "modules": sorted(modules),
|
|
944
|
+
"same_second_bursts": bursts,
|
|
945
|
+
"modules_without_summary": no_summary,
|
|
946
|
+
"phantom_uuids": phantom,
|
|
947
|
+
"known_uuid_count": len(known)}
|
|
948
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
949
|
+
return 0 if ok else 2
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
# ------------------------------------------------------------------ 交付一致性 / CLI 环境
|
|
953
|
+
|
|
954
|
+
def _run_cli(cli: str, args: list) -> dict:
|
|
955
|
+
import subprocess
|
|
956
|
+
try:
|
|
957
|
+
p = subprocess.run([cli] + list(args), capture_output=True, text=True, timeout=90)
|
|
958
|
+
except Exception as exc: # noqa: BLE001
|
|
959
|
+
return {"_error": str(exc)}
|
|
960
|
+
raw = (p.stdout or "").strip()
|
|
961
|
+
idx = raw.find("{")
|
|
962
|
+
if idx >= 0:
|
|
963
|
+
try:
|
|
964
|
+
obj, _ = json.JSONDecoder().raw_decode(raw[idx:])
|
|
965
|
+
if isinstance(obj, dict):
|
|
966
|
+
return obj
|
|
967
|
+
except ValueError:
|
|
968
|
+
pass
|
|
969
|
+
return {"_raw": raw[:500], "_stderr": (p.stderr or "").strip()[:300]}
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def cmd_deliver_check(args) -> int:
|
|
973
|
+
"""交付前一致性断言(只读):state ↔ 平台 ↔ 手册 ↔ 日志 四方对齐。
|
|
974
|
+
|
|
975
|
+
存在理由(2026-10-21 loong-20261021):手册把「长龙学堂」写成 `80C1B114`,
|
|
976
|
+
而实际被 home-apply 装修的是 `0C486AB7` —— 演示当天会进到只装修了一半的门户。
|
|
977
|
+
同类错法还有:改 bindings 后不回读(考试分类日志写 `02A1030C`,平台实际周考/月考)、
|
|
978
|
+
培训班 ids 键名不匹配导致整组验证被跳过(假的"通过")。
|
|
979
|
+
"""
|
|
980
|
+
root = args.demo_root
|
|
981
|
+
fails, warn, info = [], [], {}
|
|
982
|
+
|
|
983
|
+
state_path = os.path.join(root, STATE)
|
|
984
|
+
if not os.path.isfile(state_path):
|
|
985
|
+
print(json.dumps({"ok": False, "error": "state.json 不存在"}, ensure_ascii=False))
|
|
986
|
+
return 2
|
|
987
|
+
state = json.load(open(state_path, encoding="utf-8"))
|
|
988
|
+
portal_uuid = (state.get("portal_uuid") or "").strip()
|
|
989
|
+
info["portal_uuid"] = portal_uuid
|
|
990
|
+
if not portal_uuid:
|
|
991
|
+
fails.append("state.portal_uuid 为空")
|
|
992
|
+
|
|
993
|
+
# ① 门户:本轮 UUID 存在性 + 已发布 + 首页模块数(不要求同名唯一)
|
|
994
|
+
if portal_uuid and not args.skip_remote:
|
|
995
|
+
lst = _run_cli(args.cli, ["portal", "+list", "--format", "json"])
|
|
996
|
+
portals = ((lst.get("data") or {}) if isinstance(lst.get("data"), dict) else {}).get("list") or []
|
|
997
|
+
if not portals:
|
|
998
|
+
warn.append("portal +list 无数据,跳过门户远端断言")
|
|
999
|
+
else:
|
|
1000
|
+
hit = [p for p in portals if str(p.get("uuid", "")).upper() == portal_uuid.upper()]
|
|
1001
|
+
if not hit:
|
|
1002
|
+
fails.append(f"state.portal_uuid {portal_uuid[:8]} 不在平台门户列表(可能已被删/建错)")
|
|
1003
|
+
title = state.get("portal_title")
|
|
1004
|
+
else:
|
|
1005
|
+
title = state.get("portal_title") or hit[0].get("title")
|
|
1006
|
+
if hit[0].get("status") != 1:
|
|
1007
|
+
warn.append(f"门户 status={hit[0].get('status')}(非 1=已发布)")
|
|
1008
|
+
info["portal_title"] = title
|
|
1009
|
+
if title:
|
|
1010
|
+
same_title = [p for p in portals if p.get("title") == title]
|
|
1011
|
+
info["portal_same_title"] = len(same_title)
|
|
1012
|
+
# 同名历史对象允许共存;交付只校验本轮 UUID,不以名称唯一性阻断。
|
|
1013
|
+
if len(same_title) > 1:
|
|
1014
|
+
info["portal_same_title_policy"] = "allowed; current-run UUID is authoritative"
|
|
1015
|
+
|
|
1016
|
+
home = _run_cli(args.cli, ["portal", "+home-get", "--id", portal_uuid, "--format", "json"])
|
|
1017
|
+
data = home.get("data") or {}
|
|
1018
|
+
comps = (data.get("list") or {}).get("components") if isinstance(data.get("list"), dict) else None
|
|
1019
|
+
comps = comps or data.get("components") or []
|
|
1020
|
+
if comps:
|
|
1021
|
+
# ContainerView 是结构容器位,不算"模块"(portal_home_layout 从不把它计入清单)
|
|
1022
|
+
on = [c for c in comps
|
|
1023
|
+
if str(c.get("is_show")).lower() == "true" and c.get("type") != "ContainerView"]
|
|
1024
|
+
info["home_visible"] = len(on)
|
|
1025
|
+
expect = state.get("portal_home_modules") or []
|
|
1026
|
+
# 该字段历史上被写过两种形态:清单数组 / 数量整数,都兼容
|
|
1027
|
+
expect_n = expect if isinstance(expect, int) else len(expect)
|
|
1028
|
+
info["home_expected"] = expect_n
|
|
1029
|
+
if expect_n and len(on) != expect_n:
|
|
1030
|
+
fails.append(f"首页可见模块 {len(on)} ≠ state 记录 {expect_n}")
|
|
1031
|
+
elif portal_uuid:
|
|
1032
|
+
warn.append("home-get 未取到 components,跳过首页断言")
|
|
1033
|
+
|
|
1034
|
+
# ② 手册:出现的 uuid 必须都是真实产物
|
|
1035
|
+
manual = os.path.join(root, "DEMO演示手册.md")
|
|
1036
|
+
if os.path.isfile(manual):
|
|
1037
|
+
known = log_uuids(root)
|
|
1038
|
+
raw = open(manual, encoding="utf-8").read()
|
|
1039
|
+
bad = sorted({u.upper() for u in UUID_FULL.findall(raw)
|
|
1040
|
+
if u.upper() not in known and u.upper().split("-")[0] not in known})
|
|
1041
|
+
info["manual_uuids"] = len(UUID_FULL.findall(raw))
|
|
1042
|
+
if bad:
|
|
1043
|
+
fails.append("手册引用了非产物 uuid:" + ", ".join(b[:8] for b in bad))
|
|
1044
|
+
|
|
1045
|
+
# ③ ids 文件:published / assigned 是否与记录自洽(有字段才算)
|
|
1046
|
+
for path in sorted(glob.glob(os.path.join(root, "*-ids.json"))):
|
|
1047
|
+
try:
|
|
1048
|
+
d = json.load(open(path, encoding="utf-8"))
|
|
1049
|
+
except Exception: # noqa: BLE001
|
|
1050
|
+
continue
|
|
1051
|
+
rows = []
|
|
1052
|
+
for key in ("courses", "exams", "maps", "classes", "projects"):
|
|
1053
|
+
rows.extend(d.get(key) or [])
|
|
1054
|
+
rows = [r for r in rows if isinstance(r, dict)]
|
|
1055
|
+
if not rows:
|
|
1056
|
+
continue
|
|
1057
|
+
pub = [r for r in rows if r.get("published") is False or r.get("status") == 0]
|
|
1058
|
+
asg = [r for r in rows if r.get("assigned") is False or r.get("assign_count") == 0]
|
|
1059
|
+
if pub:
|
|
1060
|
+
fails.append(f"{os.path.basename(path)}:{len(pub)} 个未发布")
|
|
1061
|
+
if asg:
|
|
1062
|
+
warn.append(f"{os.path.basename(path)}:{len(asg)} 个未指派")
|
|
1063
|
+
|
|
1064
|
+
# ④ 日志:同秒回填 / 缺 SUMMARY / 幻影 uuid
|
|
1065
|
+
audit = None
|
|
1066
|
+
try:
|
|
1067
|
+
argv = argparse.Namespace(demo_root=root, gap=args.gap, since=args.since)
|
|
1068
|
+
import io
|
|
1069
|
+
from contextlib import redirect_stdout
|
|
1070
|
+
buf = io.StringIO()
|
|
1071
|
+
with redirect_stdout(buf):
|
|
1072
|
+
cmd_audit_log(argv)
|
|
1073
|
+
audit = json.loads(buf.getvalue() or "{}")
|
|
1074
|
+
info["log_lines"] = audit.get("lines")
|
|
1075
|
+
if not audit.get("ok"):
|
|
1076
|
+
if audit.get("same_second_bursts"):
|
|
1077
|
+
warn.append(f"日志同秒聚集 {len(audit['same_second_bursts'])} 处(历史段不改写,仅记台账)")
|
|
1078
|
+
if audit.get("modules_without_summary"):
|
|
1079
|
+
fails.append("模块缺 RUN SUMMARY:" + ", ".join(audit["modules_without_summary"]))
|
|
1080
|
+
if audit.get("phantom_uuids"):
|
|
1081
|
+
fails.append("日志出现非产物 uuid:" + ", ".join(
|
|
1082
|
+
list(audit["phantom_uuids"])[:5]))
|
|
1083
|
+
except Exception as exc: # noqa: BLE001
|
|
1084
|
+
warn.append(f"日志审计未执行:{exc}")
|
|
1085
|
+
|
|
1086
|
+
ok = not fails
|
|
1087
|
+
report = {"ok": ok, "fails": fails, "warnings": warn, "info": info,
|
|
1088
|
+
"audit": audit, "checked_at": now_ts()}
|
|
1089
|
+
out = args.out or os.path.join(root, "deliver-check.json")
|
|
1090
|
+
jdump(out, report)
|
|
1091
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
1092
|
+
return 0 if ok else 2
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
CLI_CANDIDATES = [
|
|
1096
|
+
os.environ.get("SOKE_CLI", ""),
|
|
1097
|
+
os.path.expanduser("~/.npm-global/bin/soke-cli"),
|
|
1098
|
+
"/usr/local/bin/soke-cli",
|
|
1099
|
+
"/opt/homebrew/bin/soke-cli",
|
|
1100
|
+
os.path.expanduser("~/.workbuddy/binaries/node/cli-connector-packages/bin/soke-cli"),
|
|
1101
|
+
]
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
def cli_probe(path: str) -> dict:
|
|
1105
|
+
import subprocess
|
|
1106
|
+
if not path or not os.path.exists(path):
|
|
1107
|
+
return {"path": path, "exists": False}
|
|
1108
|
+
if not os.access(path, os.X_OK):
|
|
1109
|
+
return {"path": path, "exists": True, "executable": False}
|
|
1110
|
+
try:
|
|
1111
|
+
p = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=45)
|
|
1112
|
+
out = ((p.stdout or "") + (p.stderr or ""))
|
|
1113
|
+
ver = ""
|
|
1114
|
+
for ln in out.splitlines():
|
|
1115
|
+
m = re.search(r"version\s+([0-9][\w.\-]*)", ln)
|
|
1116
|
+
if m:
|
|
1117
|
+
ver = m.group(1)
|
|
1118
|
+
break
|
|
1119
|
+
return {"path": path, "exists": True, "executable": True,
|
|
1120
|
+
"version": ver or out.strip().splitlines()[-1:][0] if out.strip() else "",
|
|
1121
|
+
"rc": p.returncode}
|
|
1122
|
+
except Exception as exc: # noqa: BLE001
|
|
1123
|
+
return {"path": path, "exists": True, "executable": True, "error": str(exc)}
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
def cmd_cli_check(args) -> int:
|
|
1127
|
+
"""体检本机 soke-cli:自更新中断 / 符号链接丢失 / 包不完整 三类故障给恢复步骤。
|
|
1128
|
+
|
|
1129
|
+
存在理由:2026-10-21 10:37 自动更新把 `~/.npm-global/bin/soke-cli` 换成临时名
|
|
1130
|
+
`.soke-cli-XXXX` 后中断,包目录被重建但 `bin/` 为空;沙箱内的 Python subprocess
|
|
1131
|
+
又看不到该路径 → 直接报 FileNotFoundError,被误判成"CLI 被卸载"。
|
|
1132
|
+
"""
|
|
1133
|
+
probes = [cli_probe(p) for p in CLI_CANDIDATES if p]
|
|
1134
|
+
good = [p for p in probes if p.get("executable") and p.get("rc") == 0]
|
|
1135
|
+
|
|
1136
|
+
bin_dir = os.path.expanduser("~/.npm-global/bin")
|
|
1137
|
+
leftovers = glob.glob(os.path.join(bin_dir, ".soke-cli-*"))
|
|
1138
|
+
pkg = os.path.expanduser("~/.npm-global/lib/node_modules/@sokeai/cli")
|
|
1139
|
+
pkg_bin = os.path.join(pkg, "bin")
|
|
1140
|
+
fails, warns = [], []
|
|
1141
|
+
if not good:
|
|
1142
|
+
fails.append("无可用 soke-cli 路径(全部缺失或不可执行)")
|
|
1143
|
+
if leftovers:
|
|
1144
|
+
msg = f"bin 目录残留临时链接 {len(leftovers)} 个(自更新中断特征)"
|
|
1145
|
+
(warns if good else fails).append(msg)
|
|
1146
|
+
if os.path.isdir(pkg) and not os.path.isdir(pkg_bin):
|
|
1147
|
+
msg = "包目录缺 bin/(安装未完成)"
|
|
1148
|
+
(warns if good else fails).append(msg)
|
|
1149
|
+
|
|
1150
|
+
problems = fails + warns
|
|
1151
|
+
recovery = [
|
|
1152
|
+
"node ~/.npm-global/lib/node_modules/@sokeai/cli/scripts/install.js",
|
|
1153
|
+
"ln -sf ../lib/node_modules/@sokeai/cli/scripts/run.js ~/.npm-global/bin/soke-cli",
|
|
1154
|
+
"~/.npm-global/bin/soke-cli doctor",
|
|
1155
|
+
]
|
|
1156
|
+
report = {"ok": not fails, "probes": probes, "problems": problems,
|
|
1157
|
+
"fails": fails, "warnings": warns,
|
|
1158
|
+
"recovery": recovery if problems else []}
|
|
1159
|
+
if args.out:
|
|
1160
|
+
jdump(args.out, report)
|
|
1161
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
1162
|
+
return 0 if not problems else 2
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def main() -> int:
|
|
1166
|
+
ap = argparse.ArgumentParser(description="DEMO 会话守卫(单实例锁/统一日志/台账渲染/临时清理)")
|
|
1167
|
+
ap.add_argument("--self-test", action="store_true")
|
|
1168
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
1169
|
+
|
|
1170
|
+
p = sub.add_parser("acquire")
|
|
1171
|
+
p.add_argument("--demo-root", required=True)
|
|
1172
|
+
p.add_argument("--module", default="")
|
|
1173
|
+
p.add_argument("--force", action="store_true")
|
|
1174
|
+
p.set_defaults(fn=cmd_acquire)
|
|
1175
|
+
|
|
1176
|
+
p = sub.add_parser("release")
|
|
1177
|
+
p.add_argument("--demo-root", required=True)
|
|
1178
|
+
p.add_argument("--module", default="")
|
|
1179
|
+
p.add_argument("--status", choices=["ok", "failed", "interrupted"], default="")
|
|
1180
|
+
p.add_argument("--force", action="store_true")
|
|
1181
|
+
p.set_defaults(fn=cmd_release)
|
|
1182
|
+
|
|
1183
|
+
p = sub.add_parser("status")
|
|
1184
|
+
p.add_argument("--demo-root", required=True)
|
|
1185
|
+
p.add_argument("--report-only", action="store_true", help="只报告,不以不一致返回非 0")
|
|
1186
|
+
p.set_defaults(fn=cmd_status)
|
|
1187
|
+
|
|
1188
|
+
p = sub.add_parser("state", help="唯一写入口:原子合并写 state.json 并重渲台账")
|
|
1189
|
+
p.add_argument("--demo-root", required=True)
|
|
1190
|
+
p.add_argument("--module", required=True, help="模块规范名(别名会自动归一)")
|
|
1191
|
+
p.add_argument("--status", required=True, choices=list(MODULE_STATUS))
|
|
1192
|
+
p.add_argument("--outputs", help="逗号分隔的产出物文件名(默认追加去重)")
|
|
1193
|
+
p.add_argument("--replace-outputs", action="store_true", help="覆盖而非追加 outputs")
|
|
1194
|
+
p.add_argument("--verify", help="回验结果一句话")
|
|
1195
|
+
p.add_argument("--note", help="备注/待处理一句话")
|
|
1196
|
+
p.add_argument("--blueprint-id", help="首次写入时补 blueprint_id")
|
|
1197
|
+
p.add_argument("--pending-add", action="append", metavar="TEXT", help="追加一条待处理(可重复)")
|
|
1198
|
+
p.add_argument("--pending-remove", action="append", metavar="TEXT", help="移除一条待处理(可重复)")
|
|
1199
|
+
p.add_argument("--set", action="append", metavar="K=V",
|
|
1200
|
+
help="自定义字段(值按 JSON 解析,失败当字符串),如 --set assigned=10")
|
|
1201
|
+
p.add_argument("--verify-file", metavar="PATH",
|
|
1202
|
+
help="*-verify.json 路径;ok!=true 时拒绝记 done(外部可验证信号)")
|
|
1203
|
+
p.add_argument("--require-files", action="store_true",
|
|
1204
|
+
help="outputs 里形如文件的条目必须在 demo_root 下存在且非空")
|
|
1205
|
+
p.set_defaults(fn=cmd_state)
|
|
1206
|
+
|
|
1207
|
+
p = sub.add_parser("log")
|
|
1208
|
+
p.add_argument("--demo-root", required=True)
|
|
1209
|
+
p.add_argument("--module", required=True)
|
|
1210
|
+
p.add_argument("--msg")
|
|
1211
|
+
p.add_argument("--file", help="逐行写入的日志文件(绕开 shell 转义,推荐 agent 用)")
|
|
1212
|
+
p.add_argument("--interval", type=float, default=0.3,
|
|
1213
|
+
help="--file 的行间间隔秒(默认 0.3;0 会让同秒 ≥5 行被 audit-log 判为回填)")
|
|
1214
|
+
p.add_argument("--src", choices=["script", "agent"], default="script")
|
|
1215
|
+
|
|
1216
|
+
def _log(a):
|
|
1217
|
+
if a.file:
|
|
1218
|
+
n = append_log_file(a.demo_root, a.module, a.file, a.src, a.interval)
|
|
1219
|
+
print(f"written={n} → run.log")
|
|
1220
|
+
return 0 if n else 2
|
|
1221
|
+
if not a.msg:
|
|
1222
|
+
print("❌ --msg 或 --file 至少给一个")
|
|
1223
|
+
return 4
|
|
1224
|
+
print(append_log(a.demo_root, a.module, a.msg, a.src))
|
|
1225
|
+
return 0
|
|
1226
|
+
p.set_defaults(fn=_log)
|
|
1227
|
+
|
|
1228
|
+
p = sub.add_parser("summary", help="从产物 JSON 机械生成 RUN SUMMARY(禁手写数字)")
|
|
1229
|
+
p.add_argument("--demo-root", required=True)
|
|
1230
|
+
p.add_argument("--module", required=True)
|
|
1231
|
+
p.set_defaults(fn=cmd_summary)
|
|
1232
|
+
|
|
1233
|
+
p = sub.add_parser("audit-log", help="审计日志:回填特征 / 缺 SUMMARY / 虚构 uuid")
|
|
1234
|
+
p.add_argument("--demo-root", required=True)
|
|
1235
|
+
p.add_argument("--gap", type=int, default=5, help="同秒行数阈值(≥ 判为疑似回填)")
|
|
1236
|
+
p.add_argument("--since", help='只审该时刻之后的行,如 "2026-10-21 11:00:00"')
|
|
1237
|
+
p.set_defaults(fn=cmd_audit_log)
|
|
1238
|
+
|
|
1239
|
+
p = sub.add_parser("ledger")
|
|
1240
|
+
p.add_argument("--demo-root", required=True)
|
|
1241
|
+
p.set_defaults(fn=cmd_ledger)
|
|
1242
|
+
|
|
1243
|
+
p = sub.add_parser("clean")
|
|
1244
|
+
p.add_argument("--demo-root", required=True)
|
|
1245
|
+
p.add_argument("--apply", action="store_true")
|
|
1246
|
+
p.set_defaults(fn=cmd_clean)
|
|
1247
|
+
|
|
1248
|
+
p = sub.add_parser("deliver-check", help="交付一致性:state↔平台↔手册↔日志 四方对齐(只读)")
|
|
1249
|
+
p.add_argument("--demo-root", required=True)
|
|
1250
|
+
p.add_argument("--cli", default=next((c for c in CLI_CANDIDATES if c and os.path.exists(c)), ""),
|
|
1251
|
+
help="soke-cli 路径(默认按 SOKE_CLI/常见安装位/PATH 自动探测)")
|
|
1252
|
+
p.add_argument("--gap", type=int, default=5)
|
|
1253
|
+
p.add_argument("--since", default="", help="只审该时刻之后的日志")
|
|
1254
|
+
p.add_argument("--skip-remote", action="store_true", help="不查平台(离线对产物自检)")
|
|
1255
|
+
p.add_argument("--out", help="报告落盘路径,默认 <demo-root>/deliver-check.json")
|
|
1256
|
+
p.set_defaults(fn=cmd_deliver_check)
|
|
1257
|
+
|
|
1258
|
+
p = sub.add_parser("cli-check", help="体检 soke-cli(自更新中断/符号链接丢失/包不完整)")
|
|
1259
|
+
p.add_argument("--out", help="报告落盘路径(可选)")
|
|
1260
|
+
p.set_defaults(fn=cmd_cli_check)
|
|
1261
|
+
|
|
1262
|
+
args = ap.parse_args()
|
|
1263
|
+
if args.self_test:
|
|
1264
|
+
return self_test()
|
|
1265
|
+
if not getattr(args, "fn", None):
|
|
1266
|
+
ap.print_help()
|
|
1267
|
+
return 4
|
|
1268
|
+
return args.fn(args)
|
|
1269
|
+
|
|
1270
|
+
|
|
1271
|
+
if __name__ == "__main__":
|
|
1272
|
+
sys.exit(main())
|