vod-devkit 0.4.4 → 0.5.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 (81) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/QUICKSTART.md +1 -1
  3. package/README.en.md +190 -56
  4. package/README.md +210 -56
  5. package/bin/vod-devkit +502 -460
  6. package/contract/tools.schema.json +114 -7
  7. package/integrations/codeartsdoer/host.json +11 -0
  8. package/integrations/codex/host.json +20 -0
  9. package/integrations/dsh/host.json +15 -0
  10. package/integrations/hermes/host.json +20 -0
  11. package/integrations/opencode/command/vod-doctor.md +10 -0
  12. package/integrations/opencode/host.json +28 -0
  13. package/package.json +13 -10
  14. package/plugins/vod-devkit/.codex-plugin/plugin.json +1 -1
  15. package/plugins/vod-devkit/build-info.json +3 -3
  16. package/plugins/vod-devkit/skills/vod-core/SKILL.md +43 -15
  17. package/plugins/vod-devkit/skills/vod-core/references/acceptance-criteria.md +9 -0
  18. package/plugins/vod-devkit/skills/vod-core/references/verification-method.md +29 -0
  19. package/plugins/vod-devkit/skills/vod-feedback-collect/SKILL.md +57 -11
  20. package/plugins/vod-devkit/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  21. package/plugins/vod-devkit/skills/vod-feedback-collect/references/verification-method.md +31 -0
  22. package/plugins/vod-devkit/skills/vod-problem-classification-rules/SKILL.md +3 -1
  23. package/plugins/vod-devkit/skills/vod-scoring-rules/SKILL.md +22 -1
  24. package/plugins/vod-devkit/vod_mcp/__init__.py +1 -1
  25. package/plugins/vod-devkit/vod_mcp/attribution.py +378 -0
  26. package/plugins/vod-devkit/vod_mcp/config_forms.py +154 -0
  27. package/plugins/vod-devkit/vod_mcp/guardrails.py +25 -0
  28. package/plugins/vod-devkit/vod_mcp/host_adapters/__init__.py +26 -0
  29. package/plugins/vod-devkit/vod_mcp/host_adapters/base.py +73 -0
  30. package/plugins/vod-devkit/vod_mcp/host_adapters/codearts.py +57 -0
  31. package/plugins/vod-devkit/vod_mcp/host_adapters/codex.py +209 -0
  32. package/plugins/vod-devkit/vod_mcp/host_adapters/dsh.py +176 -0
  33. package/plugins/vod-devkit/vod_mcp/host_adapters/generic.py +132 -0
  34. package/plugins/vod-devkit/vod_mcp/host_adapters/hermes.py +76 -0
  35. package/plugins/vod-devkit/vod_mcp/host_adapters/opencode.py +52 -0
  36. package/plugins/vod-devkit/vod_mcp/hosts.py +100 -0
  37. package/plugins/vod-devkit/vod_mcp/packs.py +19 -3
  38. package/plugins/vod-devkit/vod_mcp/payload.py +174 -0
  39. package/plugins/vod-devkit/vod_mcp/remote_app.py +100 -0
  40. package/plugins/vod-devkit/vod_mcp/server.py +43 -16
  41. package/plugins/vod-devkit/vod_mcp/skills_registry.py +124 -0
  42. package/plugins/vod-devkit/vod_mcp/tools.py +455 -55
  43. package/plugins/vod-devkit/vod_mcp/transport_remote.py +289 -0
  44. package/plugins/vod-devkit/vod_mcp/update_check.py +133 -0
  45. package/skills/vod-core/SKILL.md +43 -15
  46. package/skills/vod-core/references/acceptance-criteria.md +9 -0
  47. package/skills/vod-core/references/verification-method.md +29 -0
  48. package/skills/vod-feedback-collect/SKILL.md +57 -11
  49. package/skills/vod-feedback-collect/references/acceptance-criteria.md +28 -0
  50. package/skills/vod-feedback-collect/references/verification-method.md +31 -0
  51. package/skills/vod-problem-classification-rules/SKILL.md +3 -1
  52. package/skills/vod-scoring-rules/SKILL.md +22 -1
  53. package/vod_mcp/__init__.py +1 -1
  54. package/vod_mcp/attribution.py +378 -0
  55. package/vod_mcp/config_forms.py +154 -0
  56. package/vod_mcp/guardrails.py +25 -0
  57. package/vod_mcp/host_adapters/__init__.py +26 -0
  58. package/vod_mcp/host_adapters/__pycache__/__init__.cpython-314.pyc +0 -0
  59. package/vod_mcp/host_adapters/__pycache__/base.cpython-314.pyc +0 -0
  60. package/vod_mcp/host_adapters/__pycache__/codearts.cpython-314.pyc +0 -0
  61. package/vod_mcp/host_adapters/__pycache__/codex.cpython-314.pyc +0 -0
  62. package/vod_mcp/host_adapters/__pycache__/dsh.cpython-314.pyc +0 -0
  63. package/vod_mcp/host_adapters/__pycache__/generic.cpython-314.pyc +0 -0
  64. package/vod_mcp/host_adapters/__pycache__/hermes.cpython-314.pyc +0 -0
  65. package/vod_mcp/host_adapters/__pycache__/opencode.cpython-314.pyc +0 -0
  66. package/vod_mcp/host_adapters/base.py +73 -0
  67. package/vod_mcp/host_adapters/codearts.py +57 -0
  68. package/vod_mcp/host_adapters/codex.py +209 -0
  69. package/vod_mcp/host_adapters/dsh.py +176 -0
  70. package/vod_mcp/host_adapters/generic.py +132 -0
  71. package/vod_mcp/host_adapters/hermes.py +76 -0
  72. package/vod_mcp/host_adapters/opencode.py +52 -0
  73. package/vod_mcp/hosts.py +100 -0
  74. package/vod_mcp/packs.py +19 -3
  75. package/vod_mcp/payload.py +174 -0
  76. package/vod_mcp/remote_app.py +100 -0
  77. package/vod_mcp/server.py +43 -16
  78. package/vod_mcp/skills_registry.py +124 -0
  79. package/vod_mcp/tools.py +455 -55
  80. package/vod_mcp/transport_remote.py +289 -0
  81. package/vod_mcp/update_check.py +133 -0
@@ -0,0 +1,28 @@
1
+ # 验收标准(vod-feedback-collect)
2
+
3
+ 上线/改版前逐条勾选;每条都指向可执行的验证入口(见 references/verification-method.md)。
4
+
5
+ ## 功能
6
+
7
+ - [ ] content = 用户原话逐字(含语气词与原标点),模型不补写、不概括
8
+ - [ ] 用户明确同意才提交;"用户说了一条抱怨"不构成同意
9
+ - [ ] 回执 `echo.contents` 原样转述,每条以「已收录原话:」开头
10
+ - [ ] 固定追问至多一次、逐字使用;答"没有/跳过"=两字段不上送
11
+ - [ ] 电话/路径类敏感内容按 policy 处理(当前策略=拒收,不脱敏)
12
+ - [ ] 无通道场景落盘 `pending-feedback.jsonl`,恢复后自动补交,用户侧只说人话
13
+
14
+ ## 归因(D-attrib-B)
15
+
16
+ - [ ] 字面证据唯一命中才采信;多命中落 UNKNOWN 且保留全部片段
17
+ - [ ] 记忆只在 0 命中时启用(30 分钟窗口),新证据无条件覆盖
18
+ - [ ] 模型自报 product 不采信(仅回执 `ignoredRuntimeProduct`)
19
+
20
+ ## 传输面
21
+
22
+ - [ ] stdio 面:两段式工具可用时走 draft→commit
23
+ - [ ] 远程面:无 draft/commit/list_submitted 时不承诺两段式与本机账本查询
24
+
25
+ ## 非功能
26
+
27
+ - [ ] `SKILL.md` ≤ 500 行;改动后四个宿主装机副本已刷新(md5 对上)
28
+ - [ ] `tests/test_skill_structure.py` 与 `sync_case_roster.py --check` 全绿
@@ -0,0 +1,31 @@
1
+ # 验证方法(vod-feedback-collect)
2
+
3
+ 本文只给**验证入口**:断言细节以 `docs/proposal.md` 的用例与 `tests/` 的实现为准,
4
+ 不在本文件复制断言(避免第二真源)。改技能正文后按本文件跑一遍。
5
+
6
+ ## 1. 静态门禁(本地/CI,秒级)
7
+
8
+ ```bash
9
+ python3 -m pytest tests/test_desc_budget.py tests/test_attribution.py \
10
+ tests/test_pending_feedback.py tests/test_two_phase.py -q
11
+ python3 -m pytest tests/test_skill_structure.py -q # frontmatter/触发词/路由一致性
12
+ python3 scripts/sync_case_roster.py --check
13
+ ```
14
+
15
+ 期望:全绿;技能文件与 `plugins/vod-devkit/skills/` 副本逐字节一致(CI 双副本 diff)。
16
+
17
+ ## 2. 会话内自检(模型侧,无外部依赖)
18
+
19
+ - 可用工具里有 `vod_draft_voices` → 两段式;没有 → 单发 `vod_submit_voices`(远程面)
20
+ - 回执必须带 `echo.contents`,逐字转述;被改写即为失败
21
+ - 归因看 `productSource`:`user_input`/`memory`/`install_binding`/`unknown` 之一
22
+ - 多产品命中(`unknown` + evidence>1)不得自行择一提交
23
+
24
+ ## 3. 端到端(真宿主)
25
+
26
+ 对应 `docs/decisions.md` 里的四宿主验证配方:装新 skill 副本 → 新会话说一条抱怨 →
27
+ 查账本 voiceId 与引擎行;行为类回归见 `scripts/e2e_behavior.py`(仅本机运行)。
28
+
29
+ ## 关联用例
30
+
31
+ 话术 S49-S53;追问与拼接 S63-S73;无通道 pending S87-S90;归因链 S91-S100。
@@ -1,7 +1,9 @@
1
1
  ---
2
2
  name: vod-problem-classification-rules
3
3
  description: VOD 问题分类规则(引擎 v2.2 真实口径)— 六类定义、判定细节、LLM 分类流程。真源=workflow/src/n01_classify.py(VOD-Project 2bb3fc82 实测核对)。
4
- version: 2
4
+ tags: [vod, classification, rules]
5
+ metadata:
6
+ version: 2
5
7
  ---
6
8
 
7
9
  # VOD 问题分类规则(引擎 v2 口径)
@@ -1,7 +1,9 @@
1
1
  ---
2
2
  name: vod-scoring-rules
3
3
  description: VOD 评分规则(引擎 v2 真实公式)— 四项加法、上下限、优先级映射。真源=workflow/src/workflow_v2.py(VOD-Project 2bb3fc82 实测核对)。
4
- version: 2
4
+ tags: [vod, scoring, rules]
5
+ metadata:
6
+ version: 2
5
7
  ---
6
8
 
7
9
  # VOD 评分规则(引擎 v2 口径)
@@ -22,6 +24,25 @@ version: 2
22
24
  | 功能重要性分 | 高=1.5 / 中=1.0 / 低=0.5(无一级特性归 0) |
23
25
  | 场景范围分 / 友商对比分 | 按分组与竞品数据计算 |
24
26
 
27
+ ## 等级 L1-L5 定义(引擎 LEVEL_CRITERIA,按易用性维度)
28
+
29
+ > 等级不是一把全局尺子:引擎按「易用性分类」的七个维度分别定义 L1-L5
30
+ > (真源=workflow/src/llm_analyzer.py LEVEL_CRITERIA;产品咨询类不打等级,
31
+ > 填「不适用」)。判等级前先确定维度,再取该维度的档位。
32
+
33
+ | 维度 | L1不可用 | L2难用 | L3可用 | L4易用 | L5好用 |
34
+ |---|---|---|---|---|---|
35
+ | 易学习 | 无入门文档无基础概念 | 文档零散缺实操引导 | 有基础入门能看懂流程 | 结构清晰有新手路径 | 体系完整交互式引导 |
36
+ | 易部署 | 安装失败依赖缺失 | 步骤繁琐配置复杂无指引 | 可手动完成安装初始化 | 流程简化环境自适配 | 全自动检测静默部署 |
37
+ | 易开发 | 核心开发功能异常 | 配置晦涩调试困难 | 基础流程可跑通 | 模板丰富智能提示 | AI辅助生成全流程自动化 |
38
+ | 易迁移 | 迁移失败代码丢失 | 步骤复杂冲突频发 | 可完成基础迁入 | 向导式迁移冲突提示 | 一键全量迁移完整同步 |
39
+ | 易维护 | 频繁崩溃无排查线索 | 故障频发报错无解 | 日常稳定小问题可自查 | 报错清晰权限版本简洁 | 智能诊断主动预警 |
40
+ | 易演进 | 缺失核心刚需功能 | 设计不合理高频功能缺失 | 满足最低业务诉求 | 贴合习惯持续迭代 | 前瞻规划可定制扩展 |
41
+ | 易社区 | 无入口无求助渠道 | 冷清无人响应 | 可发帖少量内容 | 分类清晰资源丰富 | 智能匹配生态活跃 |
42
+
43
+ 采集用法提醒:等级由引擎判定,插件只做预分类提示——不要向用户宣称
44
+ 「这条是 L1」,只可解释「等级越高越优先」这层语义。
45
+
25
46
  ## 上下限(引擎代码,两条都要记)
26
47
 
27
48
  - **重点问题:clamp 1.0 ~ 10.5**
@@ -5,7 +5,7 @@
5
5
  2. 外部无 DB 直连路径(护栏 deny 兜底)
6
6
  3. 任务 ID 是唯一对账主键,写类工具返回一律携带
7
7
  """
8
- __version__ = "0.4.4"
8
+ __version__ = "0.5.1"
9
9
  # 默认上游:VOD 测试环境。外部用户本机无 VOD,回环默认值=装完即坏;
10
10
  # 生产地址定型后只改这一处(tools.py 与 bin/vod-devkit 共用本常量)。
11
11
  DEFAULT_JAVA_BASE = "https://vod-dev.topxtopx.com"
@@ -0,0 +1,378 @@
1
+ """运行期归因(D-attrib-B,2026-11-11 负责人拍板 A/A/A/A)。
2
+
3
+ 产品不再由安装/启动配置决定:从**用户原话**里解析产品名录别名,唯一命中才
4
+ 采信;0 命中依次回落到记忆(短 TTL)与安装先验;多产品命中=歧义,一律
5
+ UNKNOWN 并保留全部命中片段(宁可人工归因,不可公开错归)。
6
+
7
+ 本模块只做纯计算(索引/匹配/优先级链),不读写 runtime.json——持久化归
8
+ tools 层,便于单测零副作用。
9
+
10
+ 数据源单一真源=引擎 meta(GET /external/meta):
11
+ productCatalog [{id,name}] 提交主键(t_vod_product)与产品名
12
+ products [显示名] codearts 之类的短码由显示名大写派生
13
+
14
+ **2026-11-12 变更(引擎侧 meta 契约收紧)**:
15
+ 引擎已删除 `nameAliases` / `aliases` 两个下发字段(理由:编造数据、无消费方、
16
+ 且掩盖主数据问题)。别名能力改为**本地派生 + 显式品牌俗称表**,不再依赖后端下发:
17
+
18
+ ① 规则派生(从 productCatalog 的真实名字推导,不是编造):
19
+ 原名 / 大小写不敏感 / 去空格("AI 开发者空间"→"AI开发者空间")/
20
+ 括号与前缀剥离的核心词("对象存储服务 OBS"→"OBS")/
21
+ 中文长名里的拉丁片段("软件开发生产线 CodeArts"→"CodeArts")
22
+ ② BRAND_ALIASES(下方常量):人工确认的品牌俗称,只放**无法从表名推导**
23
+ 且用户口语高频的词(如「码道」= CodeArts 中文品牌名)。
24
+ 这是本地维护的已知清单,诚实标注为本地数据,不再假装来自后端。
25
+
26
+ `problemTypes` 同理:引擎改为 `?productId=` 按产品下发,不带参数时不含该键。
27
+ 分类白名单的获取见 tools._allowed_tags(product_id)。
28
+ """
29
+ import re
30
+
31
+ MEM_TTL = 30 * 60 # 记忆窗口:负责人拍板 P2-A(机器级 + 30 分钟)
32
+
33
+ _SNIPPET_PAD = 20
34
+ _SNIPPET_MAX = 80
35
+ _BOUNDARY = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")
36
+ _SHORT_ALIAS_MAX = 5
37
+
38
+ # 品牌俗称表(本地维护,2026-11-12 用户拍板方案 b):
39
+ # 目标产品名(必须能在 canvas productCatalog 里找到,大小写不敏感匹配)→ 口语俗称列表
40
+ # 收录标准(缺一不可):
41
+ # ① 无法从表内登记名通过规则派生(否则交给规则)
42
+ # ② 用户原话里高频真实出现(有真机语料支撑)
43
+ # ③ 品牌官方称谓,不是臆造简称
44
+ # 空表也安全:派生规则独立工作,本表只是补口语盲区。
45
+ BRAND_ALIASES = {
46
+ "CodeArts": ["码道", "华为云码道"],
47
+ }
48
+
49
+ # 派生核心词时的中文尾缀噪音("对象存储服务 OBS" → 取拉丁 "OBS")
50
+ _LATIN_RUN = re.compile(r"[A-Za-z][A-Za-z0-9 ._-]*[A-Za-z0-9]|[A-Za-z]")
51
+
52
+
53
+ def _is_ascii(text: str) -> bool:
54
+ return all(ord(c) < 128 for c in text)
55
+
56
+
57
+ def _resolve_name(raw: str, names: list) -> str:
58
+ """别名表里的枚举键(CODEARTS)→ catalog/显示名(CodeArts)。"""
59
+ low = str(raw or "").strip().lower()
60
+ for n in names:
61
+ if str(n).lower() == low:
62
+ return str(n)
63
+ return str(raw or "").strip()
64
+
65
+
66
+ def _derive_aliases(name: str) -> list:
67
+ """从单个登记名派生可用别名(全部来自真实名字,非编造)。
68
+
69
+ "AI 开发者空间" → 原名 / 去空格 "AI开发者空间" / 拉丁 "AI"(过短,弃用)
70
+ "对象存储服务 OBS" → 原名 / 拉丁核心 "OBS"
71
+ "软件开发生产线 CodeArts" → 原名 / 拉丁核心 "CodeArts"
72
+ "DataArts Studio" → 原名 / 去空格 / "DataArts"(拉丁首段)
73
+ 过短(<5)的拉丁别名会被 _ascii_hits 的精确大小写规则保护,但仍可能撞词,
74
+ 所以这里只保留长度>=3 的拉丁片段,且不做大写化(保留原样)。
75
+ """
76
+ raw = str(name or "").strip()
77
+ if not raw:
78
+ return []
79
+ out = [raw]
80
+ compact = re.sub(r"\s+", "", raw)
81
+ if compact and compact != raw:
82
+ out.append(compact)
83
+ # 拉丁片段:整串是纯拉丁时取首段与全串;含中文时取最长的拉丁连续段
84
+ runs = [m.group(0).strip() for m in _LATIN_RUN.finditer(raw)]
85
+ runs = [r for r in runs if len(r) >= 3]
86
+ if runs:
87
+ out.extend(runs)
88
+ if " " in raw and runs[0] != raw:
89
+ head = runs[0].split()[0] if runs[0].split() else runs[0]
90
+ if len(head) >= 3:
91
+ out.append(head)
92
+ # 短拉丁名的大小写变体:表里存 "Maas"、用户写 "MaaS"(真实高频差异)。
93
+ # _ascii_hits 对 <5 字符的短别名走精确大小写,只靠原样会漏。
94
+ # 关键限制:**全大写缩写(OBS/CCE/EIP)不生成小写变体**——用户不会把小写
95
+ # "obs" 当产品名,而 "obs://bucket" 这类 URL/路径反会被误命中(S93 铁律)。
96
+ # 只对非全大写的混写名(Maas/CodeArts)补变体。
97
+ for run in list(runs):
98
+ if len(run) <= 8 and _is_ascii(run) and run != run.upper():
99
+ for variant in (run.lower(), run.capitalize()):
100
+ if variant != run:
101
+ out.append(variant)
102
+ # 去重、保序
103
+ seen, uniq = set(), []
104
+ for a in out:
105
+ if a and a not in seen:
106
+ seen.add(a)
107
+ uniq.append(a)
108
+ return uniq
109
+
110
+
111
+ def build_alias_index(meta: dict) -> list:
112
+ """meta → 别名条目列表(按别名长度降序,长别名优先)。
113
+
114
+ 真机实锤的两个坑(2026-11-11 用线上 meta 实测):
115
+ ① catalog 名与展示名不一致:t_vod_product 里 MaaS 存成 "Maas"、OBS 存成
116
+ "对象存储服务 OBS",而 meta.products 是展示名 "MaaS"/"OBS"——只按名字
117
+ 对不齐会把同一产品拆成两条(一条有 id 一条没有)。
118
+ ② 别名去重不能用大小写不敏感:短别名按大小写精确匹配,"MaaS" 会被
119
+ "Maas" 顶掉。
120
+ 做法:以展示名为产品标签,用**规则派生 + BRAND_ALIASES**把多种写法桥接,
121
+ 再按 catalog id 合并成一条;去重键保留大小写(alias 原样)。
122
+
123
+ 2026-11-12:引擎已不再下发 nameAliases/aliases,改用 _derive_aliases + 本地表。
124
+ """
125
+ meta = meta or {}
126
+ catalog = meta.get("catalog") or []
127
+ products = [str(p) for p in (meta.get("products") or []) if p]
128
+ id_by_lower = {}
129
+ for item in catalog:
130
+ name = str(item.get("name") or "").strip()
131
+ if name:
132
+ id_by_lower[name.lower()] = str(item.get("id")) if item.get("id") is not None else None
133
+
134
+ canon: dict[str, dict] = {} # lower(name) -> {"label","id","aliases":set(),"brand":bool}
135
+
136
+ def _slot(name, brand):
137
+ key = str(name).strip().lower()
138
+ cur = canon.get(key)
139
+ if cur is None:
140
+ canon[key] = {"label": str(name).strip(), "id": None,
141
+ "aliases": set(), "brand": brand, "derived": set()}
142
+ cur = canon[key]
143
+ elif brand and not cur["brand"]:
144
+ cur["label"], cur["brand"] = str(name).strip(), True
145
+ cur["aliases"].add(str(name).strip())
146
+ return cur
147
+
148
+ for name in products: # 展示名优先成为标签
149
+ _slot(name, True)
150
+ for item in catalog: # catalog 名补位(无展示名时用库内名)
151
+ if item.get("name"):
152
+ _slot(item["name"], False)
153
+
154
+ # ① 规则派生:每个登记名派生多种写法(去空格 / 拉丁核心词 / 大小写变体)
155
+ # 注意:登记名「原样」不标 caseless——它由 _ascii_hits 的短别名精确规则保护
156
+ # (OBS 不能因此变成小写 obs 而命中 "obs://bucket",S93 铁律)。
157
+ for slot in list(canon.values()):
158
+ raw_label = slot["label"]
159
+ for derived in _derive_aliases(raw_label):
160
+ slot["aliases"].add(derived)
161
+ if derived != raw_label:
162
+ slot["derived"].add(derived)
163
+
164
+ # ② 品牌俗称表:把无法从表名推导的口语词挂到目标产品上
165
+ for target_name, colloquials in (BRAND_ALIASES or {}).items():
166
+ slot = canon.get(str(target_name).lower())
167
+ if slot is None:
168
+ # 目标产品不在本次 catalog(引擎换库/改名):别名不落地,避免指向
169
+ # 不存在的 id。宁可丢俗称,也不产生错归。
170
+ continue
171
+ for word in (colloquials or []):
172
+ if word:
173
+ slot["aliases"].add(str(word).strip())
174
+
175
+ # ③ 兼容:若引擎仍下发旧字段(回滚场景),继续采纳,避免双向改造期丢能力
176
+ for key, aliases in (meta.get("nameAliases") or {}).items():
177
+ aliases = [str(a) for a in (aliases or []) if a]
178
+ target = canon.get(str(key).lower())
179
+ if target is None:
180
+ for a in aliases:
181
+ if a.lower() in canon:
182
+ target = canon[a.lower()]
183
+ break
184
+ if target is None:
185
+ target = _slot(key, True)
186
+ for a in aliases:
187
+ target["aliases"].add(a)
188
+ target["aliases"].add(str(key))
189
+ for key, target_name in (meta.get("aliases") or {}).items():
190
+ slot = canon.get(str(target_name).lower())
191
+ if slot is None: # 目录/展示名都没有该目标:按别名目标建槽,别丢别名
192
+ slot = _slot(target_name, False)
193
+ slot["aliases"].add(str(key))
194
+
195
+ for slot in canon.values(): # 名字/别名任一命中 catalog → 拿 id
196
+ for alias in list(slot["aliases"]) + [slot["label"]]:
197
+ if alias.lower() in id_by_lower:
198
+ slot["id"] = id_by_lower[alias.lower()]
199
+ break
200
+
201
+ merged: list = [] # 同 id 合并(展示名那条为准)
202
+ by_id: dict = {}
203
+ for slot in canon.values():
204
+ pid = slot["id"]
205
+ if pid is not None and pid in by_id:
206
+ by_id[pid]["aliases"] |= slot["aliases"]
207
+ continue
208
+ if pid is not None:
209
+ by_id[pid] = slot
210
+ merged.append(slot)
211
+
212
+ entries: list = []
213
+ seen: set = set()
214
+ for slot in merged:
215
+ for alias in slot["aliases"]:
216
+ key = (slot["label"].lower(), alias) # 大小写敏感:保留 MaaS/Maas 两种写法
217
+ if not alias or key in seen:
218
+ continue
219
+ seen.add(key)
220
+ entries.append({"product": slot["label"], "id": slot["id"], "alias": alias,
221
+ # 派生写法允许大小写不敏感;但**全大写缩写永不 caseless**——
222
+ # "对象存储服务 OBS" 派生的 OBS 曾因此命中 "obs://bucket" 与
223
+ # "/obs/bin"(2026-11-12 实测,S93 铁律被破)
224
+ "caseless": (alias in (slot.get("derived") or set())
225
+ and alias != alias.upper())})
226
+ entries.sort(key=lambda e: len(e["alias"]), reverse=True)
227
+ return entries
228
+
229
+
230
+ def _ascii_hits(text: str, alias: str, caseless: bool = False) -> list:
231
+ """拉丁别名:词边界 + 大小写策略(短别名精确大小写)。
232
+
233
+ caseless=True 用于**从登记名派生**的写法(如表里 "Maas" 派生的 "MaaS"):
234
+ 这类变体本就来自同一登记名,允许大小写不敏感,否则用户写 "MaaS" 会漏。
235
+ 手写简称(meta 下发/品牌表)仍走精确匹配,避免 obs≠OBS 之类误伤。
236
+ """
237
+ exact_case = (not caseless) and len(alias) < _SHORT_ALIAS_MAX
238
+ hay = text if exact_case else text.lower()
239
+ needle = alias if exact_case else alias.lower()
240
+ out: list = []
241
+ start = 0
242
+ while True:
243
+ i = hay.find(needle, start)
244
+ if i < 0:
245
+ return out
246
+ j = i + len(needle)
247
+ ok_before = i == 0 or hay[i - 1] not in _BOUNDARY
248
+ ok_after = True
249
+ if j < len(hay):
250
+ nxt = hay[j]
251
+ if nxt in _BOUNDARY:
252
+ ok_after = False
253
+ elif nxt == "." and j + 1 < len(hay) and hay[j + 1].isalnum():
254
+ ok_after = False # codearts.yaml 这类文件名不是产品名
255
+ if ok_before and ok_after:
256
+ prev = hay[i - 1] if i else ""
257
+ nxt2 = hay[j] if j < len(hay) else ""
258
+ if prev in ("/", "\\", ".", "@") or nxt2 in (":", "/", "\\"):
259
+ start = i + 1
260
+ continue # URL/路径上下文不是产品提及:obs://bucket、/obs/bin、a@obs
261
+ out.append((i, j))
262
+ start = i + 1
263
+
264
+
265
+ def _snippet(text: str, start: int, end: int) -> str:
266
+ lo = max(0, start - _SNIPPET_PAD)
267
+ hi = min(len(text), end + _SNIPPET_PAD)
268
+ frag = " ".join(text[lo:hi].split())
269
+ return frag[:_SNIPPET_MAX]
270
+
271
+
272
+ def match_products(text: str, index: list) -> list:
273
+ """在用户原话里找产品别名 → 命中列表(长别名优先,重叠不重复计)。
274
+
275
+ [{"product","id","alias","start","end","snippet"}]
276
+ """
277
+ text = str(text or "")
278
+ if not text or not index:
279
+ return []
280
+ taken: list = []
281
+ hits: list = []
282
+ for entry in index:
283
+ alias = entry["alias"]
284
+ spans = _ascii_hits(text, alias, entry.get("caseless", False)) if _is_ascii(alias) else [
285
+ (m.start(), m.end()) for m in re.finditer(re.escape(alias), text)]
286
+ for start, end in spans:
287
+ if any(not (end <= s or start >= e) for s, e in taken):
288
+ continue # 被更长别名覆盖(「软件开发生产线 CodeArts」不吃子串)
289
+ taken.append((start, end))
290
+ hits.append({"product": entry["product"], "id": entry["id"],
291
+ "alias": alias, "start": start, "end": end,
292
+ "snippet": _snippet(text, start, end)})
293
+ hits.sort(key=lambda h: h["start"])
294
+ return hits
295
+
296
+
297
+ def _group(hits: list) -> dict:
298
+ """按产品合并(同产品多别名命中取最长片段作证据)。"""
299
+ grouped: dict = {}
300
+ for h in hits:
301
+ key = h["product"].lower()
302
+ cur = grouped.get(key)
303
+ if cur is None or len(h["alias"]) > len(cur["alias"]):
304
+ grouped[key] = dict(h)
305
+ return grouped
306
+
307
+
308
+ def resolve_id(product: str, meta: dict) -> str:
309
+ """产品名/短码/主键 → 提交值:目录命中给 id,否则规范名(引擎 name 兼容通道)。"""
310
+ product = str(product or "").strip()
311
+ if not product:
312
+ return ""
313
+ if product.isdigit():
314
+ return product
315
+ idx = build_alias_index(meta)
316
+ low = product.lower()
317
+ for entry in idx:
318
+ if entry["product"].lower() == low and entry["id"]:
319
+ return str(entry["id"])
320
+ for entry in idx:
321
+ if entry["alias"].lower() == low and entry["id"]:
322
+ return str(entry["id"])
323
+ return product
324
+
325
+
326
+ def attribute(text: str, meta: dict, memory: dict | None = None,
327
+ binding: str | None = None, ttl: int = MEM_TTL,
328
+ now: float | None = None) -> dict:
329
+ """归因优先级链:字面证据 > 记忆 > 安装先验 > UNKNOWN。
330
+
331
+ 返回 {"product": 提交值或 None, "source": user_input|memory|install_binding|unknown,
332
+ "evidence": [{"product","alias","snippet","reason"?}]}
333
+ """
334
+ import time
335
+ now = time.time() if now is None else now
336
+ hits = match_products(text, build_alias_index(meta))
337
+ grouped = _group(hits)
338
+
339
+ if len(grouped) == 1:
340
+ hit = next(iter(grouped.values()))
341
+ return {"product": str(hit["id"]) if hit["id"] else hit["product"],
342
+ "productName": hit["product"], "source": "user_input",
343
+ "evidence": [{"product": hit["product"], "alias": hit["alias"],
344
+ "snippet": hit["snippet"]}]}
345
+
346
+ if len(grouped) > 1:
347
+ # P1-A:歧义一律 UNKNOWN,全部命中留痕(人工归因要有上下文)
348
+ return {"product": None, "productName": None, "source": "unknown",
349
+ "evidence": [{"product": h["product"], "alias": h["alias"],
350
+ "snippet": h["snippet"], "reason": "ambiguous"}
351
+ for h in hits]}
352
+
353
+ mem = memory or {}
354
+ if mem.get("product") and now - float(mem.get("at") or 0) <= ttl:
355
+ return {"product": str(mem["product"]),
356
+ "productName": mem.get("productName") or None, "source": "memory",
357
+ "evidence": [{"product": mem.get("productName") or str(mem["product"]),
358
+ "alias": mem.get("alias"), "snippet": mem.get("snippet"),
359
+ "at": mem.get("at"), "reason": "memory"}]}
360
+
361
+ if binding:
362
+ return {"product": resolve_id(binding, meta), "productName": str(binding),
363
+ "source": "install_binding", "evidence": []}
364
+
365
+ return {"product": None, "productName": None, "source": "unknown",
366
+ "evidence": [{"reason": "no-evidence"}]}
367
+
368
+
369
+ def remember_if_evidenced(result: dict) -> dict | None:
370
+ """只有「字面证据唯一命中」的归因才写记忆(S100:歧义/无证据不污染)。"""
371
+ if result.get("source") != "user_input":
372
+ return None
373
+ ev = (result.get("evidence") or [{}])[0]
374
+ import time
375
+ return {"product": result.get("product"),
376
+ "productName": ev.get("product") or result.get("productName"),
377
+ "alias": ev.get("alias"), "snippet": ev.get("snippet"),
378
+ "at": int(time.time())}
@@ -0,0 +1,154 @@
1
+ """宿主配置文件的形态分类与受管块扫描(单一实现,零第三方依赖)。
2
+
3
+ 背景:安装器要改两类文本配置——codex 的 `config.toml` 与 dsh 的
4
+ `cordis.patch.yml`。历史缺陷全都是"尽力猜"造成的:
5
+
6
+ - TOML:`args = ["…"]` 行内方括号让正则提前断块 → 旧 env 子表残留;
7
+ 更隐蔽的一层是残留的子表 `[mcp_servers.vod-devkit.env]` 在 TOML 语义里
8
+ 会**重新创建父表**——于是装出一个没有 command 的假 server,改完配置
9
+ 反而更坏。
10
+ - YAML:模板里的字面量 `[]` 顶层行 + 追加 `- id:` = 非法 YAML,整个
11
+ profile 启动崩溃;dsh 运行期序列化还会冲掉"打平"的块。
12
+
13
+ 借鉴 huaweicloud-devkit 的纪律(`mcp-config-merge.ts`):**一个扫描器同时
14
+ 支撑写入、删除与增量**,非已知形态在改字节**之前**拒绝——宁可装不上,
15
+ 不可改坏用户文件。本模块只做分类与扫描,不做 IO,也不做"修复"。
16
+ """
17
+ import re
18
+
19
+ # 受管 TOML 表前缀:本插件拥有该表及其全部子表
20
+ TOML_MANAGED = "mcp_servers.vod-devkit"
21
+
22
+ _HEADER = re.compile(r"^\[([^\[\]]+)\]$")
23
+ _MAPPING_ROOT = re.compile(r"^[A-Za-z_][\w.\-]*\s*:")
24
+ _DSH_ID = "- id: vod-devkit"
25
+
26
+
27
+ class Refused(Exception):
28
+ """文件形态不在已知集合内:调用方必须原样放弃修改(字节不变)。"""
29
+
30
+
31
+ # ---------------- TOML ----------------
32
+
33
+ def _split_header(line: str):
34
+ """行 → 表名;非表头返回 None。空行/注释返回 ""。"""
35
+ s = line.strip()
36
+ if not s or s.startswith("#"):
37
+ return ""
38
+ # 表头允许行尾注释:`[a.b] # note`(表名里不会出现 #)
39
+ if "#" in s:
40
+ s = s.split("#", 1)[0].strip()
41
+ m = _HEADER.match(s)
42
+ if m:
43
+ return m.group(1).strip()
44
+ if s.startswith("["):
45
+ raise Refused(f"疑似表头但不合法:{line.rstrip()[:60]}")
46
+ return None
47
+
48
+
49
+ def scan_toml_sections(text: str) -> list:
50
+ """按行扫描 TOML 表:返回 [{name, start, end}](end 为下一个表头行,排他)。"""
51
+ lines = text.splitlines()
52
+ heads = [] # (name, line_no)
53
+ for i, line in enumerate(lines):
54
+ name = _split_header(line)
55
+ if name:
56
+ heads.append((name, i))
57
+ out = []
58
+ for idx, (name, start) in enumerate(heads):
59
+ end = heads[idx + 1][1] if idx + 1 < len(heads) else len(lines)
60
+ out.append({"name": name, "start": start, "end": end})
61
+ return out
62
+
63
+
64
+ def classify_codex_toml(text: str) -> tuple:
65
+ """codex config.toml 形态判定 → (verdict, reason);verdict ∈ {ok, refuse}。
66
+
67
+ 拒绝条件(都会让"删我们那一段"变成不安全的操作):
68
+ - 表头重复定义(TOML 本身非法;删哪一份都是猜)
69
+ - 出现"疑似表头"的畸形行(我们的扫描器与用户的文件理解不一致)
70
+ """
71
+ sections = scan_toml_sections(text) # 畸形表头在此抛 Refused
72
+ seen = set()
73
+ for sec in sections:
74
+ if sec["name"] in seen:
75
+ return "refuse", f"表头重复定义 [{sec['name']}](TOML 非法,拒绝猜测)"
76
+ seen.add(sec["name"])
77
+ return "ok", ""
78
+
79
+
80
+ def managed_toml_sections(sections: list) -> list:
81
+ """属于本插件的表(含子表):name == 前缀 或 name.startswith(前缀 + ".")。"""
82
+ return [s for s in sections
83
+ if s["name"] == TOML_MANAGED or s["name"].startswith(TOML_MANAGED + ".")]
84
+
85
+
86
+ def strip_managed_toml(text: str) -> tuple:
87
+ """删除本插件拥有的全部 TOML 段(含子表)→ (new_text, removed_names)。
88
+
89
+ 子表必须一起删:留下 `[mcp_servers.vod-devkit.env]` 会在 TOML 语义里
90
+ 重建父表,得到一个没有 command 的 vod-devkit server(旧实现的残留 bug)。
91
+ """
92
+ sections = scan_toml_sections(text)
93
+ doomed = managed_toml_sections(sections)
94
+ if not doomed:
95
+ return text.rstrip(), []
96
+ lines = text.splitlines()
97
+ drop = set()
98
+ for sec in doomed:
99
+ drop.update(range(sec["start"], sec["end"]))
100
+ kept = [ln for i, ln in enumerate(lines) if i not in drop]
101
+ return "\n".join(kept).rstrip(), [s["name"] for s in doomed]
102
+
103
+
104
+ # ---------------- YAML(dsh cordis.patch.yml) ----------------
105
+
106
+ def classify_dsh_patch(lines: list) -> tuple:
107
+ """dsh profile patch 形态判定 → (verdict, reason)。
108
+
109
+ 这个文件是**顶层数组**(元素形如 `- insert:`)。拒绝条件:
110
+ - 缩进里有 tab(YAML 禁止 tab 缩进,任何解析器行为都不可依赖)
111
+ - 根是映射(追加顶层数组元素会造出非法文档)
112
+ - 根是 flow 集合(`{...}` / `[...]`,同上;字面量 `[]` 占位例外)
113
+ - 本插件的 `- id: vod-devkit` 出现多次(删/替换哪一份都是猜)
114
+ """
115
+ for ln in lines:
116
+ lead = ln[:len(ln) - len(ln.lstrip())]
117
+ if "\t" in lead:
118
+ return "refuse", "缩进含 tab(YAML 禁止 tab 缩进)"
119
+ significant = [ln for ln in lines if ln.strip() and not ln.strip().startswith("#")]
120
+ if not significant:
121
+ return "ok", ""
122
+ root = significant[0].strip()
123
+ if root.startswith("{") or (root.startswith("[") and root != "[]"):
124
+ return "refuse", f"根节点是 flow 集合({root[:20]}),本插件只写块数组"
125
+ if _MAPPING_ROOT.match(root):
126
+ return "refuse", f"根节点是映射({root[:20]}),不是本插件写的顶层数组"
127
+ if sum(1 for ln in lines if ln.strip().startswith(_DSH_ID)) > 1:
128
+ return "refuse", "出现多个 `- id: vod-devkit` 块(无法判定哪一份是活的)"
129
+ return "ok", ""
130
+
131
+
132
+ def find_dsh_block(lines: list) -> tuple:
133
+ """定位 vod-devkit 块的 (start, end);不存在返回 (None, None)。
134
+
135
+ 块边界=下一顶层元素行(`- ` 开头)或 EOF。嵌套铁律(真机实锤):
136
+ dsh 只认缩进在 `- insert:` 之下的块——命中行带缩进时 start 向上归并到
137
+ 该组头,整组替换;历史平铺形态按原语义顶格替换。install 的幂等 upsert
138
+ 与 uninstall 的摘除共用本边界语义(单一实现,防两处扫描规则漂移)。
139
+ """
140
+ for i, ln in enumerate(lines):
141
+ if ln.strip().startswith(_DSH_ID):
142
+ start = i
143
+ if ln[:1] == " ": # 嵌套形态:向上归并组头
144
+ for k in range(i - 1, -1, -1):
145
+ if lines[k].startswith("- "):
146
+ start = k
147
+ break
148
+ end = len(lines)
149
+ for j in range(start + 1, len(lines)):
150
+ if lines[j].startswith("- "):
151
+ end = j
152
+ break
153
+ return start, end
154
+ return None, None