wf-patch.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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 (p1/s1), 下标 procedures[N].steps[M] 也接受; inputs/outputs 用 [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 sys
  56. from pathlib import Path
  57. # spec/tools/wf-patch.py -> procedure-dsl/
  58. DSL_ROOT = Path(__file__).resolve().parent.parent.parent
  59. TAX_DIR = DSL_ROOT / 'spec' / 'taxonomy'
  60. # Windows 控制台 UTF-8
  61. for _s in (sys.stdout, sys.stderr):
  62. if hasattr(_s, 'reconfigure'):
  63. try:
  64. _s.reconfigure(encoding='utf-8', errors='replace')
  65. except Exception:
  66. pass
  67. KIND_VOCAB = {'step', 'block', 'nested'}
  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. # ===========================================================================
  72. # 自动修引号: 模型直 Write workflow.json 时常把中文引号写成 ASCII " (未转义) → JSON 崩.
  73. # 仅在 json.loads 失败时兜底调用 (合法文件零开销). 判别: 串内一个 ASCII " 之后第一个
  74. # 非空白字符 ∈ {,:}]} 或 EOF → 真·字符串定界符 (保留); 否则是误写的内容引号 → 换直角
  75. # 引号「」(串内交替 开「/闭」). 逻辑独立内置于本文件 (不 import 任何外部模块);
  76. # scratch/repair_workflow_quotes.py 是同款独立实现, 二者无依赖关系. 改完必须能 parse 才用.
  77. # ===========================================================================
  78. _STRUCT_AFTER = set(',:}]')
  79. def repair_ascii_quotes(raw: str):
  80. """→ (修后文本, 改动的内容引号数). 纯走字符, 不依赖能否 parse."""
  81. out, i, n = [], 0, len(raw)
  82. in_str = esc = False
  83. open_q = True
  84. changes = 0
  85. while i < n:
  86. c = raw[i]
  87. if not in_str:
  88. out.append(c)
  89. if c == '"':
  90. in_str, esc, open_q = True, False, True
  91. i += 1
  92. continue
  93. if esc:
  94. out.append(c); esc = False; i += 1; continue
  95. if c == '\\':
  96. out.append(c); esc = True; i += 1; continue
  97. if c == '"':
  98. j = i + 1
  99. while j < n and raw[j] in ' \t\r\n':
  100. j += 1
  101. nxt = raw[j] if j < n else ''
  102. if nxt == '' or nxt in _STRUCT_AFTER:
  103. out.append(c); in_str = False # 真·结束符
  104. else:
  105. out.append('「' if open_q else '」') # 误写的内容引号
  106. open_q = not open_q
  107. changes += 1
  108. i += 1
  109. continue
  110. out.append(c); i += 1
  111. return ''.join(out), changes
  112. class PathError(Exception):
  113. """路径无法解析到 workflow.json 里的目标位置."""
  114. # ===========================================================================
  115. # 字典树加载: leaf 集 + {leaf: 全路径} + 全叶路径集 (与 lint 同款叶子派生)
  116. # ===========================================================================
  117. def _load_tree(name: str):
  118. """读 spec/taxonomy/{name}.json. 返回 (leaves:set, leaf2path:dict, control:list)."""
  119. f = TAX_DIR / f'{name}.json'
  120. if not f.exists():
  121. return set(), {}, []
  122. d = json.loads(f.read_text(encoding='utf-8'))
  123. leaf2path: dict[str, str] = {}
  124. def walk(node: dict, prefix: list[str]):
  125. nm = node.get('分类名称')
  126. if not nm:
  127. return
  128. p = prefix + [nm]
  129. kids = node.get('子分类') or []
  130. if not kids: # 无子分类 = 叶子
  131. leaf2path[nm] = '/'.join(p)
  132. for c in kids:
  133. walk(c, p)
  134. for top in d.get('最终分类树') or []:
  135. walk(top, [])
  136. leaves = set(d.get('$leaves') or leaf2path.keys())
  137. return leaves, leaf2path, (d.get('$control') or [])
  138. EFFECT_LEAVES, EFFECT_PATHS, _ = _load_tree('effect')
  139. ACTION_LEAVES, ACTION_PATHS, ACTION_CONTROL = _load_tree('action')
  140. TYPE_LEAVES, TYPE_PATHS, _ = _load_tree('type')
  141. def _closest(name: str, leaves) -> str:
  142. """给个最接近的叶子名做提示 (子串/前缀朴素匹配, 仅供报错文案)."""
  143. cands = [lf for lf in leaves if name and (name in lf or lf in name)]
  144. return (' 最接近: ' + '/'.join(cands[:3])) if cands else ''
  145. def _leaf_menu(field: str) -> str:
  146. """校验失败时把该词表的**完整合法叶子**摆出来, 让模型直接照抄、别瞎猜反复试。
  147. 三张词表都很小 (effect 9 / action 30 / type 50), 整列得起。比"去读文件"更直接:
  148. 模型不用多花一次 read_file, 报错里就有菜单。每个失败字段类型只在末尾打一次。
  149. """
  150. if field == 'effect':
  151. return ('合法 effect 叶子 (照抄其一): ' + ' / '.join(sorted(EFFECT_LEAVES))
  152. + ' [全文 spec/taxonomy/effect.json]')
  153. if field == 'action':
  154. byb: dict = {}
  155. for p in sorted(set(ACTION_PATHS.values())):
  156. byb.setdefault(p.split('/')[0], []).append(p)
  157. body = '; '.join(' | '.join(byb[b]) for b in sorted(byb))
  158. return ('合法 action 叶路径 (照抄其一, 全集): ' + body
  159. + ' [全文 spec/taxonomy/action.json]')
  160. if field in ('type', 'extends'):
  161. return ('合法 type 叶子 (extends 挂靠照抄其一): ' + ' / '.join(sorted(TYPE_LEAVES))
  162. + ' [全文 spec/taxonomy/type.json]')
  163. return ''
  164. # ===========================================================================
  165. # 字段校验 -> (ok, normalized_value, err_msg)
  166. # ===========================================================================
  167. def validate_field(field: str, value, proc: dict, pending_types: set[str] = None):
  168. # null 哨兵 (substance/form/url 可空)
  169. if value == '__null__':
  170. if field in ('substance', 'form', 'url'):
  171. return True, None, ''
  172. return False, value, f'__null__ 只对 substance/form/url 有意义, {field} 不可为 null'
  173. # focus 是数组: 逗号分隔 → list ('via,action,out-type-0'); 空串 → []
  174. if field == 'focus':
  175. items = [t.strip() for t in str(value).split(',') if t.strip()]
  176. return True, items, ''
  177. if field == 'effect':
  178. if value in EFFECT_LEAVES:
  179. return True, value, ''
  180. # 给了全路径 -> 归一到叶名 (schema 存叶名)
  181. for leaf, path in EFFECT_PATHS.items():
  182. if value == path:
  183. return True, leaf, ''
  184. # 容错: 路径里有某段是合法叶名 → 取最末的那个
  185. segs = [s.strip() for s in str(value).split('/') if s.strip()]
  186. for seg in reversed(segs):
  187. if seg in EFFECT_LEAVES:
  188. return True, seg, ''
  189. return False, value, f'effect={value!r} 不是 effect.json 叶子(存叶名).{_closest(segs[-1] if segs else str(value), EFFECT_LEAVES)}'
  190. if field == 'action':
  191. # action 存全路径; 给叶名自动展开, 给全叶路径原样接受
  192. if value in ACTION_PATHS: # 是叶名
  193. return True, ACTION_PATHS[value], ''
  194. if value in ACTION_PATHS.values(): # 是合法叶路径
  195. return True, value, ''
  196. # 容错: 路径里有某段是合法叶名(多写了段 / 前缀错, 如 生成/元素生成/文生图)→ 取最末的合法叶, 纠正到其全路径
  197. segs = [s.strip() for s in str(value).split('/') if s.strip()]
  198. for seg in reversed(segs):
  199. if seg in ACTION_PATHS:
  200. return True, ACTION_PATHS[seg], ''
  201. return False, value, (f'action={value!r} 不是合法动作叶子/叶路径 '
  202. f'(对到 action.json 的叶子, 如 元素生成、提取/化学提取/反推).{_closest(segs[-1] if segs else str(value), ACTION_LEAVES)}')
  203. if field == 'type':
  204. # type 是自由标签: Phase 1 随便起个描述性词即可, 不校验是否叶子/注册。
  205. # 「对到 type.json 标准叶子 / 注册 type_registry 挂靠」是 Phase 2 归类的活;
  206. # 最终是否合法由 lint-case (Check 1: 揪未注册的 case-specific type) + render schema 兜底。
  207. if isinstance(value, str) and value.strip():
  208. return True, value.strip(), ''
  209. return False, value, 'type 不能为空'
  210. if field == 'extends': # type_registry entry 的 extends 必须桥到 stdlib 叶子
  211. if value in TYPE_LEAVES:
  212. return True, value, ''
  213. return False, value, f'type_registry extends={value!r} 必须是 type.json 叶子.{_closest(value, TYPE_LEAVES)}'
  214. if field in ('substance', 'form'):
  215. # 自由提炼的元素点 — 不查词表、不校验 (spec/tools.md §1; phase2-normalize.md §4).
  216. # 字符串原样存 (如 "人物、卧室场景"), 数组逐项 strip 后存. 旧的 taxonomy-lookup 校验已废弃.
  217. if isinstance(value, str):
  218. return True, value.strip(), ''
  219. if isinstance(value, list):
  220. return True, [str(p).strip() for p in value if str(p).strip()], ''
  221. return False, value, f'{field} 必须是字符串或数组'
  222. if field == 'anchor':
  223. if re.match(r'^\s*(←|→)', str(value)):
  224. return True, value, ''
  225. return False, value, f'anchor={value!r} 须以 ← (输入引用) 或 → (输出去向) 开头'
  226. if field == 'kind':
  227. if value in KIND_VOCAB:
  228. return True, value, ''
  229. return False, value, f'kind={value!r} 不在 {sorted(KIND_VOCAB)}'
  230. # 自由文本字段 (name/value/intent/via/purpose/category/platform/author/desc/group...)
  231. return True, value, ''
  232. # ===========================================================================
  233. # 路径解析 -> (parent_container, key, proc, field_name)
  234. # ===========================================================================
  235. _SEG = re.compile(r'^([^\[]+)(?:\[(\d+)\])?$')
  236. def _split_seg(seg: str):
  237. m = _SEG.match(seg)
  238. if not m:
  239. raise PathError(f'非法路径段 {seg!r}')
  240. return m.group(1), (int(m.group(2)) if m.group(2) is not None else None)
  241. def _descend(container, segs, create=False):
  242. """沿 segs 走进 container, 返回 (parent, last_key). create=True 时自动建中间节点.
  243. segs 每段可带 [i] 下标. last_key 是 dict 键 (str) 或列表下标 (int);
  244. 设置即 parent[last_key]=value, 删除即 del parent[last_key].
  245. 用于 source.* / declarations.* 等通用路径 (proc/step 的 id 寻址不走这里).
  246. """
  247. cur = container
  248. for i, seg in enumerate(segs):
  249. name, idx = _split_seg(seg)
  250. last = (i == len(segs) - 1)
  251. if idx is None:
  252. if last:
  253. if not isinstance(cur, dict):
  254. raise PathError(f'{name!r} 的父级不是对象')
  255. return cur, name
  256. if not isinstance(cur, dict):
  257. raise PathError(f'路径段 {name!r} 的父级不是对象')
  258. if name not in cur:
  259. if not create:
  260. raise PathError(f'路径段 {name!r} 不存在, 无法下钻')
  261. cur[name] = {}
  262. cur = cur[name]
  263. else:
  264. if not isinstance(cur, dict):
  265. raise PathError(f'路径段 {name!r} 的父级不是对象')
  266. if name not in cur:
  267. if not create:
  268. raise PathError(f'路径段 {name!r} 不存在, 无法下钻')
  269. cur[name] = []
  270. lst = cur[name]
  271. if not isinstance(lst, list):
  272. raise PathError(f'{name} 不是列表')
  273. if idx >= len(lst):
  274. if not create:
  275. raise PathError(f'{name}[{idx}] 越界或非列表')
  276. while idx >= len(lst):
  277. lst.append({})
  278. if last:
  279. return lst, idx
  280. cur = lst[idx]
  281. raise PathError('路径为空')
  282. # ── --create 自动建结构用的骨架 ─────────────────────────────────────────────
  283. _STEP_SCALARS = {'effect', 'substance', 'form', 'via', 'action', 'directive', 'kind', 'intent', 'group'}
  284. def _new_procedure(pid: str) -> dict:
  285. return {
  286. 'id': pid, 'name': '', 'purpose': '', 'category': '', 'platform': '', 'author': '',
  287. 'declarations': {'inputs': [], 'resources': [], 'returns': {}},
  288. 'steps': [],
  289. }
  290. def _new_step(sid: str) -> dict:
  291. return {'id': sid, 'kind': 'step', 'via': '', 'inputs': [], 'outputs': []}
  292. def _new_io(is_output: bool, sid: str, idx: int) -> dict:
  293. if is_output:
  294. return {'id': f'{sid}o{idx + 1}', 'type': '', 'value': '', 'anchor': ''}
  295. return {'type': '', 'value': '', 'anchor': ''}
  296. def _split_step_path(remainder: str):
  297. """create 模式下 step 不存在、无法前缀匹配时, 从路径切出 (sid, fsegs).
  298. 规则: 出现 inputs[i]/outputs[i] 段 → 其前为 sid; 否则末段须是已知 step 标量字段, 其前为 sid.
  299. sid 可含点 (嵌套步 s2.1)。切不出返回 (None, None) — 不创建, 避免误建。
  300. """
  301. segs = remainder.split('.')
  302. for j, s in enumerate(segs):
  303. nm, _ = _split_seg(s)
  304. if nm in ('inputs', 'outputs'):
  305. return ('.'.join(segs[:j]) or None), segs[j:]
  306. if segs[-1] in _STEP_SCALARS:
  307. return ('.'.join(segs[:-1]) or None), [segs[-1]]
  308. return None, None
  309. def locate(data: dict, path: str, create: bool = False):
  310. """把 path 解析到目标. 返回 (parent, key, proc, field_name).
  311. 设置即 parent[key] = value. proc 给校验提供 type_registry 上下文.
  312. proc / step 主用 id 寻址 (p1/s1), 也接受下标 procedures[N]/steps[M]; inputs/outputs 用 [i] 下标.
  313. step id 可能带点 (嵌套步 s2.1) — 用最长前缀匹配消歧 (s2.1 优先于 s2).
  314. create=True (构建模式): 缺失的 procedure / step / IO 元素 / 中间结构自动创建, 新建打印到 stderr.
  315. """
  316. if '.' not in path:
  317. raise PathError(f'路径太短 {path!r}, 至少 <proc>.<字段> 或 source.<字段>')
  318. proc_id, remainder = path.split('.', 1)
  319. # --- source.* 分支 (case-level 原帖信息, 无 proc 上下文) ---
  320. if proc_id == 'source':
  321. src = data.setdefault('source', {})
  322. parent, key = _descend(src, remainder.split('.'), create=create)
  323. return parent, key, None, (key if isinstance(key, str) else '')
  324. procs = data.setdefault('procedures', [])
  325. # 接受两种 proc 寻址: id (p1) 或下标别名 procedures[N] (映射到第 N 个工序; 弱模型爱用这种)
  326. m_idx = re.match(r'^procedures\[(\d+)\]$', proc_id)
  327. if m_idx:
  328. idx = int(m_idx.group(1))
  329. if idx < len(procs):
  330. proc = procs[idx]
  331. elif create:
  332. proc = _new_procedure(f'p{idx + 1}')
  333. procs.append(proc)
  334. print(f'[wf-patch] + 新建 procedure p{idx + 1} (来自 procedures[{idx}])', file=sys.stderr)
  335. else:
  336. raise PathError(f'procedures[{idx}] 越界 (现有 {len(procs)} 个工序)')
  337. else:
  338. proc = next((p for p in procs if p.get('id') == proc_id), None)
  339. if proc is None:
  340. if not create:
  341. ids = [p.get('id') for p in procs]
  342. raise PathError(f'找不到 procedure id={proc_id!r} (现有: {ids})')
  343. proc = _new_procedure(proc_id)
  344. procs.append(proc)
  345. print(f'[wf-patch] + 新建 procedure {proc_id}', file=sys.stderr)
  346. # --- type_registry 分支 (允许自动建段/条目) ---
  347. if remainder == 'type_registry' or remainder.startswith('type_registry.'):
  348. parts = remainder.split('.')
  349. if len(parts) == 3:
  350. reg = proc.setdefault('type_registry', {})
  351. entry = reg.setdefault(parts[1], {})
  352. return entry, parts[2], proc, parts[2]
  353. raise PathError('type_registry 路径形如 p1.type_registry.<类型名>.<extends|desc>')
  354. # --- step 分支: 支持 id 寻址 (p1.s1.effect) 和下标寻址 (procedures[0].steps[0].effect) ---
  355. matched, field_part = None, None
  356. m_step = re.match(r'^steps\[(\d+)\]\.(.+)$', remainder) # 下标寻址 steps[N].<字段>
  357. if m_step:
  358. sidx = int(m_step.group(1))
  359. steps = proc.setdefault('steps', [])
  360. if sidx < len(steps):
  361. matched = steps[sidx]
  362. elif create:
  363. matched = _new_step(f's{sidx + 1}')
  364. steps.append(matched)
  365. print(f'[wf-patch] + 新建 step (procedures.steps[{sidx}] → id s{sidx + 1})', file=sys.stderr)
  366. else:
  367. raise PathError(f'steps[{sidx}] 越界 (该工序现有 {len(steps)} 步)')
  368. field_part = m_step.group(2)
  369. else: # id 寻址: 最长前缀匹配现有 step id
  370. for s in (proc.get('steps') or []):
  371. sid = s.get('id')
  372. if not sid:
  373. continue
  374. if remainder == sid:
  375. raise PathError(f'step 路径要带字段, 形如 {proc_id}.{sid}.effect')
  376. if remainder.startswith(sid + '.') and (matched is None or len(sid) > len(matched['id'])):
  377. matched = s
  378. if matched is None and create:
  379. sid_new, _ = _split_step_path(remainder)
  380. if sid_new:
  381. matched = _new_step(sid_new)
  382. proc.setdefault('steps', []).append(matched)
  383. print(f'[wf-patch] + 新建 step {proc_id}.{sid_new}', file=sys.stderr)
  384. if matched is not None:
  385. field_part = remainder[len(matched['id']) + 1:] # 'sid.' 之后
  386. if matched is not None:
  387. sid = matched.get('id', '?')
  388. fsegs = field_part.split('.')
  389. name2, idx2 = _split_seg(fsegs[0])
  390. if name2 in ('inputs', 'outputs'):
  391. if idx2 is None:
  392. raise PathError(f'{name2} 要带下标, 形如 {name2}[0]')
  393. lst = matched.get(name2)
  394. if not isinstance(lst, list):
  395. if create:
  396. matched[name2] = lst = []
  397. else:
  398. raise PathError(f'{proc_id}.{sid}.{name2}[{idx2}] 越界 (该 step 有 0 个 {name2})')
  399. if idx2 >= len(lst):
  400. if not create:
  401. raise PathError(f'{proc_id}.{sid}.{name2}[{idx2}] 越界 (该 step 有 {len(lst)} 个 {name2})')
  402. while idx2 >= len(lst):
  403. lst.append(_new_io(name2 == 'outputs', sid, len(lst)))
  404. if len(fsegs) != 2:
  405. raise PathError(f'IO 路径形如 {proc_id}.{sid}.{name2}[{idx2}].anchor')
  406. return lst[idx2], fsegs[1], proc, fsegs[1]
  407. else:
  408. if len(fsegs) != 1:
  409. raise PathError(f'step 标量字段形如 {proc_id}.{sid}.{name2}')
  410. return matched, name2, proc, name2
  411. # --- proc 内其余路径: 头部字段 / declarations.* / return_row.* 等, 走通用下钻 ---
  412. parent, key = _descend(proc, remainder.split('.'), create=create)
  413. return parent, key, proc, (key if isinstance(key, str) else '')
  414. # ===========================================================================
  415. # 透传回填: anchor 为纯 ← sN.varname 的 IO, 从源 output 抄 value (逐字回填)
  416. # ===========================================================================
  417. def _is_fillable(value) -> bool:
  418. """该 value 算「还没真正回填」吗 — 空 / 占位符 / 引用文案."""
  419. if value in (None, '', '-'):
  420. return True
  421. return bool(META_REF.search(str(value)))
  422. def _passthrough_id(anchor):
  423. """anchor 为 `← <output-id>` (可带 [i] 容器索引) → 返回 output id; 否则 None.
  424. `← 工序输入` / `← s6 (链)` 等非纯 id 引用返回 None (无法确定唯一源 value).
  425. """
  426. m = re.match(r'^\s*←\s*([^\s\[((]+)', str(anchor or ''))
  427. if not m:
  428. return None
  429. return m.group(1) or None
  430. def resolve_passthrough(data: dict):
  431. """把 anchor 为纯透传 (← <output-id>)、value 仍空或占位的 input, 用源 output 的 value 逐字填上.
  432. 迭代到不动点 (处理链式透传). 返回 (filled_msgs, warn_msgs).
  433. """
  434. out_index = {} # output id -> output item (读 value)
  435. for p in data.get('procedures') or []:
  436. for s in p.get('steps') or []:
  437. for o in s.get('outputs') or []:
  438. if isinstance(o, dict) and o.get('id'):
  439. out_index[o['id']] = o
  440. def _src_value(rid):
  441. src = out_index.get(rid)
  442. if src is None or _is_fillable(src.get('value')):
  443. return None
  444. return src['value']
  445. filled: list[str] = []
  446. changed, rounds = True, 0
  447. while changed and rounds < 20:
  448. changed, rounds = False, rounds + 1
  449. for p in data.get('procedures') or []:
  450. for s in p.get('steps') or []:
  451. for idx, io in enumerate(s.get('inputs') or []):
  452. if not isinstance(io, dict) or not _is_fillable(io.get('value')):
  453. continue
  454. rid = _passthrough_id(io.get('anchor'))
  455. val = _src_value(rid) if rid else None
  456. if val is None:
  457. continue
  458. io['value'] = val
  459. filled.append(
  460. f"{p.get('id')}.{s.get('id')}.inputs[{idx}].value "
  461. f"← 复制自 {rid} ({len(str(val))} 字)"
  462. )
  463. changed = True
  464. # 仍填不动的透传 (源 id 找不到) → warn
  465. warns: list[str] = []
  466. for p in data.get('procedures') or []:
  467. for s in p.get('steps') or []:
  468. for idx, io in enumerate(s.get('inputs') or []):
  469. if not isinstance(io, dict) or not _is_fillable(io.get('value')):
  470. continue
  471. rid = _passthrough_id(io.get('anchor'))
  472. if rid and out_index.get(rid) is None:
  473. warns.append(
  474. f"{p.get('id')}.{s.get('id')}.inputs[{idx}] anchor 指向 "
  475. f"{rid} 但找不到该 output id (检查 anchor / output id)"
  476. )
  477. return filled, warns
  478. # ===========================================================================
  479. # 应用
  480. # ===========================================================================
  481. def load_patches(args) -> list[tuple[str, str]]:
  482. """汇总 --set、--patch 与 --set-file 成 [(path, value), ...]."""
  483. def _norm(v):
  484. if isinstance(v, str):
  485. # 将中文全角双角/单引号自动归一化为标准半角引号,更利于 AI 生图引擎和 Prompt 语法识别
  486. v = v.replace('“', '"').replace('”', '"').replace('‘', "'").replace('’', "'")
  487. return v
  488. def _dq(x: str) -> str:
  489. # 剥掉成对外层引号. cmd.exe 不剥单引号 → agent 写的 --set 'p.f=v' / p.f='v'
  490. # 会把单引号原样传进来, 导致 path 变成 'p1 这种 (找不到 procedure). 这里兜底剥掉.
  491. x = x.strip()
  492. if len(x) >= 2 and x[0] == x[-1] and x[0] in ('"', "'"):
  493. x = x[1:-1].strip()
  494. return x
  495. out: list[tuple[str, str]] = []
  496. for s in args.set or []:
  497. s = _dq(s) # 整体外层引号 (cmd 没剥的 'path=value')
  498. if '=' not in s:
  499. raise SystemExit(f'wf-patch: --set 缺 "=" : {s!r} (形如 path=value)')
  500. path, value = s.split('=', 1) # 只切第一个 '='
  501. out.append((_dq(path), _norm(_dq(value))))
  502. # 🟢 新增:从外部文件读取值注入
  503. for sf in getattr(args, 'set_file', None) or []:
  504. if '=' not in sf:
  505. raise SystemExit(f'wf-patch: --set-file 缺 "=" : {sf!r} (形如 path=file_path)')
  506. path, fpath_str = sf.split('=', 1)
  507. fpath = Path(fpath_str.strip())
  508. if not fpath.exists():
  509. raise SystemExit(f'wf-patch: --set-file 指定的文件不存在: {fpath_str}')
  510. try:
  511. value = fpath.read_text(encoding='utf-8')
  512. except Exception as e:
  513. raise SystemExit(f'wf-patch: 无法读取 --set-file 指定的文件 {fpath_str}: {e}')
  514. out.append((path.strip(), _norm(value)))
  515. if args.patch:
  516. if not args.patch.exists():
  517. raise SystemExit(
  518. f'wf-patch: --patch 文件不存在 {args.patch}\n'
  519. f' → --patch 的清单文件是**你要先写的输入**(扁平 `[{{"path":..,"value":..}}]` JSON)。\n'
  520. f' 先 write_file 写出它, 再 `--patch` 跑它;\n'
  521. f' 或字段不多时直接内联: `--set \'p1.s1.inputs[0].type=参考图\' --set ...`(不用文件)。')
  522. try:
  523. items = json.loads(args.patch.read_text(encoding='utf-8'))
  524. except json.JSONDecodeError as e:
  525. raise SystemExit(f'wf-patch: --patch 不是合法 JSON: {e}')
  526. for it in items:
  527. out.append((it['path'], _norm(it['value'])))
  528. return out
  529. # ===========================================================================
  530. # @quote 标记回填: value/directive 写 `@quote|起锚|止锚` 或 `@quote|关键词`,
  531. # 由 --resolve-quotes 顺标记从原文/配图 OCR 匹配真实内容, 批量替换 (空白无关匹配)
  532. # ===========================================================================
  533. def _q_source_text(path: Path) -> str:
  534. d = json.loads(path.read_text(encoding='utf-8'))
  535. if not isinstance(d, dict):
  536. return str(d)
  537. return '\n'.join(str(d.get(k, '')) for k in ('title', 'body_text') if d.get(k))
  538. def _q_norm(text: str):
  539. chars, idx = [], []
  540. for i, ch in enumerate(text):
  541. if ch.isspace():
  542. continue
  543. chars.append(ch)
  544. idx.append(i)
  545. return ''.join(chars), idx
  546. def _q_range_between(text: str, frm: str, to: str):
  547. ns, idx = _q_norm(text)
  548. nf, _ = _q_norm(frm)
  549. nt, _ = _q_norm(to)
  550. if not nf or not nt:
  551. return None
  552. p = ns.find(nf)
  553. if p < 0:
  554. return None
  555. q = ns.find(nt, p + len(nf))
  556. if q < 0:
  557. return None
  558. return text[idx[p]: idx[q + len(nt) - 1] + 1]
  559. def _q_braces(text: str, lo: int, hi: int):
  560. depth, op, i = 0, None, lo
  561. while i >= 0:
  562. if text[i] == '}':
  563. depth += 1
  564. elif text[i] == '{':
  565. if depth == 0:
  566. op = i
  567. break
  568. depth -= 1
  569. i -= 1
  570. if op is None:
  571. return None
  572. depth, j = 0, op
  573. while j < len(text):
  574. if text[j] == '{':
  575. depth += 1
  576. elif text[j] == '}':
  577. depth -= 1
  578. if depth == 0:
  579. return (op, j) if j >= hi else None
  580. j += 1
  581. return None
  582. def _q_query_block(text: str, query: str):
  583. ns, idx = _q_norm(text)
  584. nq, _ = _q_norm(query)
  585. if not nq:
  586. return None
  587. p = ns.find(nq)
  588. if p < 0:
  589. return None
  590. o_lo, o_hi = idx[p], idx[p + len(nq) - 1]
  591. br = _q_braces(text, o_lo, o_hi) # 命中落在 {...} 内 → 返回整块
  592. if br:
  593. return text[br[0]: br[1] + 1]
  594. lo = text.rfind('\n', 0, o_lo) + 1 # 否则返回所在行/段
  595. hi = text.find('\n', o_hi)
  596. return text[lo: (hi if hi >= 0 else len(text))].strip()
  597. def resolve_quotes(data: dict, corpora: list):
  598. """扫 value/directive 里的 `@quote|...` 标记, 顺标记从 corpora 匹配真实内容批量替换.
  599. 标记: `@quote|起锚|止锚` (范围, 推荐长段) 或 `@quote|关键词` (命中落 JSON 块返回整块, 否则所在行/段).
  600. corpora: [(label, text), ...] 依次尝试 (原文优先, 再 OCR). 返回 (filled, warns).
  601. """
  602. filled, warns = [], []
  603. def _resolve(v: str):
  604. parts = v[len('@quote|'):].split('|')
  605. for label, text in corpora:
  606. r = _q_range_between(text, parts[0], parts[1]) if len(parts) >= 2 else _q_query_block(text, parts[0])
  607. if r:
  608. return r, label
  609. return None, None
  610. for p in data.get('procedures') or []:
  611. pid = p.get('id')
  612. for s in p.get('steps') or []:
  613. sid = s.get('id')
  614. d = s.get('directive')
  615. if isinstance(d, str) and d.startswith('@quote|'):
  616. r, label = _resolve(d)
  617. if r:
  618. s['directive'] = r
  619. filled.append(f'{pid}.{sid}.directive ← [{label}] {len(r)} 字')
  620. else:
  621. warns.append(f'{pid}.{sid}.directive: @quote 未匹配 {d[:40]!r}')
  622. for kind in ('inputs', 'outputs'):
  623. for k, item in enumerate(s.get(kind) or []):
  624. if not isinstance(item, dict):
  625. continue
  626. v = item.get('value')
  627. if isinstance(v, str) and v.startswith('@quote|'):
  628. r, label = _resolve(v)
  629. if r:
  630. item['value'] = r
  631. filled.append(f'{pid}.{sid}.{kind}[{k}].value ← [{label}] {len(r)} 字')
  632. else:
  633. warns.append(f'{pid}.{sid}.{kind}[{k}].value: @quote 未匹配 {v[:40]!r}')
  634. return filled, warns
  635. def main() -> None:
  636. ap = argparse.ArgumentParser(
  637. prog='wf-patch.py',
  638. description='workflow.json 安全批量字段设置器 (写入即校验, 任何一条非法整批不写)',
  639. )
  640. ap.add_argument('--workflow', type=Path, required=True, help='目标 workflow.json')
  641. ap.add_argument('--set', action='append', metavar='PATH=VALUE',
  642. help='单条赋值, 可重复. 只在第一个 = 处切; value 可含 = 和空格 (记得整体加引号)')
  643. ap.add_argument('--patch', type=Path, default=None,
  644. help='批量赋值清单 .json: [{"path":..,"value":..}, ...]')
  645. ap.add_argument('--set-file', action='append', metavar='PATH=FILE_PATH', default=None,
  646. help='从外部文件读取内容注入指定字段. e.g. p1.s1.outputs[0].value=_scratch/prompt.txt')
  647. ap.add_argument('--unset', action='append', metavar='PATH', default=None,
  648. help='删字段, 可重复. e.g. p1.declarations.inputs[0].inferred (字段不存在则跳过). 取代手 Edit 删字段')
  649. ap.add_argument('--resolve-passthrough', action='store_true',
  650. help='把 anchor 为纯透传 (← sN.varname)、value 仍空/占位的 IO, 顺 anchor 从源 output 逐字抄 value. 可单独跑, 也可跟在 --set/--patch 后 (先赋值再解析). 迭代处理链式透传')
  651. ap.add_argument('--dry-run', action='store_true', help='只校验/预演, 不写')
  652. ap.add_argument('--create', action='store_true',
  653. help='(已默认开启, 保留兼容) 缺失的 procedure / step / IO 元素自动创建、文件不存在从空建')
  654. ap.add_argument('--no-create', action='store_true',
  655. help='关闭自动建: 路径不存在就报错 (严格防 typo; 仅在「纯填充已存在结构、想抓打错的路径」时用)')
  656. ap.add_argument('--resolve-quotes', action='store_true',
  657. help='把 value/directive 里的 @quote|起锚|止锚 (或 @quote|关键词) 标记, 顺标记从 --source 原文 / --ocr 配图文本匹配真实内容批量替换. 跟 anchor patch 一起跑')
  658. ap.add_argument('--source', type=Path, default=None, help='--resolve-quotes 的原文 case json (匹配语料)')
  659. ap.add_argument('--ocr', type=Path, default=None, help='--resolve-quotes 的配图 OCR 文本文件 (第二语料)')
  660. args = ap.parse_args()
  661. # 默认 upsert (缺路径自动建); 弱模型增量 patch 总需要它, gated 反而一直撞「越界/不存在」死循环。
  662. # --no-create 才关闭 (回到严格寻址、防 typo)。--create 保留为 no-op 兼容旧命令/文档。
  663. args.create = not args.no_create
  664. wf = args.workflow
  665. repaired = 0
  666. if args.create and not wf.exists():
  667. data = {}
  668. print(f'[wf-patch] + 新建 workflow 文件 {wf.name} (从空开始构建)', file=sys.stderr)
  669. elif not wf.exists():
  670. print(f'wf-patch: 文件不存在 {wf} (默认会从空新建; 你传了 --no-create 才不建)', file=sys.stderr)
  671. sys.exit(2)
  672. else:
  673. raw = wf.read_text(encoding='utf-8')
  674. try:
  675. data = json.loads(raw)
  676. except json.JSONDecodeError as e:
  677. # 兜底: 试着把误写成 ASCII 的中文引号修成「」再 parse (模型直 Write 常见崩因)
  678. fixed, repaired = repair_ascii_quotes(raw)
  679. try:
  680. data = json.loads(fixed)
  681. except json.JSONDecodeError:
  682. print(f'wf-patch: {wf} 不是合法 JSON, 无法处理: {e}\n'
  683. f' → 去 workflow.json 第 {e.lineno} 行附近修语法 '
  684. f'(最常见: 数组 ] 或 对象 }} 结束后、下一个 "key" 前缺逗号), 修好再重跑。'
  685. f'别盲目重试本命令 (JSON 没修, 每次都同样报错)。', file=sys.stderr)
  686. sys.exit(2)
  687. print(f'[wf-patch] ⚠️ 原文件 JSON 非法 ({e.msg} @ line {e.lineno}); 已自动把 '
  688. f'{repaired} 处误写的 ASCII 引号修成「」→ 解析成功, 修复将随本次写回落盘',
  689. file=sys.stderr)
  690. patches = load_patches(args)
  691. unsets = args.unset or []
  692. if not patches and not unsets and not args.resolve_passthrough and not args.resolve_quotes:
  693. print('wf-patch: 没有 --set / --patch / --unset / --resolve-passthrough / --resolve-quotes, 啥也没干', file=sys.stderr)
  694. sys.exit(2)
  695. # 解析 + 校验; 任何一条失败 -> 整批不写
  696. pending_types = set()
  697. for path, _ in patches:
  698. m = re.match(r'^p\d+\.type_registry\.([^.]+)\.(extends|desc)$', path)
  699. if m:
  700. pending_types.add(m.group(1))
  701. plan = [] # set: (parent, key, normalized_value, path, display)
  702. del_plan = [] # unset: (parent, key, path)
  703. skipped = [] # unset 跳过 (字段本就不在)
  704. # 错误分两类, 决定原子 vs 部分应用:
  705. # fatal = 路径/结构错 (locate 失败: 路径对不上、缺 --create 等) → 整批不写, 保护结构
  706. # value = 字段值校验失败 (effect/action/type 等值非法) → **跳过这条、其余照写** (部分应用),
  707. # 末尾以 exit 1 提示回去补。这样一批里几个值错不再连累其余正确字段一起丢。
  708. fatal_errors = [] # (path, msg)
  709. value_errors = [] # (path, msg)
  710. for path, value in patches:
  711. try:
  712. parent, key, proc, field = locate(data, path, create=args.create)
  713. except PathError as e:
  714. fatal_errors.append((path, str(e)))
  715. continue
  716. ok, norm, msg = validate_field(field, value, proc, pending_types)
  717. if not ok:
  718. value_errors.append((path, field, msg))
  719. continue
  720. plan.append((parent, key, norm, path, norm if norm is not None else 'null'))
  721. for path in unsets:
  722. try:
  723. parent, key, _proc, _field = locate(data, path)
  724. except PathError as e:
  725. fatal_errors.append((path, str(e)))
  726. continue
  727. present = (isinstance(parent, dict) and key in parent) or \
  728. (isinstance(parent, list) and isinstance(key, int) and key < len(parent))
  729. (del_plan if present else skipped).append((parent, key, path) if present else path)
  730. if patches or unsets:
  731. n_fail = len(fatal_errors) + len(value_errors)
  732. print(f'[wf-patch] {wf.name} — set {len(plan)}/{len(patches)} 通过, '
  733. f'unset {len(del_plan)} 删/{len(skipped)} 跳过, {n_fail} 失败')
  734. for _p, _k, _n, path, disp in plan:
  735. print(f' ✓ set {path} = {disp}')
  736. for _p, _k, path in del_plan:
  737. print(f' ✓ unset {path}')
  738. for path in skipped:
  739. print(f' · skip {path} (字段本就不存在)')
  740. for path, _field, msg in value_errors:
  741. print(f' ✗ {path} — {msg}')
  742. for path, msg in fatal_errors:
  743. print(f' ✗✗ {path} — {msg} [路径/结构错]')
  744. # 结构错 = patch 清单跟文件对不上 → 整批不写 (原子, 别半建坏骨架)
  745. if fatal_errors:
  746. print(f'\n有 {len(fatal_errors)} 条路径/结构错误, 整批未写入 (先修: 路径写对 / 该建的加 --create).',
  747. file=sys.stderr)
  748. sys.exit(1)
  749. # 只有字段值非法 → 跳过这几条、其余照常写, 进度不丢; 末尾 exit 1 提示去补
  750. if value_errors:
  751. # 把出错字段类型的**完整合法清单**打出来 (每类一次), 模型直接照抄、别再瞎猜反复试
  752. shown = []
  753. for _p, f, _m in value_errors:
  754. key = 'type' if f == 'extends' else f
  755. if key in ('effect', 'action', 'type') and key not in shown:
  756. shown.append(key)
  757. for key in shown:
  758. print(f' ↳ {_leaf_menu(key)}', file=sys.stderr)
  759. print(f'\n{len(value_errors)} 处字段值非法**已跳过未写**, 其余 {len(plan)} 处照常应用; '
  760. f'照上面清单选合法叶子, 修正这几条后重跑补上 (进度不丢, 别整批重来).', file=sys.stderr)
  761. # 应用到内存 data (set 先 unset 后; resolve 要看到这些改动). 是否持久化由 dry-run 决定.
  762. for parent, key, norm, _, _ in plan:
  763. parent[key] = norm
  764. for parent, key, _path in sorted(del_plan, key=lambda d: -d[1] if isinstance(d[1], int) else 0):
  765. if isinstance(parent, list):
  766. parent.pop(key)
  767. else:
  768. del parent[key]
  769. # 透传回填
  770. filled, warns = [], []
  771. if args.resolve_passthrough:
  772. filled, warns = resolve_passthrough(data)
  773. print(f'[resolve-passthrough] 回填 {len(filled)} 处透传 value, {len(warns)} 处填不动')
  774. for m in filled:
  775. print(f' ✓ {m}')
  776. for w in warns:
  777. print(f' ⚠ {w}')
  778. # @quote 标记回填 (顺 @quote|起锚|止锚 从原文/OCR 匹配真实内容批量替换)
  779. quoted, qwarns = [], []
  780. if args.resolve_quotes:
  781. corpora = []
  782. if args.source and args.source.exists():
  783. corpora.append(('原文', _q_source_text(args.source)))
  784. if args.ocr and args.ocr.exists():
  785. corpora.append(('配图OCR', args.ocr.read_text(encoding='utf-8')))
  786. if not corpora:
  787. print('wf-patch: --resolve-quotes 需要 --source (或 --ocr) 指向匹配语料', file=sys.stderr)
  788. else:
  789. quoted, qwarns = resolve_quotes(data, corpora)
  790. print(f'[resolve-quotes] 回填 {len(quoted)} 处 @quote 标记, {len(qwarns)} 处未匹配')
  791. for m in quoted:
  792. print(f' ✓ {m}')
  793. for w in qwarns:
  794. print(f' ⚠ {w}')
  795. # 有字段值非法被跳过 → 退出码 1 (告诉 agent 还有几条要补), 但有效改动已照常落盘
  796. final_exit = 1 if value_errors else 0
  797. n_changes = len(plan) + len(del_plan) + len(filled) + len(quoted)
  798. if args.dry_run:
  799. extra = f' (+ 自动修复 {repaired} 处引号, dry-run 同样不写)' if repaired else ''
  800. print(f'\n--dry-run: 预演 {n_changes} 处改动{extra}, 未写入.')
  801. sys.exit(final_exit)
  802. # repaired>0 时即便无字段改动也要落盘 (否则修好的引号没存下来, 文件还是坏的)
  803. if n_changes == 0 and not repaired:
  804. print('\n没有改动 (透传 value 都已填好 / 无可赋值), 未写文件.')
  805. sys.exit(final_exit)
  806. # 落盘 (安全序列化, 你从不手写 JSON)
  807. wf.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
  808. tail = f' (含自动修复 {repaired} 处引号→「」)' if repaired else ''
  809. print(f'\n已写入 {n_changes} 处到 {wf.name}{tail}.')
  810. sys.exit(final_exit)
  811. if __name__ == '__main__':
  812. main()