wf-patch.py 29 KB

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