wf-patch.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. wf-patch.py — workflow.json 的安全批量字段设置器.
  5. 为什么有这个工具:
  6. workflow.json 由各 phase **直接 Write 骨架 + 逐字段填充** 演化. 但「给几十个 IO
  7. 逐个加 anchor」「给每个 step 填 effect/action/type」这类批量字段赋值, 用 Edit
  8. 一处一处改太碎, 手写整段 JSON 又极易踩转义 / 控制字符坑 (把文件搞坏).
  9. wf-patch 卡在中间: **你只负责语义决策 (path=value), 工具负责安全落盘 + 合法性校验**.
  10. - 安全 IO: 工具自己 json.load -> 改 -> json.dump(ensure_ascii=False), 你永远不手写 JSON.
  11. - 写入即校验 (fail-fast): 每条赋值立刻对照字典树 / type_registry / anchor 格式校验,
  12. **任何一条非法 -> 报具体哪条错, 整批不写** (不产出悄悄错的文件). lint 仍做全局兜底.
  13. 用法:
  14. # 单条 / 多条 --set (path=value, 只在第一个 '=' 处切, value 可含 '=' 和空格)
  15. python spec/tools/wf-patch.py --workflow outputs/case-N/workflow.json \
  16. --set 'p1.s1.inputs[0].anchor=← s0.主角图' \
  17. --set 'p1.s2.effect=主体生成' \
  18. --set 'p1.s2.action=生成/图像生成/文生图'
  19. # 或一次性喂一份 patch 清单 (适合 1.3 加 anchor / 2A 填字段这种几十处批量)
  20. python spec/tools/wf-patch.py --workflow outputs/case-N/workflow.json --patch _scratch/anchors.json
  21. # anchors.json = [{"path": "p1.s1.inputs[0].anchor", "value": "← s0.x"}, ...]
  22. # 只校验不写
  23. python spec/tools/wf-patch.py --workflow ... --set '...' --dry-run
  24. 路径语法 (proc / step 按 id 寻址, 不是下标; 只有真列表才用 [i]):
  25. p1.s2.effect step 标量字段 (effect/via/action/feature/control/kind/intent/group ...)
  26. p1.s1.inputs[0].anchor IO 字段 (anchor/type/substance/form/name/value)
  27. p1.s1.outputs[0].type
  28. p1.purpose procedure 头部字段 (name/purpose/category/platform/author)
  29. p1.type_registry.场景图.extends 注册 case-specific 类型 (会自动建 type_registry 段)
  30. p1.type_registry.场景图.desc
  31. value 特殊取值:
  32. __null__ -> JSON null (用于 substance/form 可空)
  33. 不在职责内 (仍用 Write / Edit):
  34. - workflow.json 骨架的首次创建 (Phase 1.2 从 template Write)
  35. - instruction (列表套列表, 1-2 行手动 Edit 即可)
  36. - 删字段 / 删 step / 调结构
  37. 退出码:
  38. 0 全部赋值校验通过并写入 (--dry-run 时为校验通过)
  39. 1 有赋值校验失败 (整批未写) / 路径解析失败
  40. 2 CLI 参数错误 / 文件不存在 / JSON 损坏
  41. """
  42. from __future__ import annotations
  43. import argparse
  44. import json
  45. import re
  46. import subprocess
  47. import sys
  48. from pathlib import Path
  49. # spec/tools/wf-patch.py -> procedure-dsl/
  50. DSL_ROOT = Path(__file__).resolve().parent.parent.parent
  51. TAX_DIR = DSL_ROOT / 'spec' / 'taxonomy'
  52. LOOKUP = DSL_ROOT / 'spec' / 'tools' / 'taxonomy-lookup.py'
  53. # Windows 控制台 UTF-8
  54. for _s in (sys.stdout, sys.stderr):
  55. if hasattr(_s, 'reconfigure'):
  56. try:
  57. _s.reconfigure(encoding='utf-8', errors='replace')
  58. except Exception:
  59. pass
  60. # 受控词 (与 syntax.md §3 / action.json $control 对齐)
  61. FEATURE_VOCAB = {'随机', '幂等', '人工', '本地', '写外部', '读外部', '-'}
  62. KIND_VOCAB = {'step', 'block', 'nested', 'atom'}
  63. # value/directive 里的「引用占位」文案 — 这些是 anchor 的活, value 应填数据本身.
  64. # 命中即视为「未真正回填」(--resolve-passthrough 会尝试填, lint 会报警).
  65. META_REF = re.compile(r'[((]?\s*同\s*s[\d]|见\s*s[\d]|←\s*s[\d]|同上')
  66. class PathError(Exception):
  67. """路径无法解析到 workflow.json 里的目标位置."""
  68. # ===========================================================================
  69. # 字典树加载: leaf 集 + {leaf: 全路径} + 全叶路径集 (与 lint 同款叶子派生)
  70. # ===========================================================================
  71. def _load_tree(name: str):
  72. """读 spec/taxonomy/{name}.json. 返回 (leaves:set, leaf2path:dict, control:list)."""
  73. f = TAX_DIR / f'{name}.json'
  74. if not f.exists():
  75. return set(), {}, []
  76. d = json.loads(f.read_text(encoding='utf-8'))
  77. leaf2path: dict[str, str] = {}
  78. def walk(node: dict, prefix: list[str]):
  79. nm = node.get('分类名称')
  80. if not nm:
  81. return
  82. p = prefix + [nm]
  83. kids = node.get('子分类') or []
  84. if not kids: # 无子分类 = 叶子
  85. leaf2path[nm] = '/'.join(p)
  86. for c in kids:
  87. walk(c, p)
  88. for top in d.get('最终分类树') or []:
  89. walk(top, [])
  90. leaves = set(d.get('$leaves') or leaf2path.keys())
  91. return leaves, leaf2path, (d.get('$control') or [])
  92. EFFECT_LEAVES, EFFECT_PATHS, _ = _load_tree('effect')
  93. ACTION_LEAVES, ACTION_PATHS, ACTION_CONTROL = _load_tree('action')
  94. TYPE_LEAVES, TYPE_PATHS, _ = _load_tree('type')
  95. CONTROL_VOCAB = set(ACTION_CONTROL) | {'-'}
  96. # substance/form 校验结果缓存 (subprocess 较慢)
  97. _taxo_cache: dict[tuple[str, str], bool] = {}
  98. def _taxo_valid(dim: str, path: str) -> bool:
  99. """调 taxonomy-lookup.py --validate, exit 0 = 合法. 结果缓存."""
  100. key = (dim, path)
  101. if key in _taxo_cache:
  102. return _taxo_cache[key]
  103. try:
  104. r = subprocess.run(
  105. [sys.executable, str(LOOKUP), '--dim', dim, '--validate', path],
  106. capture_output=True, text=True,
  107. )
  108. ok = (r.returncode == 0)
  109. except Exception:
  110. ok = False # 校验器跑不起来时, 保守判非法
  111. _taxo_cache[key] = ok
  112. return ok
  113. def _closest(name: str, leaves) -> str:
  114. """给个最接近的叶子名做提示 (子串/前缀朴素匹配, 仅供报错文案)."""
  115. cands = [lf for lf in leaves if name and (name in lf or lf in name)]
  116. return (' 最接近: ' + '/'.join(cands[:3])) if cands else ''
  117. # ===========================================================================
  118. # 字段校验 -> (ok, normalized_value, err_msg)
  119. # ===========================================================================
  120. def validate_field(field: str, value, proc: dict):
  121. # null 哨兵 (substance/form 可空)
  122. if value == '__null__':
  123. if field in ('substance', 'form'):
  124. return True, None, ''
  125. return False, value, f'__null__ 只对 substance/form 有意义, {field} 不可为 null'
  126. if field == 'effect':
  127. if value in EFFECT_LEAVES:
  128. return True, value, ''
  129. # 给了全路径 -> 归一到叶名 (schema 存叶名)
  130. for leaf, path in EFFECT_PATHS.items():
  131. if value == path:
  132. return True, leaf, ''
  133. return False, value, f'effect={value!r} 不是 effect.json 叶子(存叶名).{_closest(value, EFFECT_LEAVES)}'
  134. if field == 'action':
  135. # action 存全路径; 给叶名自动展开, 给全叶路径原样接受
  136. if value in ACTION_PATHS: # 是叶名
  137. return True, ACTION_PATHS[value], ''
  138. if value in ACTION_PATHS.values(): # 是合法叶路径
  139. return True, value, ''
  140. return False, value, (f'action={value!r} 不是合法动作叶子/叶路径 '
  141. f'(形如 生成/图像生成/文生图).{_closest(value.split("/")[-1], ACTION_LEAVES)}')
  142. if field == 'type':
  143. if value in TYPE_LEAVES:
  144. return True, value, ''
  145. reg = proc.get('type_registry') or {}
  146. if value in reg:
  147. return True, value, ''
  148. return False, value, (f'type={value!r} 不是 type.json 叶子, 也没在本工序 type_registry 注册. '
  149. f'先 --set {proc.get("id")}.type_registry.{value}.extends=<叶子> 再用.{_closest(value, TYPE_LEAVES)}')
  150. if field == 'extends': # type_registry entry 的 extends 必须桥到 stdlib 叶子
  151. if value in TYPE_LEAVES:
  152. return True, value, ''
  153. return False, value, f'type_registry extends={value!r} 必须是 type.json 叶子.{_closest(value, TYPE_LEAVES)}'
  154. if field == 'substance':
  155. if _taxo_valid('实质', value):
  156. return True, value, ''
  157. return False, value, f'substance={value!r} 不在实质词表 (taxonomy-lookup --dim 实质 --subtree 查可用叶子)'
  158. if field == 'form':
  159. if _taxo_valid('形式', value):
  160. return True, value, ''
  161. return False, value, f'form={value!r} 不在形式词表 (taxonomy-lookup --dim 形式 --subtree 查可用叶子)'
  162. if field == 'anchor':
  163. if re.match(r'^\s*(←|→)', str(value)):
  164. return True, value, ''
  165. return False, value, f'anchor={value!r} 须以 ← (输入引用) 或 → (输出去向) 开头'
  166. if field == 'feature':
  167. if value in FEATURE_VOCAB:
  168. return True, value, ''
  169. return False, value, f'feature={value!r} 不在受控词 {sorted(FEATURE_VOCAB)}'
  170. if field == 'control':
  171. if value in CONTROL_VOCAB:
  172. return True, value, ''
  173. return False, value, f'control={value!r} 不在受控词 {sorted(CONTROL_VOCAB)}'
  174. if field == 'kind':
  175. if value in KIND_VOCAB:
  176. return True, value, ''
  177. return False, value, f'kind={value!r} 不在 {sorted(KIND_VOCAB)}'
  178. # 自由文本字段 (name/value/intent/via/purpose/category/platform/author/desc/group...)
  179. return True, value, ''
  180. # ===========================================================================
  181. # 路径解析 -> (parent_container, key, proc, field_name)
  182. # ===========================================================================
  183. _SEG = re.compile(r'^([^\[]+)(?:\[(\d+)\])?$')
  184. def _split_seg(seg: str):
  185. m = _SEG.match(seg)
  186. if not m:
  187. raise PathError(f'非法路径段 {seg!r}')
  188. return m.group(1), (int(m.group(2)) if m.group(2) is not None else None)
  189. def locate(data: dict, path: str):
  190. """把 path 解析到目标. 返回 (parent, key, proc, field_name).
  191. 设置即 parent[key] = value. proc 给校验提供 type_registry 上下文.
  192. proc / step 按 id 寻址 (不是下标); inputs/outputs 用 [i] 下标.
  193. step id 可能带点 (嵌套步 s2.1) — 用最长前缀匹配消歧 (s2.1 优先于 s2).
  194. """
  195. if '.' not in path:
  196. raise PathError(f'路径太短 {path!r}, 至少 <proc>.<字段>')
  197. proc_id, remainder = path.split('.', 1)
  198. proc = next((p for p in (data.get('procedures') or []) if p.get('id') == proc_id), None)
  199. if proc is None:
  200. ids = [p.get('id') for p in (data.get('procedures') or [])]
  201. raise PathError(f'找不到 procedure id={proc_id!r} (现有: {ids})')
  202. # --- type_registry 分支 (允许自动建段/条目) ---
  203. if remainder == 'type_registry' or remainder.startswith('type_registry.'):
  204. parts = remainder.split('.')
  205. if len(parts) == 3:
  206. reg = proc.setdefault('type_registry', {})
  207. entry = reg.setdefault(parts[1], {})
  208. return entry, parts[2], proc, parts[2]
  209. raise PathError('type_registry 路径形如 p1.type_registry.<类型名>.<extends|desc>')
  210. # --- step 分支 (最长前缀匹配 step id, 兼容带点的嵌套步 id) ---
  211. matched = None
  212. for s in (proc.get('steps') or []):
  213. sid = s.get('id')
  214. if not sid:
  215. continue
  216. if remainder == sid:
  217. raise PathError(f'step 路径要带字段, 形如 {proc_id}.{sid}.effect')
  218. if remainder.startswith(sid + '.') and (matched is None or len(sid) > len(matched['id'])):
  219. matched = s
  220. if matched is not None:
  221. sid = matched['id']
  222. field_part = remainder[len(sid) + 1:] # 'sid.' 之后
  223. fsegs = field_part.split('.')
  224. name2, idx2 = _split_seg(fsegs[0])
  225. if name2 in ('inputs', 'outputs'):
  226. if idx2 is None:
  227. raise PathError(f'{name2} 要带下标, 形如 {name2}[0]')
  228. lst = matched.get(name2)
  229. if not isinstance(lst, list) or idx2 >= len(lst):
  230. raise PathError(f'{proc_id}.{sid}.{name2}[{idx2}] 越界 (该 step 有 {len(lst or [])} 个 {name2})')
  231. if len(fsegs) != 2:
  232. raise PathError(f'IO 路径形如 {proc_id}.{sid}.{name2}[{idx2}].anchor')
  233. return lst[idx2], fsegs[1], proc, fsegs[1]
  234. else:
  235. if len(fsegs) != 1:
  236. raise PathError(f'step 标量字段形如 {proc_id}.{sid}.{name2}')
  237. return matched, name2, proc, name2
  238. # --- procedure 头部字段 (单段) ---
  239. if '.' not in remainder:
  240. return proc, remainder, proc, remainder
  241. raise PathError(f'无法解析 {path!r}: {remainder.split(".")[0]!r} 既不是 {proc_id} 的 step id, 也不是单段 proc 字段')
  242. # ===========================================================================
  243. # 透传回填: anchor 为纯 ← sN.varname 的 IO, 从源 output 抄 value (逐字回填)
  244. # ===========================================================================
  245. def _is_fillable(value) -> bool:
  246. """该 value 算「还没真正回填」吗 — 空 / 占位符 / 引用文案."""
  247. if value in (None, '', '-'):
  248. return True
  249. return bool(META_REF.search(str(value)))
  250. def _parse_passthrough(anchor, step_ids: list[str]):
  251. """把 anchor 解析成纯透传源 (src_step, src_name); 非干净透传返回 None.
  252. 只认 `← sN.varname` 形式 (sN 按已知 step id 最长前缀匹配, 兼容 s2.1);
  253. `← 工序输入` / `← s6 (链, 上一张)` / 带容器索引等不算 (无法确定唯一源 value).
  254. varname 末尾的 [i] / (...) 注释会被剥掉再查.
  255. """
  256. m = re.match(r'^\s*←\s*(.+)$', str(anchor or ''))
  257. if not m:
  258. return None
  259. body = m.group(1).strip()
  260. for sid in sorted(step_ids, key=len, reverse=True):
  261. if body.startswith(sid + '.'):
  262. name = body[len(sid) + 1:].strip()
  263. name = re.sub(r'\s*[\[((].*$', '', name).strip() # 剥掉 [i] / (注释)
  264. return (sid, name) if name else None
  265. return None
  266. def _extract_ref(text, step_ids: list[str]):
  267. """从 directive/文案里抽 (src_step, src_name) 引用; 抽不出返回 None.
  268. 认「同 sN.name」「(同 sN.name 全文)」「见 sN.name」等. sN 按已知 step id
  269. 最长前缀匹配 (兼容 s2.1).
  270. """
  271. m = re.search(r'[同见]\s*([^\s)),,。]+)', str(text or ''))
  272. if not m:
  273. return None
  274. body = m.group(1)
  275. for sid in sorted(step_ids, key=len, reverse=True):
  276. if body.startswith(sid + '.'):
  277. name = re.sub(r'\s*[\[((].*$', '', body[len(sid) + 1:]).strip()
  278. return (sid, name) if name else None
  279. return None
  280. def resolve_passthrough(data: dict):
  281. """把 anchor 为纯透传、value/directive 仍空或占位的位置, 用源 output 的 value 逐字填上.
  282. 覆盖两类: (a) IO 的 value (anchor=← sN.varname); (b) instruction 的 directive
  283. (文案里「同 sN.varname」). 迭代到不动点 (处理链式透传). 返回 (filled_msgs, warn_msgs).
  284. """
  285. out_index = {} # (step_id, name) -> output item (读 value)
  286. step_ids: list[str] = []
  287. for p in data.get('procedures') or []:
  288. for s in p.get('steps') or []:
  289. sid = s.get('id')
  290. if sid:
  291. step_ids.append(sid)
  292. for o in s.get('outputs') or []:
  293. if isinstance(o, dict) and o.get('name'):
  294. out_index[(sid, o['name'])] = o
  295. def _src_value(ref):
  296. """源存在且自己已填好 → 返回其 value; 否则 None."""
  297. src = out_index.get(ref)
  298. if src is None or _is_fillable(src.get('value')):
  299. return None
  300. return src['value']
  301. filled: list[str] = []
  302. changed, rounds = True, 0
  303. while changed and rounds < 20:
  304. changed, rounds = False, rounds + 1
  305. for p in data.get('procedures') or []:
  306. for s in p.get('steps') or []:
  307. # (a) IO value
  308. for kind in ('inputs', 'outputs'):
  309. for idx, io in enumerate(s.get(kind) or []):
  310. if not isinstance(io, dict) or not _is_fillable(io.get('value')):
  311. continue
  312. pt = _parse_passthrough(io.get('anchor'), step_ids)
  313. val = _src_value(pt) if pt else None
  314. if val is None:
  315. continue
  316. io['value'] = val
  317. filled.append(
  318. f"{p.get('id')}.{s.get('id')}.{kind}[{idx}].value "
  319. f"← 复制自 {pt[0]}.{pt[1]} ({len(str(val))} 字)"
  320. )
  321. changed = True
  322. # (b) instruction directive (喂给工具的 prompt = 引用的 output 原文)
  323. for di, pair in enumerate(s.get('instruction') or []):
  324. if not (isinstance(pair, list) and len(pair) == 2 and pair[0] == 'directive'):
  325. continue
  326. if not _is_fillable(pair[1]):
  327. continue
  328. ref = _extract_ref(pair[1], step_ids)
  329. val = _src_value(ref) if ref else None
  330. if val is None:
  331. continue
  332. pair[1] = val
  333. filled.append(
  334. f"{p.get('id')}.{s.get('id')}.instruction[{di}](directive) "
  335. f"← 复制自 {ref[0]}.{ref[1]} ({len(str(val))} 字)"
  336. )
  337. changed = True
  338. # 仍填不动的透传 (源找不到) → warn
  339. warns: list[str] = []
  340. for p in data.get('procedures') or []:
  341. for s in p.get('steps') or []:
  342. for kind in ('inputs', 'outputs'):
  343. for idx, io in enumerate(s.get(kind) or []):
  344. if not isinstance(io, dict) or not _is_fillable(io.get('value')):
  345. continue
  346. pt = _parse_passthrough(io.get('anchor'), step_ids)
  347. if pt and out_index.get(pt) is None:
  348. warns.append(
  349. f"{p.get('id')}.{s.get('id')}.{kind}[{idx}] anchor 指向 "
  350. f"{pt[0]}.{pt[1]} 但找不到该 output (检查 anchor / 变量名)"
  351. )
  352. return filled, warns
  353. # ===========================================================================
  354. # 应用
  355. # ===========================================================================
  356. def load_patches(args) -> list[tuple[str, str]]:
  357. """汇总 --set 与 --patch 成 [(path, value), ...]."""
  358. out: list[tuple[str, str]] = []
  359. for s in args.set or []:
  360. if '=' not in s:
  361. raise SystemExit(f'wf-patch: --set 缺 "=" : {s!r} (形如 path=value)')
  362. path, value = s.split('=', 1) # 只切第一个 '='
  363. out.append((path.strip(), value))
  364. if args.patch:
  365. if not args.patch.exists():
  366. raise SystemExit(f'wf-patch: --patch 文件不存在 {args.patch}')
  367. try:
  368. items = json.loads(args.patch.read_text(encoding='utf-8'))
  369. except json.JSONDecodeError as e:
  370. raise SystemExit(f'wf-patch: --patch 不是合法 JSON: {e}')
  371. for it in items:
  372. out.append((it['path'], it['value']))
  373. return out
  374. def main() -> None:
  375. ap = argparse.ArgumentParser(
  376. prog='wf-patch.py',
  377. description='workflow.json 安全批量字段设置器 (写入即校验, 任何一条非法整批不写)',
  378. )
  379. ap.add_argument('--workflow', type=Path, required=True, help='目标 workflow.json')
  380. ap.add_argument('--set', action='append', metavar='PATH=VALUE',
  381. help='单条赋值, 可重复. 只在第一个 = 处切; value 可含 = 和空格 (记得整体加引号)')
  382. ap.add_argument('--patch', type=Path, default=None,
  383. help='批量赋值清单 .json: [{"path":..,"value":..}, ...]')
  384. ap.add_argument('--resolve-passthrough', action='store_true',
  385. help='把 anchor 为纯透传 (← sN.varname)、value 仍空/占位的 IO, 顺 anchor 从源 output 逐字抄 value. 可单独跑, 也可跟在 --set/--patch 后 (先赋值再解析). 迭代处理链式透传')
  386. ap.add_argument('--dry-run', action='store_true', help='只校验/预演, 不写')
  387. args = ap.parse_args()
  388. wf = args.workflow
  389. if not wf.exists():
  390. print(f'wf-patch: 文件不存在 {wf}', file=sys.stderr)
  391. sys.exit(2)
  392. try:
  393. data = json.loads(wf.read_text(encoding='utf-8'))
  394. except json.JSONDecodeError as e:
  395. print(f'wf-patch: {wf} 不是合法 JSON: {e}', file=sys.stderr)
  396. sys.exit(2)
  397. patches = load_patches(args)
  398. if not patches and not args.resolve_passthrough:
  399. print('wf-patch: 没有 --set / --patch / --resolve-passthrough, 啥也没干', file=sys.stderr)
  400. sys.exit(2)
  401. # 先全部解析 + 校验, 收集计划; 任何一条失败 -> 整批不写
  402. plan = [] # (parent, key, normalized_value, path, display)
  403. errors = [] # (path, msg)
  404. for path, value in patches:
  405. try:
  406. parent, key, proc, field = locate(data, path)
  407. except PathError as e:
  408. errors.append((path, str(e)))
  409. continue
  410. ok, norm, msg = validate_field(field, value, proc)
  411. if not ok:
  412. errors.append((path, msg))
  413. continue
  414. plan.append((parent, key, norm, path, norm if norm is not None else 'null'))
  415. if patches:
  416. print(f'[wf-patch] {wf.name} — {len(patches)} 条赋值, {len(plan)} 通过, {len(errors)} 失败')
  417. for _parent, _key, _norm, path, disp in plan:
  418. print(f' ✓ {path} = {disp}')
  419. for path, msg in errors:
  420. print(f' ✗ {path} — {msg}')
  421. if errors:
  422. print(f'\n有 {len(errors)} 条校验失败, 整批未写入 (修正后重跑).', file=sys.stderr)
  423. sys.exit(1)
  424. # 赋值先落到内存 data (resolve 要看到它们); 是否持久化由 dry-run 决定
  425. for parent, key, norm, _, _ in plan:
  426. parent[key] = norm
  427. # 透传回填
  428. filled, warns = [], []
  429. if args.resolve_passthrough:
  430. filled, warns = resolve_passthrough(data)
  431. print(f'[resolve-passthrough] 回填 {len(filled)} 处透传 value, {len(warns)} 处填不动')
  432. for m in filled:
  433. print(f' ✓ {m}')
  434. for w in warns:
  435. print(f' ⚠ {w}')
  436. n_changes = len(plan) + len(filled)
  437. if args.dry_run:
  438. print(f'\n--dry-run: 预演 {n_changes} 处改动, 未写入.')
  439. sys.exit(0)
  440. if n_changes == 0:
  441. print('\n没有改动 (透传 value 都已填好 / 无可赋值), 未写文件.')
  442. sys.exit(0)
  443. # 落盘 (安全序列化, 你从不手写 JSON)
  444. wf.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
  445. print(f'\n已写入 {n_changes} 处到 {wf.name}.')
  446. sys.exit(0)
  447. if __name__ == '__main__':
  448. main()