wf-patch.py 41 KB

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