argo-search 2.13.0 → 2.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/AGENTS.md +93 -0
  2. package/README.es.md +30 -8
  3. package/README.ja.md +30 -8
  4. package/README.ko.md +30 -8
  5. package/README.md +511 -596
  6. package/README.zh.md +975 -0
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/backends/domain_profiles.json +90 -6
  10. package/backends/engine_registry.yaml +222 -32
  11. package/backends/env_passthrough.txt +2 -0
  12. package/backends/quota_profiles.json +151 -11
  13. package/bin/argo +3 -0
  14. package/config.yaml +50 -4
  15. package/docs/CHANGELOG.md +45 -0
  16. package/docs/COMMIT_STANDARD.md +98 -0
  17. package/docs/ENGINE_CATALOG.md +100 -81
  18. package/docs/MCP_SETUP.md +1 -1
  19. package/docs/RELEASE_NOTES_v2.14.0.md +88 -0
  20. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  21. package/docs/RELEASING.md +52 -0
  22. package/engines/specs/artic.yaml +11 -1
  23. package/engines/specs/cleveland.yaml +15 -1
  24. package/engines/specs/clinicaltrials.yaml +24 -1
  25. package/engines/specs/cnii.yaml +17 -1
  26. package/engines/specs/coingecko.yaml +10 -2
  27. package/engines/specs/dbpedia.yaml +32 -0
  28. package/engines/specs/deezer.yaml +12 -1
  29. package/engines/specs/doaj.yaml +14 -1
  30. package/engines/specs/endoflife.yaml +16 -1
  31. package/engines/specs/eu_opendata.yaml +11 -1
  32. package/engines/specs/europeana.yaml +19 -1
  33. package/engines/specs/feed.yaml +62 -0
  34. package/engines/specs/figshare.yaml +12 -1
  35. package/engines/specs/fourget.yaml +23 -0
  36. package/engines/specs/grep_app.yaml +19 -0
  37. package/engines/specs/hackernews.yaml +17 -1
  38. package/engines/specs/hal.yaml +19 -1
  39. package/engines/specs/hf_datasets.yaml +59 -0
  40. package/engines/specs/hf_papers.yaml +42 -0
  41. package/engines/specs/jikan.yaml +12 -10
  42. package/engines/specs/kaggle.yaml +46 -0
  43. package/engines/specs/local_baidu.yaml +5 -0
  44. package/engines/specs/local_seek.yaml +34 -0
  45. package/engines/specs/local_yandex.yaml +37 -0
  46. package/engines/specs/maven.yaml +61 -0
  47. package/engines/specs/mojeek.yaml +31 -0
  48. package/engines/specs/mwmbl.yaml +39 -0
  49. package/engines/specs/nasa_cmr.yaml +12 -1
  50. package/engines/specs/nuget.yaml +57 -0
  51. package/engines/specs/openaire.yaml +34 -0
  52. package/engines/specs/repology.yaml +18 -0
  53. package/engines/specs/tatoeba.yaml +14 -1
  54. package/engines/specs/tvmaze.yaml +5 -1
  55. package/engines/specs/usda.yaml +14 -1
  56. package/package.json +14 -10
  57. package/packages/dsh-plugin/dsh/client.js +1 -0
  58. package/packages/dsh-plugin/dsh/native-tools.mjs +85 -116
  59. package/packages/dsh-plugin/dsh/runner.js +35 -1
  60. package/packages/dsh-plugin/dsh/specs.js +3 -1
  61. package/packages/dsh-plugin/dsh/wide-research.js +5 -3
  62. package/packages/dsh-plugin/package.json +1 -1
  63. package/packages/dsh-plugin/test/client.test.js +6 -0
  64. package/packages/dsh-plugin/test/config.test.js +5 -1
  65. package/packages/dsh-plugin/test/index.test.js +3 -1
  66. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  67. package/scripts/badcase_causes.py +81 -0
  68. package/scripts/badcase_ledger.py +336 -19
  69. package/scripts/build_release_assets.sh +43 -15
  70. package/scripts/cache.py +3 -3
  71. package/scripts/check_commit_report.py +168 -0
  72. package/scripts/dormant_ledger.py +225 -0
  73. package/scripts/engine_admission.py +9 -5
  74. package/scripts/engine_families.py +13 -2
  75. package/scripts/engine_policy.py +1 -1
  76. package/scripts/engine_states.py +398 -8
  77. package/scripts/engine_status.py +31 -0
  78. package/scripts/engine_validate.py +224 -40
  79. package/scripts/engines.py +4 -34
  80. package/scripts/engines_base.py +53 -147
  81. package/scripts/engines_builders.py +2 -33
  82. package/scripts/engines_builders_batch12.py +168 -0
  83. package/scripts/engines_builders_batch16.py +13 -0
  84. package/scripts/engines_builders_batch9.py +0 -204
  85. package/scripts/engines_builders_feeds.py +148 -30
  86. package/scripts/engines_builders_intl.py +0 -328
  87. package/scripts/engines_builders_science.py +0 -85
  88. package/scripts/engines_builders_tech.py +0 -98
  89. package/scripts/engines_parsers.py +924 -0
  90. package/scripts/evidence_loop.py +91 -4
  91. package/scripts/fetch_browser.py +4 -2
  92. package/scripts/fetch_jsrun.py +2 -1
  93. package/scripts/fetch_v3.py +22 -22
  94. package/scripts/gen_engine_catalog.py +2 -2
  95. package/scripts/gen_native_tools.py +46 -18
  96. package/scripts/local_intent.py +175 -0
  97. package/scripts/local_seek.py +256 -91
  98. package/scripts/local_seek_adapter.py +87 -0
  99. package/scripts/mcp_handlers.py +124 -72
  100. package/scripts/mcp_server.py +1 -1
  101. package/scripts/mcp_tools.py +143 -61
  102. package/scripts/mcp_transport.py +42 -10
  103. package/scripts/pre-commit +68 -1
  104. package/scripts/recovery.py +14 -5
  105. package/scripts/recovery_l0.py +5 -3
  106. package/scripts/release.py +20 -11
  107. package/scripts/release_check.py +1 -1
  108. package/scripts/research.py +1 -1
  109. package/scripts/research_gates.py +3 -3
  110. package/scripts/route_lang.py +6 -1
  111. package/scripts/route_policy.py +26 -14
  112. package/scripts/search.py +33 -25
  113. package/scripts/search_cli.py +52 -6
  114. package/scripts/search_output.py +83 -16
  115. package/scripts/secret_guard.py +106 -0
  116. package/scripts/semantic_evidence.py +230 -15
  117. package/scripts/settings_page.py +80 -8
  118. package/scripts/source_audit.py +408 -0
  119. package/scripts/sync_backends.py +38 -1
  120. package/scripts/wechat_article.py +5 -3
  121. package/scripts/wide_research.py +4 -1
  122. package/scripts/x_article_fetch.py +2 -1
  123. package/sub-skills/local-search/parsers.py +6 -1
  124. package/sub-skills/local-seek/scripts/seek.py +390 -24
  125. package/sub-skills/local-seek/scripts/seek_fts.py +28 -9
  126. package/sub-skills/local-seek/scripts/seek_rank.py +64 -1
  127. package/README.en.md +0 -814
  128. package/engines/specs/cinii.yaml +0 -44
  129. package/scripts/image_vision/vision_probe +0 -0
@@ -0,0 +1,924 @@
1
+ #!/usr/bin/env python3
2
+ """engines_parsers.py — 响应解析器注册表(L2 解耦基础)。
3
+
4
+ ## 为什么需要
5
+
6
+ 当前自定义 type 的 164 个源里,L1(标准 HTTP 协议变体)约 90 个,
7
+ L2(协议标准但响应结构需特殊解析)约 50 个,L3(真自定义)约 27 个。
8
+
9
+ L2 的问题是:每个源在 `engines_base.py` 里写一个 `_parse_xxx` 函数,
10
+ 注册进 `_CUSTOM_JSON_PARSERS` 字典。这个字典**按引擎名索引**,导致:
11
+ - 同一套解析逻辑(如「数组在第二个元素」「单对象根」)被复制多份;
12
+ - 新增一个 L2 源要改 engines_base.py(1567 行的大文件);
13
+ - 解析器无法被第三方插件复用(插件只能贡献 builder,不能贡献解析器)。
14
+
15
+ 本模块把解析器从「按引擎名索引」改为「按解析能力注册」:
16
+ - 解析器是纯函数:`parse(data: Any, spec: dict) -> list[dict]`
17
+ - spec 用 `response.parser: <name>` 引用,而不是靠引擎名隐式匹配
18
+ - 解析器可以组合:`response.parser: [worldbank, strip_fields]`
19
+
20
+ ## 与 engines_base.py 的分工
21
+
22
+ - engines_base.py:通用 HTTP/RSS/CLI 引擎的构建 + output_map 解析(覆盖 L1)
23
+ - engines_parsers.py:注册解析器(覆盖 L2)
24
+ - engines_builders_*.py:真自定义 builder(覆盖 L3)
25
+
26
+ ## 解析器契约
27
+
28
+ ```python
29
+ def parse_xxx(data: Any, spec: dict) -> list[dict]:
30
+ \"\"\"输入原始解析后的 JSON/XML,输出标准结果行。\"\"\"
31
+ return [{"title": ..., "url": ..., "snippet": ..., "source": ...}, ...]
32
+ ```
33
+
34
+ 标准结果行字段:title / url / snippet / source / published_at / score /
35
+ image_url / upstream(均为可选,缺省由下游补)。
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import html as _htmllib
41
+ import re
42
+ from pathlib import Path
43
+ from typing import Any, Callable
44
+
45
+ # 解析器签名:(原始数据, spec) -> 标准结果行列表
46
+ Parser = Callable[[Any, dict], list[dict]]
47
+
48
+ _PARSERS: dict[str, Parser] = {}
49
+
50
+
51
+ class UnknownParserError(ValueError):
52
+ """引用未注册的解析器时抛出。"""
53
+
54
+
55
+ def register(name: str, parser: Parser) -> None:
56
+ """注册一个解析器。重复注册同名视为错误(防止静默覆盖)。"""
57
+ if name in _PARSERS:
58
+ raise ValueError(f"解析器 '{name}' 已注册,重复注册请改名")
59
+ _PARSERS[name] = parser
60
+
61
+
62
+ def get(name: str) -> Parser:
63
+ """取解析器;未注册直接报错(fail-closed,不返回空函数)。"""
64
+ if name not in _PARSERS:
65
+ raise UnknownParserError(
66
+ f"未知解析器 '{name}',已注册: {sorted(_PARSERS)}"
67
+ )
68
+ return _PARSERS[name]
69
+
70
+
71
+ def has(name: str) -> bool:
72
+ """解析器是否已注册。"""
73
+ return name in _PARSERS
74
+
75
+
76
+ def list_parsers() -> dict[str, str]:
77
+ """列出全部已注册解析器(name -> docstring 首行)。"""
78
+ out: dict[str, str] = {}
79
+ for name, fn in _PARSERS.items():
80
+ doc = (fn.__doc__ or "").strip().split("\n")[0]
81
+ out[name] = doc
82
+ return out
83
+
84
+
85
+ def resolve(spec: dict) -> list[Parser]:
86
+ """从 spec 的 response.parser 字段解析出解析器列表。
87
+
88
+ 支持三种写法:
89
+ response.parser: worldbank # 单个
90
+ response.parser: [worldbank, strip] # 组合(按顺序应用)
91
+ response: {parser: null} # 显式无解析器
92
+ """
93
+ response = spec.get("response") or {}
94
+ if not isinstance(response, dict):
95
+ return []
96
+ raw = response.get("parser")
97
+ if raw is None:
98
+ return []
99
+ names = [raw] if isinstance(raw, str) else list(raw)
100
+ return [get(n) for n in names]
101
+
102
+
103
+ # ─────────────────────────────────────────────────────────────────────────────
104
+ # 声明式字段映射(output_map 的通用实现)
105
+ # ─────────────────────────────────────────────────────────────────────────────
106
+ #
107
+ # 为什么放在这里:2026-11-10 归一 13 个专用 builder 时发现,原 builder 常把
108
+ # 多个上游字段拼进 snippet(cleveland 的 `tombstone · 授权 CC0`、deezer 的
109
+ # `Deezer 音乐人 · 专辑 N · 粉丝 M`),而 output_map 只能取单个字段——归一后
110
+ # 这类信息会静默丢失。把「拼接」变成声明式能力,属于解析层职责,故与
111
+ # `parse_*` 解析器同文件维护;engines_base 只做委托调用。
112
+
113
+ def _dig(obj: Any, path: str) -> Any:
114
+ """按点分路径取嵌套值;路径段为数字时按数组索引。"""
115
+ if not path:
116
+ return obj
117
+ cur = obj
118
+ for seg in path.split("."):
119
+ if isinstance(cur, list):
120
+ try:
121
+ cur = cur[int(seg)]
122
+ except (ValueError, IndexError):
123
+ return None
124
+ elif isinstance(cur, dict):
125
+ cur = cur.get(seg)
126
+ else:
127
+ return None
128
+ return cur
129
+
130
+
131
+ def _coerce_field(val: Any, *, max_len: int | None = None) -> str:
132
+ """把 API 字段压成字符串:list 取首项、dict 丢弃、其余 str。"""
133
+ if val is None:
134
+ return ""
135
+ if isinstance(val, list):
136
+ if not val:
137
+ return ""
138
+ val = val[0]
139
+ if isinstance(val, dict):
140
+ return ""
141
+ s = str(val).strip()
142
+ if max_len is not None and len(s) > max_len:
143
+ return s[:max_len]
144
+ return s
145
+
146
+
147
+ def _render_field_template(template: str, item: dict) -> str:
148
+ """模板插值:`{field}` 取条目字段(支持点分路径),空值置空并折叠分隔符。
149
+
150
+ 与 URL 模板的区别:URL 模板任一占位为空则整体落空(否则拼出半截链接),
151
+ 而文本模板把空占位折叠掉——少一段仍是有效文本。
152
+ 连续/首尾的 `·`/`⇄`/`|` 分隔符会折叠,避免缺字段留下 `a · · b` 残渣。
153
+ """
154
+ def _repl(m: re.Match) -> str:
155
+ return _coerce_field(_dig(item, m.group(1)))
156
+
157
+ out = re.sub(r"\{([^}]+)\}", _repl, template)
158
+ out = re.sub(r"(?:\s*[·⇄|]\s*)+", lambda m: " " + next(
159
+ (ch for ch in m.group(0) if ch in "·⇄|"), "·") + " ", out)
160
+ out = out.strip()
161
+ out = re.sub(r"(?:^\s*[·⇄|]\s*|\s*[·⇄|]\s*$)", "", out)
162
+ return out.strip()
163
+
164
+
165
+ def _format_url_template(template: str, item: dict) -> str:
166
+ """支持 {field} 与 {a.b.c} 点分路径的 URL 模板;任一占位为空则返回空串。"""
167
+ vals = {m.group(1): _coerce_field(_dig(item, m.group(1)))
168
+ for m in re.finditer(r"\{([^}]+)\}", template)}
169
+ if any(not v for v in vals.values()):
170
+ return ""
171
+ try:
172
+ return re.sub(r"\{([^}]+)\}", lambda m: vals[m.group(1)], template)
173
+ except Exception:
174
+ return ""
175
+
176
+
177
+ def extract_items(data: Any, path: str) -> list:
178
+ """从 JSON 按路径提取列表。path 为 . / $ / [] / 空 且 data 为 list 时直接返回。"""
179
+ if path in ("", ".", "$", "[]"):
180
+ return data if isinstance(data, list) else []
181
+ if not isinstance(data, dict):
182
+ return []
183
+ obj = _dig(data, path)
184
+ if isinstance(obj, list):
185
+ return obj
186
+ # DBLP 等 API 在 h=1 时把 hit 收成对象而非数组
187
+ if isinstance(obj, dict):
188
+ return [obj]
189
+ return []
190
+
191
+
192
+ def make_field_parser(path: str, fields: dict[str, str], url_template: str | None = None,
193
+ max_items: int = 10, templates: dict[str, str] | None = None,
194
+ url_item_template: str | None = None) -> Callable:
195
+ """构造声明式 parser。支持点分路径字段、url_template(含嵌套占位)与模板拼接。
196
+
197
+ `templates` 是可选的模板字段映射(`{item_title, item_summary}`),声明后
198
+ 覆盖同名 `fields` 条目——用于需要多字段拼接的源(见 `_render_field_template`)。
199
+
200
+ `url_item_template` 是**逐条目**的 URL 拼接模板(如 eu_opendata 的
201
+ `landing_page.0.resource` 数组取首项)。与 `url_template` 的区别:后者用
202
+ `_format_url_template` 且任一占位为空即整体落空;前者在取不到值时保持
203
+ 「不声明 URL」,交给通用推断或下游补。
204
+ """
205
+ templates = templates or {}
206
+
207
+ def parser(data: Any) -> list[dict[str, Any]]:
208
+ if isinstance(data, list) and path in ("", ".", "$", "[]"):
209
+ items = data
210
+ elif isinstance(data, dict):
211
+ items = extract_items(data, path)
212
+ else:
213
+ items = []
214
+ results = []
215
+ for item in items:
216
+ if not isinstance(item, dict):
217
+ continue
218
+ r: dict[str, Any] = {}
219
+ for ok, ik in fields.items():
220
+ if not ik:
221
+ continue
222
+ raw = _dig(item, ik) if "." in str(ik) else item.get(ik, "")
223
+ if raw in ("", None) and "." not in str(ik):
224
+ raw = item.get(ik, "")
225
+ coerced = _coerce_field(raw, max_len=300 if ok == "snippet" else 500)
226
+ if coerced:
227
+ r[ok] = coerced
228
+ # 模板字段优先于同名单字段映射(声明式拼接覆盖单字段取值)。
229
+ # 键名是 output_map 的声明名(item_title_template),落到标准行字段
230
+ # 名(title/snippet)——不转换会把结果写进 `item_summary_template` 键。
231
+ # 模板渲染为空时**回落**到单字段映射(如 tatoeba 无译文时用 lang),
232
+ # 而不是把已取到的值覆盖成空。
233
+ for ok, tmpl in templates.items():
234
+ if not tmpl:
235
+ continue
236
+ std = {"item_title_template": "title",
237
+ "item_summary_template": "snippet"}.get(ok, ok)
238
+ rendered = _render_field_template(tmpl, item)
239
+ if rendered:
240
+ r[std] = rendered[:300 if std == "snippet" else 500]
241
+ if url_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
242
+ built = _format_url_template(url_template, item)
243
+ if built.startswith(("http://", "https://")):
244
+ r["url"] = built
245
+ else:
246
+ r.pop("url", None)
247
+ # 逐条目 URL 模板:占位取自条目自身(如 landing_page.0.resource),
248
+ # 取不到就保持无 URL(不造半截链接)。
249
+ if url_item_template and (not r.get("url") or not str(r["url"]).startswith(("http://", "https://"))):
250
+ built = _format_url_template(url_item_template, item)
251
+ if built.startswith(("http://", "https://")):
252
+ r["url"] = built
253
+ if isinstance(r.get("url"), str) and r["url"].startswith("//"):
254
+ r["url"] = "https:" + r["url"]
255
+ if r.get("title") or r.get("url"):
256
+ results.append(r)
257
+ return results[:max_items]
258
+ return parser
259
+
260
+
261
+ # ─────────────────────────────────────────────────────────────────────────────
262
+ # 内置解析器
263
+ # ─────────────────────────────────────────────────────────────────────────────
264
+
265
+ def _std_row(item: dict, source: str) -> dict:
266
+ """把一个原始条目转成标准结果行的最小骨架。"""
267
+ return {
268
+ "title": str(item.get("title") or "").strip(),
269
+ "url": str(item.get("url") or "").strip(),
270
+ "snippet": str(item.get("snippet") or item.get("summary") or "").strip(),
271
+ "source": source,
272
+ }
273
+
274
+
275
+ def parse_array_at(data: Any, spec: dict) -> list[dict]:
276
+ """通用:数组在指定索引或路径下(worldbank 的数组在第二个元素)。
277
+
278
+ spec.response.items_path 指定路径,如 "1" 或 "data.results"。
279
+ """
280
+ path = (spec.get("response") or {}).get("items_path", "")
281
+ if isinstance(data, list) and not path:
282
+ rows = data
283
+ else:
284
+ rows = _dig(data, path)
285
+ if not isinstance(rows, list):
286
+ return []
287
+ source = spec.get("engine_id", "?")
288
+ return [_std_row(r, source) for r in rows if isinstance(r, dict)]
289
+
290
+
291
+ def parse_object_root(data: Any, spec: dict) -> list[dict]:
292
+ """通用:响应是单对象根(unpaywall / doi 类)。
293
+
294
+ spec.response.fields 映射标准字段到对象路径。
295
+ """
296
+ if not isinstance(data, dict):
297
+ return []
298
+ fields = (spec.get("response") or {}).get("fields") or {}
299
+ source = spec.get("engine_id", "?")
300
+ row = {}
301
+ for std, path in fields.items():
302
+ row[std] = _dig(data, path)
303
+ row["source"] = source
304
+ return [row]
305
+
306
+
307
+ def parse_strip_fields(data: Any, spec: dict) -> list[dict]:
308
+ """组合用:剥 HTML 标签、截断 snippet。"""
309
+ rows = data if isinstance(data, list) else []
310
+ import html as _htmllib
311
+ for r in rows:
312
+ sn = r.get("snippet")
313
+ if isinstance(sn, str):
314
+ sn = _strip_tags(sn)
315
+ if "&" in sn:
316
+ sn = _htmllib.unescape(sn)
317
+ if len(sn) > 300:
318
+ sn = sn[:300]
319
+ r["snippet"] = sn
320
+ return rows
321
+
322
+
323
+ _TAG_RE = __import__("re").compile(r"<[^>]+>")
324
+
325
+
326
+ def _strip_tags(text: str) -> str:
327
+ return _TAG_RE.sub("", text)
328
+
329
+
330
+ def _dig(obj: Any, path: str) -> Any:
331
+ """按点分路径取嵌套值;路径段为数字时按数组索引。"""
332
+ if not path:
333
+ return obj
334
+ cur = obj
335
+ for seg in path.split("."):
336
+ if isinstance(cur, list):
337
+ try:
338
+ cur = cur[int(seg)]
339
+ except (ValueError, IndexError):
340
+ return None
341
+ elif isinstance(cur, dict):
342
+ cur = cur.get(seg)
343
+ else:
344
+ return None
345
+ return cur
346
+
347
+
348
+ def _flatten_segments(val: Any) -> str:
349
+ """把 [{value, is_bold}, ...] 数组展平成纯文本。
350
+
351
+ Mwmbl 的 title/extract 是高亮片段数组,标准 output_map 只会取到
352
+ 第一个 dict 然后被 _coerce_field 丢成空串。这个解析器做展平。
353
+ """
354
+ if isinstance(val, str):
355
+ return val
356
+ if isinstance(val, list):
357
+ return "".join(
358
+ str(seg.get("value", "")) if isinstance(seg, dict) else str(seg)
359
+ for seg in val
360
+ )
361
+ if isinstance(val, dict):
362
+ return str(val.get("value", ""))
363
+ return ""
364
+
365
+
366
+ def parse_mwmbl(data: Any, spec: dict) -> list[dict]:
367
+ """Mwmbl 响应解析(L2 试点:字段展平)。
368
+
369
+ 上游 title/extract 是 [{value, is_bold}] 数组,标准 output_map 无法
370
+ 展平,故注册专用解析器。这是「协议标准、解析变体」的典型形态。
371
+ """
372
+ if not isinstance(data, list):
373
+ return []
374
+ source = spec.get("engine_id", "mwmbl")
375
+ results = []
376
+ for _rk, r in enumerate(data):
377
+ if not isinstance(r, dict):
378
+ continue
379
+ title = _flatten_segments(r.get("title"))
380
+ extract = _flatten_segments(r.get("extract"))
381
+ url_ = r.get("url") or ""
382
+ if not title and not url_:
383
+ continue
384
+ results.append({
385
+ "title": title[:200] or url_[:200],
386
+ "url": url_,
387
+ "snippet": extract[:300],
388
+ "source": source,
389
+ "score": max(0.0, 0.7 - _rk * 0.05),
390
+ })
391
+ return results
392
+
393
+
394
+ def parse_artic(data: Any, spec: dict) -> list[dict]:
395
+ """Art Institute of Chicago 响应解析(L2:IIIF 图片需响应级 config 拼接)。
396
+
397
+ 上游把 IIIF 基础地址放在响应的 `config.iiif_url`(不在条目里),图片直链
398
+ 是 `{iiif_url}/{image_id}/full/843,/0/default.jpg`。这类「拼接依赖响应级
399
+ 配置」的解析无法用 output_map 声明,故注册专用解析器——协议标准、解析变体。
400
+
401
+ image_id 为空时**不产出** image_url(不得凭空造链接,见 test_image_sources)。
402
+ """
403
+ if not isinstance(data, dict):
404
+ return []
405
+ source = spec.get("engine_id", "artic")
406
+ iiif = str(((data.get("config") or {}).get("iiif_url") or "")).rstrip("/")
407
+ rows = data.get("data") if isinstance(data.get("data"), list) else []
408
+ results = []
409
+ for _rk, it in enumerate(rows):
410
+ if not isinstance(it, dict):
411
+ continue
412
+ title = str(it.get("title") or "").strip()
413
+ art_id = it.get("id")
414
+ url_ = f"https://www.artic.edu/artworks/{art_id}" if art_id else ""
415
+ if not title and not url_:
416
+ continue
417
+ row = {
418
+ "title": title[:200],
419
+ "url": url_,
420
+ "snippet": str(it.get("artist_display") or "")[:300],
421
+ "source": source,
422
+ "score": max(0.0, 0.7 - _rk * 0.05),
423
+ }
424
+ image_id = str(it.get("image_id") or "").strip()
425
+ if iiif and image_id:
426
+ row["image_url"] = f"{iiif}/{image_id}/full/843,/0/default.jpg"
427
+ # AIC 是 CC0 开放图像;授权缺失时按无授权处理,不凭空标注
428
+ lic = str(it.get("copyright_notice") or "").strip()
429
+ if lic:
430
+ row["image_license"] = lic
431
+ else:
432
+ row["image_license"] = "CC0(芝加哥艺术博物馆开放图像)"
433
+ results.append(row)
434
+ return results
435
+
436
+
437
+ # 注册通用解析器
438
+ register("array_at", parse_array_at)
439
+ register("object_root", parse_object_root)
440
+ register("strip_fields", parse_strip_fields)
441
+ register("mwmbl", parse_mwmbl)
442
+ register("artic", parse_artic)
443
+
444
+
445
+ def parse_smart_generic(data: Any, engine_name: str = "?",
446
+ limit: int = 10, spec: dict[str, Any] | None = None) -> list[dict[str, Any]]:
447
+ """通用智能自省推断解析器:自适应探测常见列表路径、单层嵌套展平与字段候选降级。
448
+
449
+ 列表探测(最多 3 层):
450
+ - 顶层 results/items/data/works/search/hits/papers/documents/entries 等
451
+ - 一层嵌套(data.results / data.value)
452
+ - 二层嵌套(data.webPages.value 等)
453
+
454
+ 字段别名与候选降级:
455
+ - title: title|name|heading|Title|titleNullable|headline|subject|topic
456
+ - url: url|URL|html_url|link|href|urlNullable|web_url|canonical_url(支持 url_template/{id})
457
+ - snippet: snippet|summary|content|description|abstract|subtitleNullable|subtitle|extract|details|text
458
+ - published_at: published_at|publishedAt|created_at|pubdate|date|time
459
+ """
460
+ if spec is None and isinstance(engine_name, dict):
461
+ spec = engine_name
462
+ engine_name = spec.get("engine_id", "?")
463
+ spec = spec or {}
464
+
465
+ list_keys = (
466
+ "results", "items", "value", "works", "search", "data",
467
+ "organic", "webPages", "hits", "documents", "entries", "papers",
468
+ )
469
+
470
+ def _find_items(obj: Any, depth: int = 0) -> list | None:
471
+ if depth > 3 or obj is None:
472
+ return None
473
+ if isinstance(obj, list):
474
+ if not obj or isinstance(obj[0], dict):
475
+ return obj
476
+ return None
477
+ if not isinstance(obj, dict):
478
+ return None
479
+ for key in list_keys:
480
+ if key not in obj:
481
+ continue
482
+ found = _find_items(obj[key], depth + 1)
483
+ if found is not None:
484
+ return found
485
+ if depth < 2:
486
+ for v in obj.values():
487
+ if isinstance(v, dict):
488
+ found = _find_items(v, depth + 1)
489
+ if found is not None:
490
+ return found
491
+ return None
492
+
493
+ items = _find_items(data) if isinstance(data, (dict, list)) else None
494
+ if not items or not isinstance(items, list):
495
+ return []
496
+
497
+ url_template = spec.get("url_template") or (spec.get("output_map") or {}).get("url_template")
498
+ results: list[dict[str, Any]] = []
499
+
500
+ for idx, i in enumerate(items):
501
+ if not isinstance(i, dict):
502
+ continue
503
+ flat = dict(i)
504
+ for nested_k in ("paper", "item", "data", "node", "article", "entry", "show", "bibjson"):
505
+ if isinstance(i.get(nested_k), dict):
506
+ for k, v in i[nested_k].items():
507
+ flat.setdefault(k, v)
508
+
509
+ title = (
510
+ flat.get("title") or flat.get("name") or flat.get("heading")
511
+ or flat.get("Title") or flat.get("titleNullable") or flat.get("title_s")
512
+ or flat.get("headline") or flat.get("subject") or flat.get("topic")
513
+ or flat.get("text") or flat.get("cycle") or ""
514
+ )
515
+ if isinstance(title, dict):
516
+ # 多语言字典(如 EU Open Data):优先取 en/zh/fr/de,否则取首个
517
+ for lang in ("en", "zh", "fr", "de"):
518
+ if title.get(lang):
519
+ title = title[lang]
520
+ break
521
+ if isinstance(title, dict) and title:
522
+ title = next(iter(title.values()))
523
+ elif isinstance(title, list):
524
+ title = title[0] if title else ""
525
+ raw_id = flat.get("id") or flat.get("objectID") or flat.get("ID") or ""
526
+ url = (
527
+ flat.get("url") or flat.get("URL") or flat.get("html_url")
528
+ or flat.get("link") or flat.get("href") or flat.get("urlNullable")
529
+ or flat.get("web_url") or flat.get("canonical_url") or flat.get("guid")
530
+ or flat.get("uri_s") or flat.get("url_public_html")
531
+ or flat.get("resource") or flat.get("landing_page") or ""
532
+ )
533
+ if isinstance(url, list) and url:
534
+ if isinstance(url[0], dict):
535
+ url = url[0].get("url") or url[0].get("href") or url[0].get("resource") or ""
536
+ else:
537
+ url = str(url[0])
538
+ if not url and url_template:
539
+ url = url_template.replace("{id}", str(raw_id))
540
+ for _k, _v in flat.items():
541
+ if f"{{{_k}}}" in url:
542
+ url = url.replace(f"{{{_k}}}", str(_v))
543
+
544
+ snippet = (
545
+ flat.get("snippet") or flat.get("summary") or flat.get("content")
546
+ or flat.get("description") or flat.get("abstract") or flat.get("abstract_s")
547
+ or flat.get("subtitleNullable") or flat.get("subtitle")
548
+ or flat.get("extract") or flat.get("details") or flat.get("text") or ""
549
+ )
550
+ if not snippet and (flat.get("eol") or flat.get("latest")):
551
+ _sp = [f"最新 {flat['latest']}" if flat.get("latest") else "",
552
+ f"发布 {flat['releaseDate']}" if flat.get("releaseDate") else "",
553
+ f"支持至 {flat['support']}" if flat.get("support") else "",
554
+ f"EOL {flat['eol']}" if flat.get("eol") else ""]
555
+ snippet = " · ".join(x for x in _sp if x)
556
+ if isinstance(snippet, dict):
557
+ for lang in ("en", "zh", "fr", "de"):
558
+ if snippet.get(lang):
559
+ snippet = snippet[lang]
560
+ break
561
+ if isinstance(snippet, dict) and snippet:
562
+ snippet = next(iter(snippet.values()))
563
+ elif isinstance(snippet, list):
564
+ snippet = snippet[0] if snippet else ""
565
+
566
+ # 文本标签剥离与 HTML 实体反转义
567
+ if isinstance(title, str) and ("<" in title or "&" in title):
568
+ title = _strip_tags(title)
569
+ if "&" in title:
570
+ title = _htmllib.unescape(title)
571
+ if isinstance(snippet, str) and ("<" in snippet or "&" in snippet):
572
+ snippet = _strip_tags(snippet)
573
+ if "&" in snippet:
574
+ snippet = _htmllib.unescape(snippet)
575
+
576
+ published_at = (
577
+ flat.get("published_at") or flat.get("publishedAt")
578
+ or flat.get("created_at") or flat.get("pubdate") or flat.get("date")
579
+ or flat.get("premiered") or flat.get("first_air_date") or ""
580
+ )
581
+ if published_at:
582
+ try:
583
+ from engines_base import _normalize_epoch
584
+ published_at = _normalize_epoch(published_at)
585
+ except Exception:
586
+ published_at = str(published_at)
587
+
588
+ # 统一分值契约:复用 engines_base.rank_score(保证 [0, 1] 夹紧、防 NaN/Inf、单调平滑衰减)
589
+ raw_score = next((v for v in (flat.get("score"), flat.get("relevance_score")) if v not in (None, "")), 0.5)
590
+ try:
591
+ from engines_base import rank_score
592
+ score = rank_score(raw_score, idx)
593
+ except Exception:
594
+ score = max(0.0, 0.7 - idx * 0.05)
595
+
596
+ row: dict[str, Any] = {
597
+ "title": str(title)[:200],
598
+ "url": str(url),
599
+ "snippet": str(snippet)[:300],
600
+ "score": score,
601
+ "source": engine_name,
602
+ }
603
+ if published_at:
604
+ row["published_at"] = str(published_at)
605
+ results.append(row)
606
+ return results[:limit]
607
+
608
+
609
+ register("smart_generic", parse_smart_generic)
610
+
611
+
612
+ # 迁移 engines_base.py 里现有的 4 个专用解析器(保持向后兼容)
613
+ def _migrate_builtin() -> None:
614
+ """把 engines_base 的 _CUSTOM_JSON_PARSERS 投影进注册表。
615
+
616
+ 为什么不直接删 engines_base 的实现:它们有更精细的字段处理
617
+ (如 semantic_scholar 的引用数、作者拼接),迁移到声明式
618
+ output_map 会丢信息。这里先投影,让 spec 可以显式引用;
619
+ 引擎名隐式匹配作为兜底保留,逐步切到显式。
620
+ """
621
+ try:
622
+ import engines_base
623
+ except ImportError:
624
+ return
625
+ mapping = {
626
+ "uapi": engines_base._parse_uapi,
627
+ "semantic_scholar": engines_base._parse_semantic_scholar,
628
+ "doi": engines_base._parse_doi,
629
+ "unpaywall": engines_base._parse_unpaywall,
630
+ }
631
+ for name, fn in mapping.items():
632
+ if not has(name):
633
+ register(name, fn)
634
+
635
+
636
+ _migrate_builtin()
637
+
638
+
639
+ # ─────────────────────────────────────────────────────────────────────────────
640
+ # 声明式架构自省与结构漂移诊断(第一性原理 + MECE 原则)
641
+ # ─────────────────────────────────────────────────────────────────────────────
642
+
643
+ _TITLE_SYNONYMS = (
644
+ "title", "name", "headline", "subject", "text", "label",
645
+ "caption", "item_title", "artwork_title", "track_name", "display_name",
646
+ )
647
+ _URL_SYNONYMS = (
648
+ "url", "link", "web_url", "html_url", "href", "uri",
649
+ "source_url", "landing_page", "target_url", "permalink", "page_url", "site_url",
650
+ )
651
+ _SUMMARY_SYNONYMS = (
652
+ "snippet", "summary", "description", "abstract", "body",
653
+ "content", "desc", "overview", "intro", "tombstone", "details", "comment",
654
+ )
655
+ _PUB_SYNONYMS = (
656
+ "published_at", "created_at", "pubdate", "pub_date", "date",
657
+ "time", "timestamp", "premiered", "first_air_date", "release_date",
658
+ )
659
+
660
+
661
+ def _flatten_item(item: Any, prefix: str = "", depth: int = 0, max_depth: int = 3) -> dict[str, Any]:
662
+ """将嵌套字典/列表展平为点分路径键值字典(深度受控,列表展开前 2 条)。"""
663
+ flat: dict[str, Any] = {}
664
+ if depth > max_depth or not isinstance(item, (dict, list)):
665
+ return flat
666
+ if isinstance(item, dict):
667
+ for k, v in item.items():
668
+ path = f"{prefix}.{k}" if prefix else str(k)
669
+ if isinstance(v, (dict, list)) and depth < max_depth:
670
+ flat.update(_flatten_item(v, path, depth + 1, max_depth))
671
+ else:
672
+ flat[path] = v
673
+ elif isinstance(item, list):
674
+ for i, v in enumerate(item[:2]):
675
+ path = f"{prefix}.{i}" if prefix else str(i)
676
+ if isinstance(v, (dict, list)) and depth < max_depth:
677
+ flat.update(_flatten_item(v, path, depth + 1, max_depth))
678
+ else:
679
+ flat[path] = v
680
+ return flat
681
+
682
+
683
+ def _find_candidate_containers(data: Any, prefix: str = "", depth: int = 0, max_depth: int = 4) -> list[tuple[str, list, float]]:
684
+ """递归搜索全部字典列表,并按结构质量评分。"""
685
+ candidates: list[tuple[str, list, float]] = []
686
+ if depth > max_depth:
687
+ return candidates
688
+ if isinstance(data, list):
689
+ if data and isinstance(data[0], dict):
690
+ sample = data[0]
691
+ score = 0.5 + min(0.3, len(data) * 0.02)
692
+ keys = {str(k).lower() for k in sample.keys()}
693
+ if any(k in keys for k in ("title", "name", "id", "url", "link")):
694
+ score += 0.2
695
+ candidates.append((prefix or ".", data, score))
696
+ return candidates
697
+ if isinstance(data, dict):
698
+ for k, v in data.items():
699
+ path = f"{prefix}.{k}" if prefix else str(k)
700
+ if isinstance(v, list) and v and isinstance(v[0], dict):
701
+ sample = v[0]
702
+ score = 0.5 + min(0.3, len(v) * 0.02)
703
+ keys = {str(k).lower() for k in sample.keys()}
704
+ if any(syn in keys for syn in ("title", "name", "id", "url", "link")):
705
+ score += 0.2
706
+ candidates.append((path, v, score))
707
+ elif isinstance(v, dict) and depth < max_depth:
708
+ candidates.extend(_find_candidate_containers(v, path, depth + 1, max_depth))
709
+ candidates.sort(key=lambda x: x[2], reverse=True)
710
+ return candidates
711
+
712
+
713
+ def _match_best_field(target_kind: str, flat: dict[str, Any]) -> tuple[str | None, Any, float]:
714
+ """根据目标类型和扁平键树,启发式匹配最优路径。"""
715
+ if target_kind == "title":
716
+ for path, val in flat.items():
717
+ if not isinstance(val, (str, int)) or not str(val).strip():
718
+ continue
719
+ seg = path.split(".")[-1].lower()
720
+ if seg in ("title", "name", "headline", "artwork_title"):
721
+ return path, val, 0.95
722
+ if seg in _TITLE_SYNONYMS:
723
+ return path, val, 0.85
724
+ elif target_kind == "url":
725
+ url_candidates: list[tuple[str, Any, float]] = []
726
+ for path, val in flat.items():
727
+ s = str(val or "").strip()
728
+ if not (s.startswith("http://") or s.startswith("https://") or s.startswith("/")):
729
+ continue
730
+ seg = path.split(".")[-1].lower()
731
+ score = 0.6
732
+ if seg in _URL_SYNONYMS:
733
+ score += 0.3
734
+ if any(s.lower().endswith(ext) for ext in (".jpg", ".jpeg", ".png", ".gif", ".webp")):
735
+ score -= 0.4
736
+ url_candidates.append((path, val, score))
737
+ if url_candidates:
738
+ url_candidates.sort(key=lambda x: x[2], reverse=True)
739
+ best = url_candidates[0]
740
+ if best[2] >= 0.5:
741
+ return best[0], best[1], best[2]
742
+ for path, val in flat.items():
743
+ seg = path.split(".")[-1].lower()
744
+ if seg in _URL_SYNONYMS and val:
745
+ return path, val, 0.75
746
+ elif target_kind == "summary":
747
+ for path, val in flat.items():
748
+ s = str(val or "").strip()
749
+ if not s or len(s) < 5:
750
+ continue
751
+ seg = path.split(".")[-1].lower()
752
+ if seg in ("snippet", "summary", "description", "abstract"):
753
+ return path, val, 0.90
754
+ if seg in _SUMMARY_SYNONYMS:
755
+ return path, val, 0.80
756
+ return None, None, 0.0
757
+
758
+
759
+ def diagnose_schema_drift(raw_data: Any, spec_or_output_map: dict[str, Any]) -> dict[str, Any]:
760
+ """上游数据源结构漂移自省对拍诊断(第一性原理 + MECE 原则)。
761
+
762
+ 层级覆盖:
763
+ 1. Envelope: 业务错误封套、非结构化数据判定
764
+ 2. Container: items 容器路径位移对拍与自动推荐
765
+ 3. Field: item_title / item_url / item_summary 字段更名、层级下沉同义与特征对拍
766
+ """
767
+ omap = spec_or_output_map.get("output_map") if isinstance(spec_or_output_map.get("output_map"), dict) else spec_or_output_map
768
+ if not isinstance(omap, dict):
769
+ omap = {}
770
+
771
+ current_items_path = omap.get("items", "")
772
+ current_title = omap.get("item_title", "title")
773
+ current_url = omap.get("item_url", "url")
774
+ current_summary = omap.get("item_summary", "snippet")
775
+
776
+ issues: list[str] = []
777
+ container_drift: dict[str, Any] | None = None
778
+ field_drifts: dict[str, Any] = {}
779
+ suggested_patch: dict[str, str] = {}
780
+
781
+ # 1. Envelope 层
782
+ if not isinstance(raw_data, (dict, list)):
783
+ return {
784
+ "ok": False,
785
+ "drift_detected": False,
786
+ "stage": "envelope",
787
+ "issues": [f"响应非 JSON 结构 (类型: {type(raw_data).__name__})"],
788
+ "confidence": 0.0,
789
+ "suggested_patch": {},
790
+ }
791
+ if isinstance(raw_data, dict):
792
+ err_val = raw_data.get("error") or raw_data.get("err_msg") or raw_data.get("message")
793
+ if err_val and not raw_data.get("data") and not raw_data.get("results") and not raw_data.get("items"):
794
+ return {
795
+ "ok": False,
796
+ "drift_detected": False,
797
+ "stage": "envelope",
798
+ "issues": [f"上游返回业务错误封套: {err_val}"],
799
+ "confidence": 0.0,
800
+ "suggested_patch": {},
801
+ }
802
+
803
+ # 2. Container 层
804
+ items = extract_items(raw_data, current_items_path)
805
+ if not items or not isinstance(items[0], dict):
806
+ candidates = _find_candidate_containers(raw_data)
807
+ if candidates:
808
+ best_path, best_items, score = candidates[0]
809
+ container_drift = {
810
+ "from": current_items_path,
811
+ "to": best_path,
812
+ "count": len(best_items),
813
+ "score": score,
814
+ }
815
+ issues.append(f"容器路径失效: '{current_items_path}' 未提取到条目,候选路径 '{best_path}' (包含 {len(best_items)} 条)")
816
+ suggested_patch["items"] = best_path
817
+ items = best_items
818
+ else:
819
+ return {
820
+ "ok": False,
821
+ "drift_detected": False,
822
+ "stage": "container",
823
+ "issues": [f"未在响应中发现任何字典列表容器 (当前 items='{current_items_path}')"],
824
+ "confidence": 0.0,
825
+ "suggested_patch": {},
826
+ }
827
+
828
+ # 3. Field 层
829
+ sample = items[0]
830
+ flat = _flatten_item(sample, max_depth=3)
831
+
832
+ # 校验与对拍 title
833
+ val_title = _dig(sample, current_title) if current_title else None
834
+ if not val_title:
835
+ cand_p, cand_v, cand_s = _match_best_field("title", flat)
836
+ if cand_p and cand_p != current_title:
837
+ field_drifts["item_title"] = {"from": current_title, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
838
+ issues.append(f"标题字段失效: '{current_title}' 为空 -> 候选 '{cand_p}' (值: {cand_v!r})")
839
+ suggested_patch["item_title"] = cand_p
840
+
841
+ # 校验与对拍 url
842
+ val_url = _dig(sample, current_url) if current_url else None
843
+ if not val_url:
844
+ cand_p, cand_v, cand_s = _match_best_field("url", flat)
845
+ if cand_p and cand_p != current_url:
846
+ field_drifts["item_url"] = {"from": current_url, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
847
+ issues.append(f"链接字段失效: '{current_url}' 为空 -> 候选 '{cand_p}' (值: {cand_v!r})")
848
+ suggested_patch["item_url"] = cand_p
849
+
850
+ # 校验与对拍 summary
851
+ if current_summary:
852
+ val_sum = _dig(sample, current_summary)
853
+ if not val_sum:
854
+ cand_p, cand_v, cand_s = _match_best_field("summary", flat)
855
+ if cand_p and cand_p != current_summary:
856
+ field_drifts["item_summary"] = {"from": current_summary, "to": cand_p, "sample": str(cand_v)[:50], "score": cand_s}
857
+ issues.append(f"摘要字段失效: '{current_summary}' 为空 -> 候选 '{cand_p}'")
858
+ suggested_patch["item_summary"] = cand_p
859
+
860
+ drift_detected = bool(container_drift or field_drifts)
861
+ stage = "field" if field_drifts else ("container" if container_drift else "ok")
862
+ confidence = 0.0
863
+ if drift_detected:
864
+ confidence = 0.95 if (suggested_patch.get("items") or ("item_title" in suggested_patch and "item_url" in suggested_patch)) else 0.80
865
+
866
+ return {
867
+ "ok": not drift_detected,
868
+ "drift_detected": drift_detected,
869
+ "stage": stage,
870
+ "issues": issues,
871
+ "container_drift": container_drift,
872
+ "field_drifts": field_drifts,
873
+ "suggested_patch": suggested_patch,
874
+ "confidence": confidence,
875
+ }
876
+
877
+
878
+ def render_drift_report(diagnosis: dict[str, Any], engine_id: str = "") -> str:
879
+ """渲染终端格式化的结构漂移诊断报告。"""
880
+ lines: list[str] = []
881
+ prefix = f"[{engine_id}] " if engine_id else ""
882
+ if not diagnosis.get("drift_detected"):
883
+ if diagnosis.get("issues"):
884
+ lines.append(f"{prefix}诊断发现异常 (Stage: {diagnosis.get('stage')}):")
885
+ for iss in diagnosis["issues"]:
886
+ lines.append(f" • {iss}")
887
+ else:
888
+ lines.append(f"{prefix}结构正常,未检测到漂移。")
889
+ return "\n".join(lines)
890
+
891
+ lines.append(f"{prefix}检测到上游响应结构漂移 (Stage: {diagnosis.get('stage')}, 置信度: {diagnosis.get('confidence', 0):.0%}):")
892
+ for iss in diagnosis.get("issues", []):
893
+ lines.append(f" • {iss}")
894
+
895
+ patch = diagnosis.get("suggested_patch") or {}
896
+ if patch:
897
+ lines.append(" 建议 Spec 补丁 (output_map):")
898
+ for k, v in patch.items():
899
+ lines.append(f" {k}: {v}")
900
+ return "\n".join(lines)
901
+
902
+
903
+ def apply_schema_patch(spec_file: str | Path, patch: dict[str, str]) -> tuple[bool, str]:
904
+ """安全原子应用 Spec 补丁:保留所有注释和格式,仅改写 output_map 对应键。"""
905
+ import re as _re
906
+ p = Path(spec_file)
907
+ if not p.is_file():
908
+ return False, f"Spec 文件不存在: {p}"
909
+
910
+ text = p.read_text(encoding="utf-8")
911
+ if "output_map:" not in text:
912
+ return False, "Spec 中无 output_map 节点,不支持就地修改"
913
+
914
+ for k, v in patch.items():
915
+ pattern = _re.compile(rf"^([ \t]+){_re.escape(k)}:\s*.*$", _re.M)
916
+ if pattern.search(text):
917
+ text = pattern.sub(rf"\g<1>{k}: {v}", text)
918
+ else:
919
+ # 补在 output_map 之后
920
+ text = _re.sub(r"^(output_map:.*)$", rf"\1\n {k}: {v}", text, count=1, flags=_re.M)
921
+
922
+ p.write_text(text, encoding="utf-8")
923
+ return True, f"已安全更新 {p.name} 中的 {len(patch)} 个字段"
924
+