vod-devkit 0.5.0 → 0.5.2

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 (66) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/QUICKSTART.md +1 -1
  3. package/README.en.md +190 -57
  4. package/README.md +194 -75
  5. package/bin/vod-devkit +436 -426
  6. package/contract/tools.schema.json +78 -8
  7. package/integrations/codeartsdoer/host.json +11 -0
  8. package/package.json +4 -1
  9. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  10. package/plugins/vod-devkit/build-info.json +3 -3
  11. package/plugins/vod-devkit/skills/vod-core/SKILL.md +12 -4
  12. package/plugins/vod-devkit/skills/vod-core/references/acceptance-criteria.md +9 -0
  13. package/plugins/vod-devkit/skills/vod-core/references/verification-method.md +29 -0
  14. package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +57 -11
  15. package/plugins/vod-devkit/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  16. package/plugins/vod-devkit/skills/vod-feedback-collect/references/verification-method.md +31 -0
  17. package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +3 -1
  18. package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +22 -1
  19. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  20. package/plugins/vod-devkit/vod_mcp/attribution.py +378 -0
  21. package/plugins/vod-devkit/vod_mcp/host_adapters/__init__.py +26 -0
  22. package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +73 -0
  23. package/plugins/vod-devkit/vod_mcp/host_adapters/codearts.py +57 -0
  24. package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +209 -0
  25. package/plugins/vod-devkit/vod_mcp/host_adapters/dsh.py +176 -0
  26. package/plugins/vod-devkit/vod_mcp/host_adapters/generic.py +132 -0
  27. package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +76 -0
  28. package/plugins/vod-devkit/vod_mcp/host_adapters/opencode.py +52 -0
  29. package/plugins/vod-devkit/vod_mcp/hosts.py +20 -0
  30. package/plugins/vod-devkit/vod_mcp/packs.py +3 -1
  31. package/plugins/vod-devkit/vod_mcp/payload.py +174 -0
  32. package/plugins/vod-devkit/vod_mcp/server.py +13 -1
  33. package/plugins/vod-devkit/vod_mcp/tools.py +399 -46
  34. package/plugins/vod-devkit/vod_mcp/update_check.py +31 -3
  35. package/skills/vod-core/SKILL.md +12 -4
  36. package/skills/vod-core/references/acceptance-criteria.md +9 -0
  37. package/skills/vod-core/references/verification-method.md +29 -0
  38. package/skills/vod-feedback-collect/SKILL.md +57 -11
  39. package/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  40. package/skills/vod-feedback-collect/references/verification-method.md +31 -0
  41. package/skills/vod-problem-classification-rules/SKILL.md +3 -1
  42. package/skills/vod-scoring-rules/SKILL.md +22 -1
  43. package/vod_mcp/__init__.py +1 -1
  44. package/vod_mcp/attribution.py +378 -0
  45. package/vod_mcp/host_adapters/__init__.py +26 -0
  46. package/vod_mcp/host_adapters/__pycache__/__init__.cpython-314.pyc +0 -0
  47. package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
  48. package/vod_mcp/host_adapters/__pycache__/codearts.cpython-314.pyc +0 -0
  49. package/vod_mcp/host_adapters/__pycache__/codex.cpython-314.pyc +0 -0
  50. package/vod_mcp/host_adapters/__pycache__/dsh.cpython-314.pyc +0 -0
  51. package/vod_mcp/host_adapters/__pycache__/generic.cpython-314.pyc +0 -0
  52. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
  53. package/vod_mcp/host_adapters/__pycache__/opencode.cpython-314.pyc +0 -0
  54. package/vod_mcp/host_adapters/base.py +73 -0
  55. package/vod_mcp/host_adapters/codearts.py +57 -0
  56. package/vod_mcp/host_adapters/codex.py +209 -0
  57. package/vod_mcp/host_adapters/dsh.py +176 -0
  58. package/vod_mcp/host_adapters/generic.py +132 -0
  59. package/vod_mcp/host_adapters/hermes.py +76 -0
  60. package/vod_mcp/host_adapters/opencode.py +52 -0
  61. package/vod_mcp/hosts.py +20 -0
  62. package/vod_mcp/packs.py +3 -1
  63. package/vod_mcp/payload.py +174 -0
  64. package/vod_mcp/server.py +13 -1
  65. package/vod_mcp/tools.py +399 -46
  66. package/vod_mcp/update_check.py +31 -3
@@ -17,6 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from pathlib import Path
19
19
 
20
+ from vod_mcp import attribution as _attrib
20
21
  from vod_mcp import provenance
21
22
  from vod_mcp import DEFAULT_JAVA_BASE
22
23
 
@@ -93,16 +94,25 @@ _META_SNAPSHOT = {"products": ["agentarts", "codearts", "dataarts", "maas", "obs
93
94
 
94
95
 
95
96
  def _load_meta(force: bool = False) -> dict:
96
- """可漂移值(product 白名单等)动态取:缓存 TTL 24h,
97
- 引擎端点不可达时回退快照并标 stale。真源=引擎 submit 校验常量。
97
+ """可漂移值动态取:缓存 TTL 24h,引擎端点不可达时回退快照并标 stale。
98
+ 真源=引擎 submit 校验常量。
99
+
98
100
  T7i:productCatalog=[{id,name}](t_vod_product 运营预置,meta 组装)——
99
- 提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。"""
101
+ 提交产品归因按平台主键 id 的解析真源;老引擎无该键=catalog 空。
102
+
103
+ **2026-11-12 引擎契约收紧**:
104
+ · `nameAliases` / `aliases` 已由引擎删除 → 本函数不再读取;别名能力改由
105
+ attribution 的规则派生 + BRAND_ALIASES 提供。
106
+ · `problemTypes` 改为按产品下发(`?productId=`):**无参请求不含该键**。
107
+ 分类白名单必须用 `_allowed_tags(product_id)` 按产品取,见下。
108
+ """
100
109
  import time
101
110
  cache = _RT.get("meta_cache") or {}
102
111
  now = time.time()
103
112
  if not force and cache.get("data") and now - cache.get("fetchedAt", 0) < _META_TTL:
104
113
  return {"products": cache["data"].get("products", _META_SNAPSHOT["products"]),
105
114
  "catalog": cache["data"].get("productCatalog") or [],
115
+ "dictVersion": cache["data"].get("dictVersion"),
106
116
  "stale": False, "source": "cache"}
107
117
  try:
108
118
  out = _http("GET", _META_PATH, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
@@ -111,10 +121,14 @@ def _load_meta(force: bool = False) -> dict:
111
121
  _save_runtime({"meta_cache": {"fetchedAt": int(now), "data": data}})
112
122
  return {"products": data["products"],
113
123
  "catalog": data.get("productCatalog") or [],
124
+ "dictVersion": data.get("dictVersion"),
114
125
  "stale": False, "source": "meta"}
115
126
  except ToolError:
116
127
  pass
128
+ # 快照不含分类白名单:_allowed_tags 取不到产品分类时 allowed 为空=不校验
129
+ # (宁可放行也不误杀采集)
117
130
  return {"products": _META_SNAPSHOT["products"], "catalog": [],
131
+ "dictVersion": None,
118
132
  "stale": True, "source": "snapshot"}
119
133
 
120
134
 
@@ -192,35 +206,264 @@ _PRODUCT_MAP = {
192
206
  }
193
207
 
194
208
 
195
- def _resolve_product(params: dict) -> tuple[str | None, str | None]:
196
- """归因(D-attrib-A:2026-11-06 负责人拍板,方案 A 收紧):
197
- 归因只由 install 绑定(runtime.json product)决定——运行期显式传参
198
- 仅当与绑定一致(忽略大小写)才采信;不一致=宿主模型自报,一律忽略
199
- 回退绑定值(实锤:hermes 会话模型传 product="hermes" 覆盖 CodeArts
200
- 绑定,[HERMES] 未注册错归)。无绑定 → None(引擎 UNKNOWN 档兜底)。
201
- 返回 (product, ignored_runtime_product)。
202
- T7i(方案 A,2026-11-05 拍板):产品归因主键化——
203
- ①纯数字串=平台主键 id,原样透传(引擎 selectById 精确命中)
204
- ②名字→meta productCatalog 按名解析出平台 id 后提交(对账主键化,
205
- 归一化/改名漂移不进提交链路);_PRODUCT_MAP 先归一短码再查目录
206
- ③目录无此名/目录不可用→规范名原样上送(引擎 name 兼容通道,
207
- 命中同样补落 product_id)——不静默丢提交。"""
208
- binding = str(_RT.get("product") or "").strip()
209
- raw = str(params.get("product") or "").strip()
210
- ignored = None
211
- if raw and (not binding or raw.lower() != binding.lower()):
212
- ignored = raw # 运行期自报≠绑定(或无绑定)→ 忽略留痕,不采信
213
- raw = ""
214
- product = raw or binding or None
215
- if not product:
216
- return None, ignored
217
- if product.isdigit():
218
- return product, ignored
219
- name = _PRODUCT_MAP.get(product.lower(), product)
220
- for item in (_load_meta().get("catalog") or []):
221
- if str(item.get("name") or "").lower() == name.lower():
222
- return str(item.get("id")), ignored
223
- return name, ignored
209
+ _SESSION_TTL = 30 * 60 # 会话内滑动记忆(D-product-ask-1)
210
+ _SESSION_MEM: dict = {} # 进程=一次宿主会话:重启即清,跨会话不继承
211
+ _UNRESOLVED_CODE = -32010 # 「需要先问用户是哪个产品」的可执行错误码
212
+
213
+
214
+ def _session_key(client_info) -> str:
215
+ """记忆作用域(Scope):宿主 + 身份。
216
+
217
+ 进程内即一次 stdio 会话;远程面是多租户共享进程,所以身份也必须进 key,
218
+ 否则 A 用户的"不知道→CodeArts"会串到 B 用户。
219
+ """
220
+ ci = client_info or {}
221
+ import hashlib
222
+ ident = _eff_key() or ""
223
+ ident_hash = hashlib.sha256(ident.encode()).hexdigest()[:8] if ident else _install_nonce()
224
+ return f"{ci.get('name') or 'unknown'}|{ident_hash}"
225
+
226
+
227
+ def _memory_get(client_info) -> dict:
228
+ import time as _t
229
+ cur = _SESSION_MEM.get(_session_key(client_info)) or {}
230
+ if cur and _t.time() - float(cur.get("at") or 0) > _SESSION_TTL:
231
+ return {}
232
+ return dict(cur)
233
+
234
+
235
+ def _memory_put(client_info, **fields) -> None:
236
+ import time as _t
237
+ key = _session_key(client_info)
238
+ cur = _memory_get(client_info)
239
+ cur.update(fields)
240
+ cur["at"] = int(_t.time()) # 滑动过期
241
+ _SESSION_MEM[key] = cur
242
+
243
+
244
+ def _host_product() -> str | None:
245
+ """宿主产品(兜底用):安装期写入 runtime.host_product,env 可覆盖。"""
246
+ return (os.environ.get("VOD_HOST_PRODUCT")
247
+ or str(_RT.get("host_product") or "").strip()
248
+ or str(_runtime_cfg().get("host_product") or "").strip() or None)
249
+
250
+
251
+ def search_products(params: dict) -> dict:
252
+ """产品候选检索(只读):给模型 3-5 个候选去问用户,而不是从 103 条里瞎猜。"""
253
+ query = str(params.get("query") or "").strip()
254
+ limit = int(params.get("limit") or 5)
255
+ limit = max(1, min(limit, 20))
256
+ meta = _load_meta()
257
+ catalog = meta.get("catalog") or []
258
+ if not query:
259
+ return {"candidates": [], "total": len(catalog)}
260
+ idx = _attrib.build_alias_index(meta)
261
+ hits = _attrib.match_products(query, idx)
262
+ seen, cands = set(), []
263
+ for h in hits:
264
+ pid = str(h.get("id") or "")
265
+ if not pid or pid in seen:
266
+ continue
267
+ seen.add(pid)
268
+ cands.append({"id": pid, "name": h["product"],
269
+ "score": round(min(1.0, len(h["alias"]) / max(len(query), 1)), 2),
270
+ "matchReason": f"alias:{h['alias']}"})
271
+ if not cands: # 别名没命中:退回名字子串(用户可能打错/只说一半)
272
+ q = query.lower()
273
+ for item in catalog:
274
+ name = str(item.get("name") or "")
275
+ if q and (q in name.lower() or name.lower() in q):
276
+ cands.append({"id": str(item.get("id")), "name": name, "score": 0.5,
277
+ "matchReason": "name-substring"})
278
+ if not cands: # 完全无关联词:给名录前 N 个当"可选项"(问用户用)
279
+ for item in catalog[:limit]:
280
+ cands.append({"id": str(item.get("id")), "name": str(item.get("name") or ""),
281
+ "score": 0.0, "matchReason": "catalog-default"})
282
+ cands.sort(key=lambda c: (c["score"], len(c["name"])), reverse=True)
283
+ return {"candidates": cands[:limit], "total": len(catalog)}
284
+
285
+
286
+ def _attribute_product(items: list, params: dict, client_info: dict | None = None) -> dict:
287
+ """归因(D-product-ask-1,2026-11-11 负责人拍板:不许裸 UNKNOWN,缺产品先问)。
288
+
289
+ 优先级(按拍板口径,不是"原话永远第一"):
290
+ ① 用户明确回答/确认(params.product,仅问过用户后由模型填)
291
+ ② 原话唯一且高置信提及(多产品/歧义=低置信,转去问)
292
+ ③ 会话记忆(30 分钟滑动,进程内;跨会话不继承)
293
+ ④ 安装先验
294
+ ⑤ host_default:仅当用户明确说"不知道/随便"(params.productNotSpecified)
295
+ 都拿不到 → 返回 source=unknown + confidence=low,由调用方抛可执行错误要求追问。
296
+ """
297
+ text = "\n".join(content for _i, _v, content in items)
298
+ meta = _load_meta()
299
+ answer = str(params.get("product") or "").strip()
300
+ mem = _memory_get(client_info)
301
+ binding = str(_RT.get("product") or "").strip() or None
302
+
303
+ if answer:
304
+ rid = _attrib.resolve_id(answer, meta)
305
+ hit = [c for c in (meta.get("catalog") or [])
306
+ if str(c.get("id")) == str(rid)
307
+ or str(c.get("name") or "").lower() == answer.lower()]
308
+ if not hit and not (meta.get("catalog") or []):
309
+ # 名录不可用(离线/快照/老引擎):没有校验依据,不能假装能核。
310
+ # 按用户回答原样上报,标 low(引擎侧仍会按表解析,未命中落未知池)。
311
+ return {"product": answer, "productName": answer, "source": "user_answer",
312
+ "confidence": "low", "rawText": answer,
313
+ "evidence": [{"reason": "catalog-unavailable", "rawText": answer}],
314
+ "ignored": None}
315
+ if not hit:
316
+ # 用户说了名录里没有的产品("智果"/"XYZ"/打错):**不拿原名硬提交**,
317
+ # 也不要自己猜最像的——把候选交回去,让模型按名录再问一次。
318
+ cands = search_products({"query": answer, "limit": 5})["candidates"]
319
+ return {"product": None, "productName": None, "source": "unknown",
320
+ "confidence": "low", "rawText": answer, "unmatched_answer": answer,
321
+ "candidates": cands,
322
+ "evidence": [{"reason": "unmatched-answer", "rawText": answer}],
323
+ "ignored": None}
324
+ name = hit[0].get("name")
325
+ return {"product": str(hit[0].get("id")), "productName": name,
326
+ "source": "user_answer", "confidence": "high", "rawText": answer,
327
+ "evidence": [{"product": name, "alias": "用户回答", "snippet": answer}],
328
+ "ignored": None}
329
+
330
+ result = _attrib.attribute(text, meta,
331
+ memory={k: v for k, v in mem.items()
332
+ if k in ("product", "productName", "alias",
333
+ "snippet", "at")},
334
+ binding=binding)
335
+ result["rawText"] = None
336
+ result["ignored"] = None
337
+ if result["source"] == "user_input":
338
+ result["confidence"] = "high"
339
+ return result
340
+ if result["source"] == "memory" and mem.get("product") and not mem.get("not_specified"):
341
+ result["confidence"] = "medium"
342
+ return result
343
+ if result["source"] == "install_binding":
344
+ result["confidence"] = "medium"
345
+ return result
346
+
347
+ not_specified = bool(params.get("productNotSpecified")) or bool(mem.get("not_specified"))
348
+ if not_specified:
349
+ # 用户明确说不知道:**不做任何猜测**(不按宿主产品兜底——那也是一次推断,
350
+ # 且产品会进引擎幂等域,错归代价比丢一条高)。交给调用方提示用户"缺产品不提交"。
351
+ pass
352
+ ev = list(result.get("evidence") or [])
353
+ if not_specified:
354
+ ev = [{"reason": "user-not-specified"}] + ev
355
+ return {"product": None, "productName": None, "source": "unknown",
356
+ "not_specified": not_specified,
357
+ "confidence": "low", "rawText": None,
358
+ "evidence": (ev or [{"reason": "no-evidence"}]),
359
+ "ignored": None}
360
+
361
+
362
+ def _require_product_or_ask(attr: dict, items: list, client_info: dict | None = None) -> None:
363
+ """缺产品且用户没说不知道 → 可执行错误:先问一次(D-product-ask-1)。
364
+
365
+ 错误里带候选(来自原话关键词),模型照着问一句就能补齐;不是"参考文档"。
366
+ """
367
+ if attr.get("product"):
368
+ return
369
+ # 追问轮次上限(2026-11-12 评审采纳):同一会话最多追问 2 次,之后明确终止——
370
+ # 避免"用户连续给两个都查不到的名字"时模型无限重问。
371
+ mem = _memory_get(client_info)
372
+ fails = int(mem.get("ask_failures") or 0) + 1
373
+ _memory_put(client_info, ask_failures=fails)
374
+ stop = fails > 2
375
+ tail = "(已追问 2 次仍未确认:别再问了,直接告诉用户这条反馈因为没有产品归属而不提交)"
376
+
377
+ if attr.get("unmatched_answer"):
378
+ cands = attr.get("candidates") or []
379
+ hint = "、".join(f"{c['name']}({c['id']})" for c in cands) or "(名录为空)"
380
+ raise ToolError(
381
+ f"用户说的产品「{attr['rawText']}」不在产品名录里,不能按它提交。"
382
+ f"请按名录再确认一次是哪一个:{hint};用户仍说不出来就说明这条先不提交。"
383
+ + (tail if stop else ""),
384
+ code=_UNRESOLVED_CODE)
385
+ if attr.get("not_specified"):
386
+ raise ToolError(
387
+ "用户没有提供产品,这条反馈**不能提交**:请告诉用户「没有产品归属的反馈我不提交,"
388
+ "因为不知道要转给哪个产品团队」,并请他补充是哪个产品;他仍不想说就说明这条先不提交。"
389
+ f"可选候选:{'、'.join(c['name'] + '(' + str(c['id']) + ')' for c in search_products({'query': '\n'.join(x[2] for x in items), 'limit': 5})['candidates'])}"
390
+ + (tail if stop else ""),
391
+ code=_UNRESOLVED_CODE)
392
+ if os.environ.get("VOD_ALLOW_UNKNOWN_PRODUCT") == "1":
393
+ # 旧客户端兼容(业界口径:可选字段 + 明确默认值,不做破坏性变更):
394
+ # 缺 product 的老客户端不让它直接失败,回执标 legacy_default/low,可追溯。
395
+ attr["source"] = "legacy_default"
396
+ attr["confidence"] = "low"
397
+ return
398
+ text = "\n".join(c for _i, _v, c in items)
399
+ cands = search_products({"query": text, "limit": 5})["candidates"]
400
+ hint = "、".join(f"{c['name']}({c['id']})" for c in cands) or "(名录未命中,可问用户直接说产品名)"
401
+ raise ToolError(
402
+ "这条反馈还没确定是哪个产品:请先问用户一次『这条是哪个产品的反馈?』,"
403
+ "把回答填进 product(产品名或 ID);用户明确说不知道/随便时,传 productNotSpecified=true。"
404
+ f"候选:{hint}", code=_UNRESOLVED_CODE)
405
+
406
+
407
+ def _attach_attribution(result: dict, attr: dict) -> None:
408
+ """回执留痕(D-product-ask-1):来源 + 置信 + 原始回答 + 证据。
409
+
410
+ productSource 枚举:user_input | user_answer | memory | install_binding |
411
+ host_default(后者恒 confidence=low,必须可人工修正)。
412
+ """
413
+ result["productSource"] = attr.get("source") or "unknown"
414
+ result["productConfidence"] = attr.get("confidence") or "low"
415
+ if attr.get("productName"):
416
+ result["productName"] = attr["productName"]
417
+ if attr.get("product") is not None:
418
+ result["productId"] = str(attr["product"])
419
+ if attr.get("rawText"):
420
+ result["productRawText"] = attr["rawText"]
421
+ if attr.get("evidence"):
422
+ result["productEvidence"] = attr["evidence"]
423
+
424
+
425
+ def _merge_ledger(extra: dict | None, attr: dict) -> dict:
426
+ """账本条目带上归因来源与证据:错归可回溯到用户原话(S99)。"""
427
+ out = dict(extra or {})
428
+ out["productSource"] = attr.get("source") or "unknown"
429
+ if attr.get("evidence"):
430
+ out["productEvidence"] = attr["evidence"]
431
+ return out
432
+
433
+
434
+ _ATTR_HISTORY_CAP = 10
435
+
436
+
437
+ def _remember_attribution(result: dict, client_info: dict | None = None) -> None:
438
+ """写记忆:只接受「字面证据唯一命中」,歧义/无证据/记忆本身不写(S100)。
439
+
440
+ 覆盖时留快照(D-attrib-B 追加,评审意见采纳项):旧条目进
441
+ attribution_history(cap 10,带 replacedAt),事后能回答「当时为什么归
442
+ 到 A 而不是 B」——单条记忆被覆盖后判据不可追是排障黑洞。
443
+ """
444
+ # 会话记忆(D-product-ask-1):只记「有证据/用户明确回答/用户说不知道」三种
445
+ src = result.get("source")
446
+ if result.get("product"):
447
+ _memory_put(client_info, ask_failures=0)
448
+ if src in ("user_input", "user_answer"):
449
+ _memory_put(client_info, product=result.get("product"),
450
+ productName=result.get("productName"),
451
+ alias=(result.get("evidence") or [{}])[0].get("alias"))
452
+ elif src == "host_default":
453
+ _memory_put(client_info, not_specified=True,
454
+ product=result.get("product"), productName=result.get("productName"))
455
+ mem = _attrib.remember_if_evidenced(result)
456
+ if not mem:
457
+ return
458
+ prev = _RT.get("attribution_memory") or {}
459
+ if prev and prev.get("product"):
460
+ hist = list(_RT.get("attribution_history") or [])
461
+ hist.append({**prev, "replacedAt": mem["at"]})
462
+ hist = hist[-_ATTR_HISTORY_CAP:]
463
+ _save_runtime({"attribution_history": hist})
464
+ _RT["attribution_history"] = hist # 进程内同步:否则同会话读不到新记忆
465
+ _save_runtime({"attribution_memory": mem})
466
+ _RT["attribution_memory"] = mem
224
467
 
225
468
 
226
469
  _SUBMIT_HOARDING = "/rest/developer/manager/hdvodmngservice/v1/external/voices"
@@ -340,6 +583,67 @@ def _flush_pending(product):
340
583
 
341
584
 
342
585
 
586
+ def _allowed_tags(product_id=None) -> set:
587
+ """分类白名单(引擎 meta.problemTypes,单一真源)。
588
+
589
+ 2026-11-12 引擎契约变更:problemTypes 不再随无参 meta 下发(那是"全部分类"
590
+ 的假全集),改为 `GET /external/meta?productId=<id>` 按产品下发——真源是
591
+ t_vod_problem_category 按 product_id 分组,不同产品的分类集不同。
592
+
593
+ 取不到(无 product_id / 老引擎 / 快照降级 / 该产品无分类)→ 空集=不知道
594
+ 白名单 → 不过滤:宁可放行也不误杀采集。
595
+ """
596
+ pid = str(product_id or "").strip()
597
+ if not pid or not pid.isdigit():
598
+ return set()
599
+ import time
600
+ cache = _RT.get("ptype_cache") or {}
601
+ now = time.time()
602
+ if now - float(cache.get("at") or 0) < _META_TTL and pid in (cache.get("by") or {}):
603
+ return set(cache["by"][pid] or [])
604
+ by = dict(cache.get("by") or {})
605
+ try:
606
+ path = f"{_META_PATH}?productId={pid}"
607
+ out = _http("GET", path, None, base=JAVA_BASE, key=_eff_key(), timeout=10)
608
+ data = out.get("data") or {}
609
+ types = [str(t) for t in (data.get("problemTypes") or []) if str(t).strip()]
610
+ by[pid] = types
611
+ cache = {"at": int(now), "by": by}
612
+ _save_runtime({"ptype_cache": cache})
613
+ _RT["ptype_cache"] = cache # 同进程后续调用要能命中,否则每次提交都外呼
614
+ return set(types)
615
+ except Exception:
616
+ # 任何取不到(网络/超时/引擎异常)= 不知道值域 → 不过滤,绝不阻断提交
617
+ return set(by.get(pid) or [])
618
+
619
+
620
+ _PROBLEM_TYPE_PREFIX = "problem_type:"
621
+
622
+
623
+ def _filter_tags(tags, allowed: set) -> tuple:
624
+ """tags 白名单过滤 → (kept, dropped)。
625
+
626
+ 引擎约定(ExternalVoicesServiceImpl.extractProblemType):分类标注写
627
+ `problem_type:<值>`,值域=meta.problemTypes(六类)。其它语义的 tag 不参与
628
+ 分类校验、原样保留;只有 problem_type 的值会被白名单过滤——脏值丢弃不拒收
629
+ 声音(对标 vod-skill 的 check_classification:分类必须存在于知识库)。
630
+ """
631
+ kept, dropped = [], []
632
+ for t in tags or []:
633
+ s = str(t).strip()
634
+ if not s:
635
+ continue
636
+ if allowed and s.startswith(_PROBLEM_TYPE_PREFIX):
637
+ val = s[len(_PROBLEM_TYPE_PREFIX):].strip()
638
+ if val not in allowed:
639
+ dropped.append(s)
640
+ continue
641
+ s = _PROBLEM_TYPE_PREFIX + val # 归一(去多余空白)
642
+ if s not in kept:
643
+ kept.append(s)
644
+ return kept, dropped
645
+
646
+
343
647
  def _collect_voice_items(params: dict) -> tuple[list, list]:
344
648
  """校验段:content 非空+≤2000 字(契约 maxLength,防超大 payload)。
345
649
  返回 (items[(index, voice, content)], rejected 明细)。"""
@@ -430,12 +734,15 @@ def submit_voices(params: dict, client_info: dict | None = None,
430
734
  """
431
735
  import uuid
432
736
  host = (client_info or {}).get("name") or "unknown-host"
433
- product, ignored_runtime = _resolve_product(params)
434
737
  global JAVA_KEY
435
738
  accepted, voice_ids, task_ids = 0, [], []
436
739
  items, rejected = _collect_voice_items(params)
437
740
  if not items:
438
741
  return {"accepted": 0, "voiceIds": [], "taskIds": [], "rejected": rejected}
742
+ # 归因(D-attrib-B):证据来自用户原话,模型自报不参战
743
+ # 归因(D-product-ask-1):身份/鉴权优先于产品追问,产品校验放在下面 key 守卫之后
744
+ attr = _attribute_product(items, params, client_info)
745
+ product = attr["product"]
439
746
 
440
747
  def _legacy_submit(i, v, content):
441
748
  """过渡回落:老链单条提交(提交即分析语义,仅 404 触发)。"""
@@ -462,8 +769,24 @@ def submit_voices(params: dict, client_info: dict | None = None,
462
769
  "<VOD key>(插件只搬运身份,不产生身份;落库与配额都在服务端)",
463
770
  code=-32012)
464
771
 
772
+ # 缺产品且用户没说不知道 → 可执行错误(先问一次),不许裸提交 UNKNOWN
773
+ _require_product_or_ask(attr, items, client_info)
465
774
  # ---- 主路径:囤积端点批式提交 ----
466
- body = {"voices": [_hoard_voice(v, content) for _, v, content in items]}
775
+ # 分类白名单按产品取(引擎 ?productId= 下发);product 非数字 id 时取不到→不过滤
776
+ allowed_tags = _allowed_tags(product)
777
+ hoard, invalid_tags = [], []
778
+ for i, v, content in items:
779
+ hv = _hoard_voice(v, content)
780
+ if hv.get("tags"):
781
+ kept, dropped = _filter_tags(hv["tags"], allowed_tags)
782
+ if kept:
783
+ hv["tags"] = kept
784
+ else:
785
+ hv.pop("tags", None)
786
+ if dropped:
787
+ invalid_tags.append({"index": i, "tags": dropped})
788
+ hoard.append(hv)
789
+ body = {"voices": hoard}
467
790
  if product: # 无归因不带 product(引擎 UNKNOWN 档),不本地拦截
468
791
  body["product"] = product
469
792
  out = None
@@ -514,13 +837,14 @@ def submit_voices(params: dict, client_info: dict | None = None,
514
837
  "analysis": "deferred", # 囤积语义明示(V6 运营批量消费)
515
838
  "path": "hoarding",
516
839
  "echo": _echo_plan(items, voice_ids)}
840
+ if invalid_tags: # 分类白名单外值被丢弃(不拒收声音,只丢 tag)
841
+ result["invalidTags"] = invalid_tags
517
842
  if out.get("productRegistered") is not None:
518
843
  result["productRegistered"] = out.get("productRegistered")
519
- # D-attrib-A 可观测:模型试图改归因留痕,不静默吞
520
- result["productSource"] = "install_binding"
521
- if ignored_runtime:
522
- result["ignoredRuntimeProduct"] = ignored_runtime
523
- _ledger_submit(items, voice_ids, task_ids, product, ledger_extra)
844
+ _attach_attribution(result, attr) # 来源+证据留痕(S99)
845
+ _remember_attribution(attr, client_info) # 会话记忆 + 审计(S95/S100)
846
+ _ledger_submit(items, voice_ids, task_ids, product,
847
+ _merge_ledger(ledger_extra, attr))
524
848
  result["pendingFlush"] = _flush_pending(product)
525
849
  return result
526
850
  # ---- 过渡回落:老链单条提交(仅囤积端点 404 触发) ----
@@ -557,7 +881,11 @@ def submit_voices(params: dict, client_info: dict | None = None,
557
881
  "taskIds": task_ids, "rejected": rejected,
558
882
  "path": "legacy-fallback",
559
883
  "echo": _echo_plan(items, voice_ids)}
560
- _ledger_submit(items, voice_ids, task_ids, product, ledger_extra)
884
+ _attach_attribution(result, attr)
885
+ if accepted:
886
+ _remember_attribution(attr, client_info)
887
+ _ledger_submit(items, voice_ids, task_ids, product,
888
+ _merge_ledger(ledger_extra, attr))
561
889
  result["pendingFlush"] = _flush_pending(product)
562
890
  return result
563
891
 
@@ -844,9 +1172,24 @@ def _drafts_load() -> dict:
844
1172
  def draft_voices(params: dict, client_info: dict | None = None) -> dict:
845
1173
  """两段式第一步:校验+暂存草稿+签发一次性令牌(不提交任何数据)。"""
846
1174
  import time as _time
847
- product, ignored_runtime = _resolve_product(params)
848
1175
  voices_in = params.get("voices", [])
1176
+ invalid_tags = []
849
1177
  clean = []
1178
+
1179
+ # 归因(D-attrib-B)前移:分类白名单按产品下发(?productId=),必须先知道
1180
+ # 产品才能取到该产品的分类集,否则过滤会拿到空集而静默失效。
1181
+ # 归因只看 content,不依赖 tags,前移不改变其它语义。
1182
+ _attr_items = []
1183
+ for i, v in enumerate(voices_in):
1184
+ _c = str(v.get("content", "")).strip()
1185
+ if _c:
1186
+ _attr_items.append((i, v, _c))
1187
+ attr = (_attribute_product(_attr_items, params, client_info)
1188
+ if _attr_items else {"product": None, "source": "unknown",
1189
+ "confidence": "low"})
1190
+ product = attr.get("product")
1191
+ allowed_tags = _allowed_tags(product)
1192
+
850
1193
  for i, v in enumerate(voices_in):
851
1194
  content = str(v.get("content", "")).strip()
852
1195
  if not content:
@@ -855,7 +1198,11 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
855
1198
  raise ToolError(f"第 {i + 1} 条 content 超 2000 字({len(content)})", code=-32602)
856
1199
  item = {"content": content}
857
1200
  if v.get("tags"):
858
- item["tags"] = v["tags"]
1201
+ kept, dropped = _filter_tags(v["tags"], allowed_tags)
1202
+ if kept:
1203
+ item["tags"] = kept
1204
+ if dropped:
1205
+ invalid_tags.append({"index": i, "tags": dropped})
859
1206
  if v.get("userType"):
860
1207
  item["userType"] = v["userType"]
861
1208
  # D-followup-impl-2:追问补充随 draft 暂存(commit 复用 payload 原样上送),
@@ -864,6 +1211,7 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
864
1211
  clean.append(item)
865
1212
  if not clean:
866
1213
  raise ToolError("voices 为必填且至少 1 条", code=-32602)
1214
+ _remember_attribution(attr, client_info)
867
1215
 
868
1216
  import secrets
869
1217
  draft_id = "draft_" + secrets.token_hex(8)
@@ -884,16 +1232,16 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
884
1232
  # 风险,换断回合可续:agent 回合中断后凭 draftId 即可恢复提交(此前
885
1233
  # approvalToken 只存在于 draft 响应文本,回合断即丢失,只能重开草稿)
886
1234
  "token": token,
887
- "product": product, "createdAt": _time.strftime("%Y-%m-%dT%H:%M:%S"),
1235
+ "product": product, "productSource": attr.get("source"),
1236
+ "productEvidence": attr.get("evidence") or [],
1237
+ "createdAt": _time.strftime("%Y-%m-%dT%H:%M:%S"),
888
1238
  "expiresAt": _time.time() + _DRAFT_TTL,
889
1239
  }
890
1240
  while len(store) > _DRAFT_CAP: # 环形:最旧先淘汰
891
1241
  store.pop(next(iter(store)))
892
1242
  _save_runtime({_DRAFT_KEY: store})
893
1243
 
894
- if ignored_runtime: # D-attrib-A 可观测:模型试图改归因留痕
895
- _warn(f"draft: runtime product 被忽略(绑定权威): {ignored_runtime}")
896
- return {
1244
+ out = {
897
1245
  "draftId": draft_id,
898
1246
  "approvalToken": token,
899
1247
  "payloadSha256": payload_sha,
@@ -903,6 +1251,10 @@ def draft_voices(params: dict, client_info: dict | None = None) -> dict:
903
1251
  "「确认提交吗」。用户明确同意前禁止调用 vod_commit_voices;"
904
1252
  "不同意则停(草稿 10 分钟后自动作废)。"),
905
1253
  }
1254
+ _attach_attribution(out, attr) # 草稿阶段也让归因来源可审(commit 回执沿用)
1255
+ if invalid_tags:
1256
+ out["invalidTags"] = invalid_tags
1257
+ return out
906
1258
 
907
1259
 
908
1260
  def commit_voices(params: dict, client_info: dict | None = None) -> dict:
@@ -964,6 +1316,7 @@ def retrieve_skill(params: dict, client_info: dict | None = None) -> dict:
964
1316
 
965
1317
 
966
1318
  _HANDLERS = {
1319
+ "vod_search_products": search_products,
967
1320
  "vod_check_update": check_update,
968
1321
  "vod_list_skills": list_skills,
969
1322
  "vod_retrieve_skill": retrieve_skill,
@@ -4,8 +4,10 @@
4
4
  agent 发版管理,D-key-guard-3②)。所以升级动作永远是 install/update,工具
5
5
  只负责回答"我这台是不是旧了",绝不下载、不解包、不改盘。
6
6
 
7
- 三个约束:
7
+ 四个约束:
8
8
  - 一次会话只打扰一次 + 拒绝后冷却 3 天(devkit 同款);状态落 runtime.json。
9
+ - **skip-version**(devkit update-skip 裁剪版):用户明确说"这个版本不要提醒"时记
10
+ 住该版本号,只压这一个版本——下个版本照常提醒(永久静音的危害大于打扰)。
9
11
  - 网络失败静默降级(离线/内网环境必须可用),不阻塞任何采集链。
10
12
  - preset 形态完全不发外呼。
11
13
  """
@@ -53,6 +55,8 @@ def check(params: dict | None = None) -> dict:
53
55
  from vod_mcp import __version__, tools
54
56
  params = params or {}
55
57
  dismiss = bool(params.get("dismiss"))
58
+ skip = bool(params.get("skip"))
59
+ clear_skip = bool(params.get("clearSkip"))
56
60
  cfg = tools._runtime_cfg()
57
61
  state = cfg.get("update_check") or {}
58
62
  now = _now()
@@ -63,6 +67,25 @@ def check(params: dict | None = None) -> dict:
63
67
  "note": "本装机为产品分发形态(preset),版本随 agent 发版管理,"
64
68
  "不做外呼检查。升级请联系产品提供方。"}
65
69
 
70
+ if clear_skip:
71
+ tools._save_runtime({"update_check": {k: v for k, v in state.items()
72
+ if k != "skipVersion"}})
73
+ return {"currentVersion": __version__, "latestVersion": state.get("latestVersion"),
74
+ "updateAvailable": False, "checked": False,
75
+ "note": "已清除版本跳过设置,下次检查恢复正常提醒。"}
76
+
77
+ if skip:
78
+ latest_seen = state.get("latestVersion") or _fetch_latest()
79
+ if not latest_seen:
80
+ return {"currentVersion": __version__, "latestVersion": None,
81
+ "updateAvailable": False, "checked": False,
82
+ "note": "版本检查不可达,无法记录跳过版本;不影响采集,稍后重试即可。"}
83
+ tools._save_runtime({"update_check": {**state, "skipVersion": latest_seen}})
84
+ return {"currentVersion": __version__, "latestVersion": latest_seen,
85
+ "updateAvailable": False, "checked": False,
86
+ "note": f"已跳过 v{latest_seen}:只压这一个版本,下个版本仍会提醒"
87
+ f"(clearSkip=true 可撤销)。"}
88
+
66
89
  dismissed_until = state.get("dismissedUntil")
67
90
  if dismiss:
68
91
  until = (now + datetime.timedelta(days=DISMISS_DAYS)).date().isoformat()
@@ -95,11 +118,16 @@ def check(params: dict | None = None) -> dict:
95
118
  tools._save_runtime({"update_check": {**state, "checkedAt": now.isoformat(
96
119
  timespec="seconds"), "latestVersion": latest}})
97
120
  newer = _version_tuple(latest) > _version_tuple(__version__)
121
+ skipped = bool(state.get("skipVersion")) and state["skipVersion"] == latest
98
122
  out = {"currentVersion": __version__, "latestVersion": latest,
99
- "updateAvailable": newer, "checked": True,
123
+ "updateAvailable": newer and not skipped, "checked": True,
100
124
  "note": ("有新版本可用:重跑 install(幂等原位更新)或 vod-devkit update。"
101
125
  "用户不想被打扰时用 dismiss=true 跳过 3 天。") if newer else
102
126
  "已是最新版本。"}
103
- if newer:
127
+ if skipped and newer:
128
+ out["skippedVersion"] = latest
129
+ out["note"] = (f"v{latest} 已被用户跳过(skip-version),本期不提醒;"
130
+ f"clearSkip=true 可恢复。")
131
+ if out["updateAvailable"]:
104
132
  out["upgradeCommand"] = "vod-devkit update # 或重跑 install(同一行装命令)"
105
133
  return out