wf-patch.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. # 删字段 (取代手 Edit 删; 字段不存在则幂等跳过)
  25. python spec/tools/wf-patch.py --workflow ... --unset 'p1.declarations.inputs[0].inferred'
  26. # 只校验不写
  27. python spec/tools/wf-patch.py --workflow ... --set '...' --dry-run
  28. 路径语法 (proc / step 按 id 寻址, 不是下标; 只有真列表才用 [i]; 嵌套步 id 带点 s2.1 也支持):
  29. p1.s2.effect step 标量字段 (effect/substance/form/via/action/directive/kind/intent/group)
  30. p1.s1.inputs[0].anchor IO 字段 (anchor/type/value/id)
  31. p1.s2.focus step 的 focus 数组 (逗号分隔: focus=via,action,out-type-0)
  32. p1.purpose procedure 头部字段 (name/purpose/category/platform/author)
  33. p1.declarations.inputs[0].desc declarations 内任意字段 (通用下钻)
  34. source.url case-level 原帖信息 (platform/author/date/url/title/excerpt)
  35. p1.type_registry.场景图.extends 注册 case-specific 类型 (会自动建 type_registry 段)
  36. value 特殊取值:
  37. __null__ -> JSON null (用于 substance/form/url 可空)
  38. 仍用 Write / Edit 的只剩 (尽量别碰生 JSON):
  39. - workflow.json 骨架的首次创建 (Phase 1.2 从 template Write)
  40. - instruction (列表套列表, 手动 Edit; 透传 directive 用 --resolve-passthrough)
  41. 改字段/删字段/改 source 现在都走本工具, 不要再 Read→Edit 改 workflow.json (会反复重读、烧 token).
  42. 自动修引号 (load 时兜底):
  43. workflow.json 由模型直 Write, 偶尔把中文引号写成未转义的 ASCII " → JSON 崩.
  44. 本工具 load 失败时会自动把这类误引号修成「」再 parse; 修成功则继续 patch, 并把
  45. 修复随本次写回落盘 (--dry-run 不写). 修不回才按 exit 2 报错. 不用再手写 _scratch 修复脚本.
  46. 退出码:
  47. 0 全部校验通过并写入 (--dry-run 时为校验通过)
  48. 1 有校验失败 (整批未写) / 路径解析失败
  49. 2 CLI 参数错误 / 文件不存在 / JSON 损坏 (且自动修引号也救不回)
  50. """
  51. from __future__ import annotations
  52. import argparse
  53. import json
  54. import re
  55. import subprocess
  56. import sys
  57. from pathlib import Path
  58. # spec/tools/wf-patch.py -> procedure-dsl/
  59. DSL_ROOT = Path(__file__).resolve().parent.parent.parent
  60. TAX_DIR = DSL_ROOT / 'spec' / 'taxonomy'
  61. LOOKUP = DSL_ROOT / 'spec' / 'tools' / 'taxonomy-lookup.py'
  62. # Windows 控制台 UTF-8
  63. for _s in (sys.stdout, sys.stderr):
  64. if hasattr(_s, 'reconfigure'):
  65. try:
  66. _s.reconfigure(encoding='utf-8', errors='replace')
  67. except Exception:
  68. pass
  69. KIND_VOCAB = {'step', 'block', 'nested'}
  70. # value/directive 里的「引用占位」文案 — 这些是 anchor 的活, value 应填数据本身.
  71. # 命中即视为「未真正回填」(--resolve-passthrough 会尝试填, lint 会报警).
  72. META_REF = re.compile(r'[((]?\s*同\s*s[\d]|见\s*s[\d]|←\s*s[\d]|同上')
  73. # ===========================================================================
  74. # 自动修引号: 模型直 Write workflow.json 时常把中文引号写成 ASCII " (未转义) → JSON 崩.
  75. # 仅在 json.loads 失败时兜底调用 (合法文件零开销). 判别: 串内一个 ASCII " 之后第一个
  76. # 非空白字符 ∈ {,:}]} 或 EOF → 真·字符串定界符 (保留); 否则是误写的内容引号 → 换直角
  77. # 引号「」(串内交替 开「/闭」). 逻辑独立内置于本文件 (不 import 任何外部模块);
  78. # scratch/repair_workflow_quotes.py 是同款独立实现, 二者无依赖关系. 改完必须能 parse 才用.
  79. # ===========================================================================
  80. _STRUCT_AFTER = set(',:}]')
  81. def repair_ascii_quotes(raw: str):
  82. """→ (修后文本, 改动的内容引号数). 纯走字符, 不依赖能否 parse."""
  83. out, i, n = [], 0, len(raw)
  84. in_str = esc = False
  85. open_q = True
  86. changes = 0
  87. while i < n:
  88. c = raw[i]
  89. if not in_str:
  90. out.append(c)
  91. if c == '"':
  92. in_str, esc, open_q = True, False, True
  93. i += 1
  94. continue
  95. if esc:
  96. out.append(c); esc = False; i += 1; continue
  97. if c == '\\':
  98. out.append(c); esc = True; i += 1; continue
  99. if c == '"':
  100. j = i + 1
  101. while j < n and raw[j] in ' \t\r\n':
  102. j += 1
  103. nxt = raw[j] if j < n else ''
  104. if nxt == '' or nxt in _STRUCT_AFTER:
  105. out.append(c); in_str = False # 真·结束符
  106. else:
  107. out.append('「' if open_q else '」') # 误写的内容引号
  108. open_q = not open_q
  109. changes += 1
  110. i += 1
  111. continue
  112. out.append(c); i += 1
  113. return ''.join(out), changes
  114. class PathError(Exception):
  115. """路径无法解析到 workflow.json 里的目标位置."""
  116. # ===========================================================================
  117. # 字典树加载: leaf 集 + {leaf: 全路径} + 全叶路径集 (与 lint 同款叶子派生)
  118. # ===========================================================================
  119. def _load_tree(name: str):
  120. """读 spec/taxonomy/{name}.json. 返回 (leaves:set, leaf2path:dict, control:list)."""
  121. f = TAX_DIR / f'{name}.json'
  122. if not f.exists():
  123. return set(), {}, []
  124. d = json.loads(f.read_text(encoding='utf-8'))
  125. leaf2path: dict[str, str] = {}
  126. def walk(node: dict, prefix: list[str]):
  127. nm = node.get('分类名称')
  128. if not nm:
  129. return
  130. p = prefix + [nm]
  131. kids = node.get('子分类') or []
  132. if not kids: # 无子分类 = 叶子
  133. leaf2path[nm] = '/'.join(p)
  134. for c in kids:
  135. walk(c, p)
  136. for top in d.get('最终分类树') or []:
  137. walk(top, [])
  138. leaves = set(d.get('$leaves') or leaf2path.keys())
  139. return leaves, leaf2path, (d.get('$control') or [])
  140. EFFECT_LEAVES, EFFECT_PATHS, _ = _load_tree('effect')
  141. ACTION_LEAVES, ACTION_PATHS, ACTION_CONTROL = _load_tree('action')
  142. TYPE_LEAVES, TYPE_PATHS, _ = _load_tree('type')
  143. # substance/form 校验结果缓存 (subprocess 较慢)
  144. _taxo_cache: dict[tuple[str, str], bool] = {}
  145. def _taxo_valid(dim: str, path: str) -> bool:
  146. """调 taxonomy-lookup.py --validate, exit 0 = 合法. 结果缓存."""
  147. key = (dim, path)
  148. if key in _taxo_cache:
  149. return _taxo_cache[key]
  150. try:
  151. import os
  152. env = os.environ.copy()
  153. env['PYTHONIOENCODING'] = 'utf-8'
  154. r = subprocess.run(
  155. [sys.executable, str(LOOKUP), '--dim', dim, '--validate', path],
  156. capture_output=True, text=True, encoding='utf-8', errors='replace', env=env,
  157. )
  158. ok = (r.returncode == 0)
  159. except Exception:
  160. ok = False # 校验器跑不起来时, 保守判非法
  161. _taxo_cache[key] = ok
  162. return ok
  163. def _closest(name: str, leaves) -> str:
  164. """给个最接近的叶子名做提示 (子串/前缀朴素匹配, 仅供报错文案)."""
  165. cands = [lf for lf in leaves if name and (name in lf or lf in name)]
  166. return (' 最接近: ' + '/'.join(cands[:3])) if cands else ''
  167. # ===========================================================================
  168. # 字段校验 -> (ok, normalized_value, err_msg)
  169. # ===========================================================================
  170. def validate_field(field: str, value, proc: dict, pending_types: set[str] = None):
  171. # null 哨兵 (substance/form/url 可空)
  172. if value == '__null__':
  173. if field in ('substance', 'form', 'url'):
  174. return True, None, ''
  175. return False, value, f'__null__ 只对 substance/form/url 有意义, {field} 不可为 null'
  176. # focus 是数组: 逗号分隔 → list ('via,action,out-type-0'); 空串 → []
  177. if field == 'focus':
  178. items = [t.strip() for t in str(value).split(',') if t.strip()]
  179. return True, items, ''
  180. if field == 'effect':
  181. if value in EFFECT_LEAVES:
  182. return True, value, ''
  183. # 给了全路径 -> 归一到叶名 (schema 存叶名)
  184. for leaf, path in EFFECT_PATHS.items():
  185. if value == path:
  186. return True, leaf, ''
  187. return False, value, f'effect={value!r} 不是 effect.json 叶子(存叶名).{_closest(value, EFFECT_LEAVES)}'
  188. if field == 'action':
  189. # action 存全路径; 给叶名自动展开, 给全叶路径原样接受
  190. if value in ACTION_PATHS: # 是叶名
  191. return True, ACTION_PATHS[value], ''
  192. if value in ACTION_PATHS.values(): # 是合法叶路径
  193. return True, value, ''
  194. return False, value, (f'action={value!r} 不是合法动作叶子/叶路径 '
  195. f'(形如 生成/图像生成/文生图).{_closest(value.split("/")[-1], ACTION_LEAVES)}')
  196. if field == 'type':
  197. if value in TYPE_LEAVES:
  198. return True, value, ''
  199. reg = proc.get('type_registry') or {}
  200. if value in reg:
  201. return True, value, ''
  202. if pending_types and value in pending_types:
  203. return True, value, ''
  204. return False, value, (f'type={value!r} 不是 type.json 叶子, 也没在本工序 type_registry 注册. '
  205. f'先 --set {proc.get("id")}.type_registry.{value}.extends=<叶子> 再用.{_closest(value, TYPE_LEAVES)}')
  206. if field == 'extends': # type_registry entry 的 extends 必须桥到 stdlib 叶子
  207. if value in TYPE_LEAVES:
  208. return True, value, ''
  209. return False, value, f'type_registry extends={value!r} 必须是 type.json 叶子.{_closest(value, TYPE_LEAVES)}'
  210. if field == 'substance':
  211. if isinstance(value, str):
  212. if '+' in value:
  213. paths = [p.strip() for p in value.split('+') if p.strip()]
  214. else:
  215. paths = [value.strip()]
  216. elif isinstance(value, list):
  217. paths = [str(p).strip() for p in value if str(p).strip()]
  218. else:
  219. return False, value, 'substance 必须是字符串或数组'
  220. invalid_paths = []
  221. for p in paths:
  222. if not _taxo_valid('实质', p):
  223. invalid_paths.append(p)
  224. if invalid_paths:
  225. return False, value, f'以下 substance 路径不在实质词表: {invalid_paths}'
  226. norm_val = paths if (isinstance(value, list) or (isinstance(value, str) and '+' in value)) else paths[0]
  227. return True, norm_val, ''
  228. if field == 'form':
  229. if isinstance(value, str):
  230. if '+' in value:
  231. paths = [p.strip() for p in value.split('+') if p.strip()]
  232. else:
  233. paths = [value.strip()]
  234. elif isinstance(value, list):
  235. paths = [str(p).strip() for p in value if str(p).strip()]
  236. else:
  237. return False, value, 'form 必须是字符串或数组'
  238. invalid_paths = []
  239. for p in paths:
  240. if not _taxo_valid('形式', p):
  241. invalid_paths.append(p)
  242. if invalid_paths:
  243. return False, value, f'以下 form 路径不在形式词表: {invalid_paths}'
  244. norm_val = paths if (isinstance(value, list) or (isinstance(value, str) and '+' in value)) else paths[0]
  245. return True, norm_val, ''
  246. if field == 'anchor':
  247. if re.match(r'^\s*(←|→)', str(value)):
  248. return True, value, ''
  249. return False, value, f'anchor={value!r} 须以 ← (输入引用) 或 → (输出去向) 开头'
  250. if field == 'kind':
  251. if value in KIND_VOCAB:
  252. return True, value, ''
  253. return False, value, f'kind={value!r} 不在 {sorted(KIND_VOCAB)}'
  254. # 自由文本字段 (name/value/intent/via/purpose/category/platform/author/desc/group...)
  255. return True, value, ''
  256. # ===========================================================================
  257. # 路径解析 -> (parent_container, key, proc, field_name)
  258. # ===========================================================================
  259. _SEG = re.compile(r'^([^\[]+)(?:\[(\d+)\])?$')
  260. def _split_seg(seg: str):
  261. m = _SEG.match(seg)
  262. if not m:
  263. raise PathError(f'非法路径段 {seg!r}')
  264. return m.group(1), (int(m.group(2)) if m.group(2) is not None else None)
  265. def _descend(container, segs):
  266. """沿 segs 走进 container, 返回 (parent, last_key). 中间节点必须已存在.
  267. segs 每段可带 [i] 下标. last_key 是 dict 键 (str) 或列表下标 (int);
  268. 设置即 parent[last_key]=value, 删除即 del parent[last_key].
  269. 用于 source.* / declarations.* 等通用路径 (proc/step 的 id 寻址不走这里).
  270. """
  271. cur = container
  272. for i, seg in enumerate(segs):
  273. name, idx = _split_seg(seg)
  274. last = (i == len(segs) - 1)
  275. if last and idx is None:
  276. if not isinstance(cur, dict):
  277. raise PathError(f'{name!r} 的父级不是对象')
  278. return cur, name
  279. if not isinstance(cur, dict) or name not in cur:
  280. raise PathError(f'路径段 {name!r} 不存在, 无法下钻')
  281. nxt = cur[name]
  282. if idx is not None:
  283. if not isinstance(nxt, list) or idx >= len(nxt):
  284. raise PathError(f'{name}[{idx}] 越界或非列表')
  285. if last:
  286. return nxt, idx
  287. cur = nxt[idx]
  288. else:
  289. cur = nxt
  290. raise PathError('路径为空')
  291. def locate(data: dict, path: str):
  292. """把 path 解析到目标. 返回 (parent, key, proc, field_name).
  293. 设置即 parent[key] = value. proc 给校验提供 type_registry 上下文.
  294. proc / step 按 id 寻址 (不是下标); inputs/outputs 用 [i] 下标.
  295. step id 可能带点 (嵌套步 s2.1) — 用最长前缀匹配消歧 (s2.1 优先于 s2).
  296. """
  297. if '.' not in path:
  298. raise PathError(f'路径太短 {path!r}, 至少 <proc>.<字段> 或 source.<字段>')
  299. proc_id, remainder = path.split('.', 1)
  300. # --- source.* 分支 (case-level 原帖信息, 无 proc 上下文) ---
  301. if proc_id == 'source':
  302. src = data.setdefault('source', {})
  303. parent, key = _descend(src, remainder.split('.'))
  304. return parent, key, None, (key if isinstance(key, str) else '')
  305. proc = next((p for p in (data.get('procedures') or []) if p.get('id') == proc_id), None)
  306. if proc is None:
  307. ids = [p.get('id') for p in (data.get('procedures') or [])]
  308. raise PathError(f'找不到 procedure id={proc_id!r} (现有: {ids})')
  309. # --- type_registry 分支 (允许自动建段/条目) ---
  310. if remainder == 'type_registry' or remainder.startswith('type_registry.'):
  311. parts = remainder.split('.')
  312. if len(parts) == 3:
  313. reg = proc.setdefault('type_registry', {})
  314. entry = reg.setdefault(parts[1], {})
  315. return entry, parts[2], proc, parts[2]
  316. raise PathError('type_registry 路径形如 p1.type_registry.<类型名>.<extends|desc>')
  317. # --- step 分支 (最长前缀匹配 step id, 兼容带点的嵌套步 id) ---
  318. matched = None
  319. for s in (proc.get('steps') or []):
  320. sid = s.get('id')
  321. if not sid:
  322. continue
  323. if remainder == sid:
  324. raise PathError(f'step 路径要带字段, 形如 {proc_id}.{sid}.effect')
  325. if remainder.startswith(sid + '.') and (matched is None or len(sid) > len(matched['id'])):
  326. matched = s
  327. if matched is not None:
  328. sid = matched['id']
  329. field_part = remainder[len(sid) + 1:] # 'sid.' 之后
  330. fsegs = field_part.split('.')
  331. name2, idx2 = _split_seg(fsegs[0])
  332. if name2 in ('inputs', 'outputs'):
  333. if idx2 is None:
  334. raise PathError(f'{name2} 要带下标, 形如 {name2}[0]')
  335. lst = matched.get(name2)
  336. if not isinstance(lst, list) or idx2 >= len(lst):
  337. raise PathError(f'{proc_id}.{sid}.{name2}[{idx2}] 越界 (该 step 有 {len(lst or [])} 个 {name2})')
  338. if len(fsegs) != 2:
  339. raise PathError(f'IO 路径形如 {proc_id}.{sid}.{name2}[{idx2}].anchor')
  340. return lst[idx2], fsegs[1], proc, fsegs[1]
  341. else:
  342. if len(fsegs) != 1:
  343. raise PathError(f'step 标量字段形如 {proc_id}.{sid}.{name2}')
  344. return matched, name2, proc, name2
  345. # --- proc 内其余路径: 头部字段 / declarations.* / return_row.* 等, 走通用下钻 ---
  346. parent, key = _descend(proc, remainder.split('.'))
  347. return parent, key, proc, (key if isinstance(key, str) else '')
  348. # ===========================================================================
  349. # 透传回填: anchor 为纯 ← sN.varname 的 IO, 从源 output 抄 value (逐字回填)
  350. # ===========================================================================
  351. def _is_fillable(value) -> bool:
  352. """该 value 算「还没真正回填」吗 — 空 / 占位符 / 引用文案."""
  353. if value in (None, '', '-'):
  354. return True
  355. return bool(META_REF.search(str(value)))
  356. def _passthrough_id(anchor):
  357. """anchor 为 `← <output-id>` (可带 [i] 容器索引) → 返回 output id; 否则 None.
  358. `← 工序输入` / `← s6 (链)` 等非纯 id 引用返回 None (无法确定唯一源 value).
  359. """
  360. m = re.match(r'^\s*←\s*([^\s\[((]+)', str(anchor or ''))
  361. if not m:
  362. return None
  363. return m.group(1) or None
  364. def resolve_passthrough(data: dict):
  365. """把 anchor 为纯透传 (← <output-id>)、value 仍空或占位的 input, 用源 output 的 value 逐字填上.
  366. 迭代到不动点 (处理链式透传). 返回 (filled_msgs, warn_msgs).
  367. """
  368. out_index = {} # output id -> output item (读 value)
  369. for p in data.get('procedures') or []:
  370. for s in p.get('steps') or []:
  371. for o in s.get('outputs') or []:
  372. if isinstance(o, dict) and o.get('id'):
  373. out_index[o['id']] = o
  374. def _src_value(rid):
  375. src = out_index.get(rid)
  376. if src is None or _is_fillable(src.get('value')):
  377. return None
  378. return src['value']
  379. filled: list[str] = []
  380. changed, rounds = True, 0
  381. while changed and rounds < 20:
  382. changed, rounds = False, rounds + 1
  383. for p in data.get('procedures') or []:
  384. for s in p.get('steps') or []:
  385. for idx, io in enumerate(s.get('inputs') or []):
  386. if not isinstance(io, dict) or not _is_fillable(io.get('value')):
  387. continue
  388. rid = _passthrough_id(io.get('anchor'))
  389. val = _src_value(rid) if rid else None
  390. if val is None:
  391. continue
  392. io['value'] = val
  393. filled.append(
  394. f"{p.get('id')}.{s.get('id')}.inputs[{idx}].value "
  395. f"← 复制自 {rid} ({len(str(val))} 字)"
  396. )
  397. changed = True
  398. # 仍填不动的透传 (源 id 找不到) → warn
  399. warns: list[str] = []
  400. for p in data.get('procedures') or []:
  401. for s in p.get('steps') or []:
  402. for idx, io in enumerate(s.get('inputs') or []):
  403. if not isinstance(io, dict) or not _is_fillable(io.get('value')):
  404. continue
  405. rid = _passthrough_id(io.get('anchor'))
  406. if rid and out_index.get(rid) is None:
  407. warns.append(
  408. f"{p.get('id')}.{s.get('id')}.inputs[{idx}] anchor 指向 "
  409. f"{rid} 但找不到该 output id (检查 anchor / output id)"
  410. )
  411. return filled, warns
  412. # ===========================================================================
  413. # 应用
  414. # ===========================================================================
  415. def load_patches(args) -> list[tuple[str, str]]:
  416. """汇总 --set、--patch 与 --set-file 成 [(path, value), ...]."""
  417. def _norm(v):
  418. if isinstance(v, str):
  419. # 将中文全角双角/单引号自动归一化为标准半角引号,更利于 AI 生图引擎和 Prompt 语法识别
  420. v = v.replace('“', '"').replace('”', '"').replace('‘', "'").replace('’', "'")
  421. return v
  422. out: list[tuple[str, str]] = []
  423. for s in args.set or []:
  424. if '=' not in s:
  425. raise SystemExit(f'wf-patch: --set 缺 "=" : {s!r} (形如 path=value)')
  426. path, value = s.split('=', 1) # 只切第一个 '='
  427. out.append((path.strip(), _norm(value)))
  428. # 🟢 新增:从外部文件读取值注入
  429. for sf in getattr(args, 'set_file', None) or []:
  430. if '=' not in sf:
  431. raise SystemExit(f'wf-patch: --set-file 缺 "=" : {sf!r} (形如 path=file_path)')
  432. path, fpath_str = sf.split('=', 1)
  433. fpath = Path(fpath_str.strip())
  434. if not fpath.exists():
  435. raise SystemExit(f'wf-patch: --set-file 指定的文件不存在: {fpath_str}')
  436. try:
  437. value = fpath.read_text(encoding='utf-8')
  438. except Exception as e:
  439. raise SystemExit(f'wf-patch: 无法读取 --set-file 指定的文件 {fpath_str}: {e}')
  440. out.append((path.strip(), _norm(value)))
  441. if args.patch:
  442. if not args.patch.exists():
  443. raise SystemExit(f'wf-patch: --patch 文件不存在 {args.patch}')
  444. try:
  445. items = json.loads(args.patch.read_text(encoding='utf-8'))
  446. except json.JSONDecodeError as e:
  447. raise SystemExit(f'wf-patch: --patch 不是合法 JSON: {e}')
  448. for it in items:
  449. out.append((it['path'], _norm(it['value'])))
  450. return out
  451. def main() -> None:
  452. ap = argparse.ArgumentParser(
  453. prog='wf-patch.py',
  454. description='workflow.json 安全批量字段设置器 (写入即校验, 任何一条非法整批不写)',
  455. )
  456. ap.add_argument('--workflow', type=Path, required=True, help='目标 workflow.json')
  457. ap.add_argument('--set', action='append', metavar='PATH=VALUE',
  458. help='单条赋值, 可重复. 只在第一个 = 处切; value 可含 = 和空格 (记得整体加引号)')
  459. ap.add_argument('--patch', type=Path, default=None,
  460. help='批量赋值清单 .json: [{"path":..,"value":..}, ...]')
  461. ap.add_argument('--set-file', action='append', metavar='PATH=FILE_PATH', default=None,
  462. help='从外部文件读取内容注入指定字段. e.g. p1.s1.outputs[0].value=_scratch/prompt.txt')
  463. ap.add_argument('--unset', action='append', metavar='PATH', default=None,
  464. help='删字段, 可重复. e.g. p1.declarations.inputs[0].inferred (字段不存在则跳过). 取代手 Edit 删字段')
  465. ap.add_argument('--resolve-passthrough', action='store_true',
  466. help='把 anchor 为纯透传 (← sN.varname)、value 仍空/占位的 IO, 顺 anchor 从源 output 逐字抄 value. 可单独跑, 也可跟在 --set/--patch 后 (先赋值再解析). 迭代处理链式透传')
  467. ap.add_argument('--dry-run', action='store_true', help='只校验/预演, 不写')
  468. args = ap.parse_args()
  469. wf = args.workflow
  470. if not wf.exists():
  471. print(f'wf-patch: 文件不存在 {wf}', file=sys.stderr)
  472. sys.exit(2)
  473. raw = wf.read_text(encoding='utf-8')
  474. repaired = 0
  475. try:
  476. data = json.loads(raw)
  477. except json.JSONDecodeError as e:
  478. # 兜底: 试着把误写成 ASCII 的中文引号修成「」再 parse (模型直 Write 常见崩因)
  479. fixed, repaired = repair_ascii_quotes(raw)
  480. try:
  481. data = json.loads(fixed)
  482. except json.JSONDecodeError:
  483. print(f'wf-patch: {wf} 不是合法 JSON (自动修引号也救不回): {e}', file=sys.stderr)
  484. sys.exit(2)
  485. print(f'[wf-patch] ⚠️ 原文件 JSON 非法 ({e.msg} @ line {e.lineno}); 已自动把 '
  486. f'{repaired} 处误写的 ASCII 引号修成「」→ 解析成功, 修复将随本次写回落盘',
  487. file=sys.stderr)
  488. patches = load_patches(args)
  489. unsets = args.unset or []
  490. if not patches and not unsets and not args.resolve_passthrough:
  491. print('wf-patch: 没有 --set / --patch / --unset / --resolve-passthrough, 啥也没干', file=sys.stderr)
  492. sys.exit(2)
  493. # 解析 + 校验; 任何一条失败 -> 整批不写
  494. pending_types = set()
  495. for path, _ in patches:
  496. m = re.match(r'^p\d+\.type_registry\.([^.]+)\.(extends|desc)$', path)
  497. if m:
  498. pending_types.add(m.group(1))
  499. plan = [] # set: (parent, key, normalized_value, path, display)
  500. del_plan = [] # unset: (parent, key, path)
  501. skipped = [] # unset 跳过 (字段本就不在)
  502. errors = [] # (path, msg)
  503. for path, value in patches:
  504. try:
  505. parent, key, proc, field = locate(data, path)
  506. except PathError as e:
  507. errors.append((path, str(e)))
  508. continue
  509. ok, norm, msg = validate_field(field, value, proc, pending_types)
  510. if not ok:
  511. errors.append((path, msg))
  512. continue
  513. plan.append((parent, key, norm, path, norm if norm is not None else 'null'))
  514. for path in unsets:
  515. try:
  516. parent, key, _proc, _field = locate(data, path)
  517. except PathError as e:
  518. errors.append((path, str(e)))
  519. continue
  520. present = (isinstance(parent, dict) and key in parent) or \
  521. (isinstance(parent, list) and isinstance(key, int) and key < len(parent))
  522. (del_plan if present else skipped).append((parent, key, path) if present else path)
  523. if patches or unsets:
  524. print(f'[wf-patch] {wf.name} — set {len(plan)}/{len(patches)} 通过, '
  525. f'unset {len(del_plan)} 删/{len(skipped)} 跳过, {len(errors)} 失败')
  526. for _p, _k, _n, path, disp in plan:
  527. print(f' ✓ set {path} = {disp}')
  528. for _p, _k, path in del_plan:
  529. print(f' ✓ unset {path}')
  530. for path in skipped:
  531. print(f' · skip {path} (字段本就不存在)')
  532. for path, msg in errors:
  533. print(f' ✗ {path} — {msg}')
  534. if errors:
  535. print(f'\n有 {len(errors)} 条失败, 整批未写入 (修正后重跑).', file=sys.stderr)
  536. sys.exit(1)
  537. # 应用到内存 data (set 先 unset 后; resolve 要看到这些改动). 是否持久化由 dry-run 决定.
  538. for parent, key, norm, _, _ in plan:
  539. parent[key] = norm
  540. for parent, key, _path in sorted(del_plan, key=lambda d: -d[1] if isinstance(d[1], int) else 0):
  541. if isinstance(parent, list):
  542. parent.pop(key)
  543. else:
  544. del parent[key]
  545. # 透传回填
  546. filled, warns = [], []
  547. if args.resolve_passthrough:
  548. filled, warns = resolve_passthrough(data)
  549. print(f'[resolve-passthrough] 回填 {len(filled)} 处透传 value, {len(warns)} 处填不动')
  550. for m in filled:
  551. print(f' ✓ {m}')
  552. for w in warns:
  553. print(f' ⚠ {w}')
  554. n_changes = len(plan) + len(del_plan) + len(filled)
  555. if args.dry_run:
  556. extra = f' (+ 自动修复 {repaired} 处引号, dry-run 同样不写)' if repaired else ''
  557. print(f'\n--dry-run: 预演 {n_changes} 处改动{extra}, 未写入.')
  558. sys.exit(0)
  559. # repaired>0 时即便无字段改动也要落盘 (否则修好的引号没存下来, 文件还是坏的)
  560. if n_changes == 0 and not repaired:
  561. print('\n没有改动 (透传 value 都已填好 / 无可赋值), 未写文件.')
  562. sys.exit(0)
  563. # 落盘 (安全序列化, 你从不手写 JSON)
  564. wf.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
  565. tail = f' (含自动修复 {repaired} 处引号→「」)' if repaired else ''
  566. print(f'\n已写入 {n_changes} 处到 {wf.name}{tail}.')
  567. sys.exit(0)
  568. if __name__ == '__main__':
  569. main()