@sakanano-moe/agenthelm 6.13.1 → 6.14.0

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 (117) hide show
  1. package/package.json +1 -1
  2. package/runtime/index.json +6 -6
  3. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  4. package/runtime/plugins/agent-pack/plugin.json +1 -1
  5. package/runtime/plugins/agent-pack/references/capability-config.md +10 -0
  6. package/runtime/plugins/agent-pack/references/check-opinion-migrate.en.md +31 -0
  7. package/runtime/plugins/agent-pack/references/check-opinion-migrate.md +31 -0
  8. package/runtime/plugins/agent-pack/references/dedupe-contract.en.md +27 -0
  9. package/runtime/plugins/agent-pack/references/dedupe-contract.md +27 -0
  10. package/runtime/plugins/agent-pack/references/inventory-contract.en.md +83 -0
  11. package/runtime/plugins/agent-pack/references/inventory-contract.md +83 -0
  12. package/runtime/plugins/agent-pack/references/nudge.en.md +10 -2
  13. package/runtime/plugins/agent-pack/references/nudge.md +10 -2
  14. package/runtime/plugins/agent-pack/references/relocate-contract.en.md +41 -0
  15. package/runtime/plugins/agent-pack/references/relocate-contract.md +41 -0
  16. package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +572 -30
  17. package/runtime/plugins/agent-pack/runtime/agent_pack_clients.py +233 -0
  18. package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +112 -4
  19. package/runtime/plugins/agent-pack/runtime/agent_pack_dedupe.py +502 -0
  20. package/runtime/plugins/agent-pack/runtime/agent_pack_desktop.py +92 -0
  21. package/runtime/plugins/agent-pack/runtime/agent_pack_ext_common.py +251 -0
  22. package/runtime/plugins/agent-pack/runtime/agent_pack_inventory.py +989 -0
  23. package/runtime/plugins/agent-pack/runtime/agent_pack_mcp_write.py +447 -0
  24. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +29 -4
  25. package/runtime/plugins/agent-pack/runtime/agent_pack_relocate.py +385 -0
  26. package/runtime/plugins/agent-pack/runtime/agent_pack_scope.py +233 -0
  27. package/runtime/plugins/agent-pack/runtime/agenthelm.py +183 -14
  28. package/runtime/plugins/agent-pack/runtime/locale/en.json +250 -1
  29. package/runtime/plugins/agent-pack/runtime/mcp_server.py +12 -0
  30. package/runtime/plugins/agent-pack/runtime/nudge_text.py +8 -2
  31. package/runtime/plugins/agent-pack/runtime/user_settings.py +2 -1
  32. package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +15 -0
  33. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  34. package/runtime/plugins/agents-init/content.json +4 -2
  35. package/runtime/plugins/agents-init/plugin.json +1 -1
  36. package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +2 -0
  37. package/runtime/plugins/agents-init/skills/agents-init/launcher.en.sh +93 -0
  38. package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +27 -0
  39. package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +4 -1
  40. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +24 -9
  41. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  42. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  43. package/runtime/plugins/opinion-manager/catalog/README.md +3 -1
  44. package/runtime/plugins/opinion-manager/catalog/rules/om.align-requirements/versions/1.1.0.json +34 -0
  45. package/runtime/plugins/opinion-manager/catalog/rules/om.assumptions-authority/versions/1.1.0.json +34 -0
  46. package/runtime/plugins/opinion-manager/catalog/rules/om.batch-questions/versions/1.1.0.json +34 -0
  47. package/runtime/plugins/opinion-manager/catalog/rules/om.bilingual-terms/versions/1.1.0.json +34 -0
  48. package/runtime/plugins/opinion-manager/catalog/rules/om.calculations/versions/1.1.0.json +34 -0
  49. package/runtime/plugins/opinion-manager/catalog/rules/om.chinese-response/versions/1.1.0.json +34 -0
  50. package/runtime/plugins/opinion-manager/catalog/rules/om.clean-deliverable/versions/1.1.0.json +34 -0
  51. package/runtime/plugins/opinion-manager/catalog/rules/om.complete-options/versions/1.1.0.json +34 -0
  52. package/runtime/plugins/opinion-manager/catalog/rules/om.conclusion-first/versions/1.1.0.json +34 -0
  53. package/runtime/plugins/opinion-manager/catalog/rules/om.concrete-titles/versions/1.1.0.json +34 -0
  54. package/runtime/plugins/opinion-manager/catalog/rules/om.consistent-items/versions/1.1.0.json +34 -0
  55. package/runtime/plugins/opinion-manager/catalog/rules/om.device-readable/versions/1.1.0.json +34 -0
  56. package/runtime/plugins/opinion-manager/catalog/rules/om.editable-diagrams/versions/1.1.0.json +34 -0
  57. package/runtime/plugins/opinion-manager/catalog/rules/om.evidence-inference/versions/1.1.0.json +34 -0
  58. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-chinese/versions/1.1.0.json +34 -0
  59. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-project-language/versions/1.1.0.json +34 -0
  60. package/runtime/plugins/opinion-manager/catalog/rules/om.markdown-structure/versions/1.1.0.json +34 -0
  61. package/runtime/plugins/opinion-manager/catalog/rules/om.portable-files/versions/1.1.0.json +34 -0
  62. package/runtime/plugins/opinion-manager/catalog/rules/om.report-context/versions/1.1.0.json +34 -0
  63. package/runtime/plugins/opinion-manager/catalog/rules/om.report-formats/versions/1.1.0.json +34 -0
  64. package/runtime/plugins/opinion-manager/catalog/rules/om.report-review/versions/1.1.0.json +34 -0
  65. package/runtime/plugins/opinion-manager/catalog/rules/om.response-brief/versions/1.1.0.json +34 -0
  66. package/runtime/plugins/opinion-manager/catalog/rules/om.response-dense/versions/1.1.0.json +34 -0
  67. package/runtime/plugins/opinion-manager/catalog/rules/om.rules-tools/versions/1.1.0.json +34 -0
  68. package/runtime/plugins/opinion-manager/catalog/rules/om.semantic-wrap/versions/1.1.0.json +34 -0
  69. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-proportional/versions/1.1.0.json +34 -0
  70. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-three-level/versions/1.1.0.json +34 -0
  71. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-compact/versions/1.1.0.json +34 -0
  72. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-list-first/versions/1.1.0.json +34 -0
  73. package/runtime/plugins/opinion-manager/catalog/rules/om.test-evidence/versions/1.1.0.json +34 -0
  74. package/runtime/plugins/opinion-manager/catalog/rules/om.versioned-files/versions/1.1.0.json +34 -0
  75. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/compact-tables/versions/1.1.0.json +32 -0
  76. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/list-first/versions/1.1.0.json +32 -0
  77. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/chinese-maintenance/versions/1.1.0.json +26 -0
  78. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/project-language/versions/1.1.0.json +26 -0
  79. package/runtime/plugins/opinion-manager/catalog/templates/response-style/brief-chinese/versions/1.1.0.json +30 -0
  80. package/runtime/plugins/opinion-manager/catalog/templates/response-style/dense-chinese/versions/1.1.0.json +30 -0
  81. package/runtime/plugins/opinion-manager/catalog/templates/scenario/concise-project/versions/1.1.0.json +181 -0
  82. package/runtime/plugins/opinion-manager/catalog/templates/scenario/reviewed-project/versions/1.1.0.json +179 -0
  83. package/runtime/plugins/opinion-manager/catalog/templates/work-method/proportional/versions/1.1.0.json +31 -0
  84. package/runtime/plugins/opinion-manager/catalog/templates/work-method/three-level/versions/1.1.0.json +31 -0
  85. package/runtime/plugins/opinion-manager/content.json +44 -3
  86. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  87. package/runtime/plugins/opinion-manager/references/inbox.en.md +25 -4
  88. package/runtime/plugins/opinion-manager/references/inbox.md +25 -4
  89. package/runtime/plugins/opinion-manager/references/profile.schema.json +19 -2
  90. package/runtime/plugins/opinion-manager/references/rule.schema.json +25 -3
  91. package/runtime/plugins/opinion-manager/references/versioned-template.schema.json +5 -4
  92. package/runtime/plugins/opinion-manager/references/versioning.md +89 -4
  93. package/runtime/plugins/opinion-manager/runtime/context.py +26 -19
  94. package/runtime/plugins/opinion-manager/runtime/inbox.py +400 -25
  95. package/runtime/plugins/opinion-manager/runtime/inbox_relations.py +106 -0
  96. package/runtime/plugins/opinion-manager/runtime/inbox_routes.py +132 -0
  97. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +117 -11
  98. package/runtime/plugins/opinion-manager/runtime/lifecycle.py +35 -5
  99. package/runtime/plugins/opinion-manager/runtime/locale/en.json +137 -2
  100. package/runtime/plugins/opinion-manager/runtime/migrate.py +582 -0
  101. package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +9 -4
  102. package/runtime/plugins/opinion-manager/runtime/rule_lines.py +247 -0
  103. package/runtime/plugins/opinion-manager/runtime/tags.py +217 -0
  104. package/runtime/plugins/opinion-manager/runtime/versioned.py +289 -41
  105. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +8 -7
  106. package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
  107. package/runtime/plugins/project-orchestrator/plugin.json +1 -1
  108. package/runtime/plugins/project-orchestrator/runtime/locale/en.json +305 -3
  109. package/runtime/plugins/project-orchestrator/runtime/private_paths.py +11 -1
  110. package/runtime/plugins/project-orchestrator/runtime/project_cli.py +101 -1
  111. package/runtime/plugins/project-orchestrator/runtime/project_demo.py +13 -1
  112. package/runtime/plugins/project-orchestrator/runtime/project_ext_actions.py +415 -0
  113. package/runtime/plugins/project-orchestrator/runtime/project_extensions.py +971 -0
  114. package/runtime/plugins/project-orchestrator/runtime/project_extensions_demo.py +86 -0
  115. package/runtime/plugins/project-orchestrator/runtime/project_menu.py +345 -2
  116. package/runtime/plugins/project-orchestrator/runtime/project_real.py +17 -1
  117. package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +2 -0
@@ -0,0 +1,971 @@
1
+ """技能与 MCP 的只读清单:取数(子进程调用 ``agenthelm inventory``)、重复归类、机械体检与文字渲染。
2
+
3
+ - 不 import agent-pack:只用参数列表(不经 shell)运行 ``agenthelm inventory --output json`` 并解析 JSON。
4
+ 找不到命令、命令失败、输出不是 JSON、``schema_version`` 主版本未知时一律降级为「不可用」并写明原因,不猜测。
5
+ - 全程只读、不联网。MCP 条目只取白名单字段(名字、客户端、作用域、存储、传输、指纹前缀、变量名、url 主机名);
6
+ 命令行参数、url 全文、环境变量值、headers 从不进入任何输出。
7
+ - 「哪一份生效」只在官方文档写明优先级的场景下下结论,其余一律「未知」;证据为 unknown 的副本永远显示「未知」。
8
+ - 体检只输出机械事实与阈值,不打分、不排名、不建议删除。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import unicodedata
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from wf import S, display_width, term_width
23
+ from i18n_orchestrator import _, N_ # noqa: E402
24
+
25
+ SUPPORTED_SCHEMA_MAJOR = 1
26
+ INVENTORY_TIMEOUT_SECONDS = 60
27
+ PROBE_TIMEOUT_SECONDS = 10
28
+ EVIDENCE_LEVELS = ("file", "setting", "cli", "unknown")
29
+ # 阈值:来自 Agent Skills 规范与 Claude Code Skills 文档(2026-11-18 读取),是社区或厂商约定,不是对本仓库的强制要求。
30
+ SPEC_DESCRIPTION_CHARS = 1024
31
+ CLAUDE_DESCRIPTION_CAP_CHARS = 1536
32
+ SPEC_SKILL_MD_LINES = 500
33
+ # description 相似度提示的阈值:没有外部依据,只用于提示(设计文档 D-CB8)。
34
+ SIMILARITY_THRESHOLD = 0.6
35
+ SIMILARITY_MAX_ENTRIES = 1500
36
+ SOURCE_SPEC = N_("Agent Skills 规范 agentskills.io/specification")
37
+ SOURCE_CLAUDE = N_("Claude Code Skills 文档 code.claude.com/docs/en/skills")
38
+
39
+ SCOPE_LABEL = {"user": N_("用户级"), "project": N_("项目级"), "local": N_("本机项目级"),
40
+ "managed": N_("企业级"), "enterprise": N_("企业级"), "desktop": N_("应用级")}
41
+ KIND_LABEL = {"skill": N_("技能"), "mcp": "MCP"}
42
+ BADGE = {"file": "●", "setting": "⚙", "cli": "⌘", "unknown": "?"}
43
+ FORBIDDEN_NAME = re.compile("[<>\\u200b\\u200c\\u200d\\u2060\\ufeff]")
44
+
45
+ TAG_LABEL = {"no-description": N_("无 description"), "desc-too-long": N_("描述会被截断"), "skill-md-long": N_("体积大"),
46
+ "name-dir-mismatch": N_("名称与目录不一致"), "name-bad-chars": N_("name 含禁用字符"),
47
+ "frontmatter-incomplete": N_("frontmatter 不全"), "stale": N_("过期")}
48
+
49
+
50
+ # ---------------------------------------------------------------- 取数
51
+
52
+ def agenthelm_command(host: Any) -> list[str] | None:
53
+ """经 ``agenthelm project`` 启动时用同一个 agent-pack 的 agenthelm.py;否则找 PATH 里的 agenthelm。"""
54
+ if host is not None:
55
+ script = Path(host.__file__).resolve().parent / "agenthelm.py"
56
+ if script.is_file():
57
+ return [sys.executable, str(script)]
58
+ found = shutil.which("agenthelm")
59
+ return [found] if found else None
60
+
61
+
62
+ def _run(command: list[str], timeout: int) -> tuple[int, str, str]:
63
+ try:
64
+ done = subprocess.run(command, capture_output=True, text=True, check=False, timeout=timeout)
65
+ except subprocess.TimeoutExpired:
66
+ raise OSError(_("等待 agenthelm 超过 {0} 秒").format(timeout)) from None
67
+ return done.returncode, done.stdout, (done.stderr or "").strip()[:200]
68
+
69
+
70
+ def unavailable(reason: str) -> dict:
71
+ return {"state": "unavailable", "reason": reason, "inventory": None}
72
+
73
+
74
+ def probe(host: Any) -> tuple[bool, str]:
75
+ """能力探测:找得到命令且 ``inventory --help`` 能运行才算可用。不读取任何清单。"""
76
+ command = agenthelm_command(host)
77
+ if command is None:
78
+ return False, _("未找到 agent-pack 的 inventory:没有可运行的 agenthelm 命令")
79
+ try:
80
+ code, _out, _err = _run([*command, "inventory", "--help"], PROBE_TIMEOUT_SECONDS)
81
+ except OSError as exc:
82
+ return False, _("无法运行 agenthelm inventory:{0}").format(exc)
83
+ if code != 0:
84
+ return False, _("当前的 agenthelm 没有 inventory 命令(需要更新 agent-pack)")
85
+ return True, ""
86
+
87
+
88
+ def inventory_argv(command: list[str], root: Path | None, include_description: bool) -> list[str]:
89
+ argv = [*command, "inventory", "--output", "json", "--client", "all"] # all:含只读的 claude-desktop
90
+ if root is not None:
91
+ argv += ["--project", str(root)]
92
+ if include_description:
93
+ argv.append("--include-description")
94
+ return argv
95
+
96
+
97
+ def load(host: Any, root: Path | None, *, include_description: bool = False) -> dict:
98
+ """运行一次 inventory;返回 {state, reason, inventory}。不抛错:不可用本身就是结果。"""
99
+ command = agenthelm_command(host)
100
+ if command is None:
101
+ return unavailable(_("未找到 agent-pack 的 inventory:没有可运行的 agenthelm 命令"))
102
+ try:
103
+ code, out, err = _run(inventory_argv(command, root, include_description), INVENTORY_TIMEOUT_SECONDS)
104
+ except OSError as exc:
105
+ return unavailable(_("无法运行 agenthelm inventory:{0}").format(exc))
106
+ if code == 2 and not out.strip(): # argparse 的用法错误:这个 agenthelm 不认识 inventory 子命令
107
+ return unavailable(_("当前的 agenthelm 没有 inventory 命令(需要更新 agent-pack)"))
108
+ try:
109
+ data = json.loads(out)
110
+ except ValueError:
111
+ detail = err or _("输出不是 JSON")
112
+ return unavailable(_("agenthelm inventory 没有返回可解析的结果:{0}").format(detail))
113
+ if not isinstance(data, dict):
114
+ return unavailable(_("agenthelm inventory 返回的不是对象"))
115
+ if code != 0 and not isinstance(data.get("skills"), list) and not isinstance(data.get("mcps"), list):
116
+ return unavailable(_("agenthelm inventory 运行失败(退出码 {0}):{1}").format(code, err or _("无详情")))
117
+ return validate(data)
118
+
119
+
120
+ def validate(data: dict) -> dict:
121
+ version = data.get("schema_version")
122
+ major = str(version).split(".")[0] if version is not None else ""
123
+ if not major.isdigit():
124
+ return unavailable(_("inventory 没有 schema_version:无法确认字段含义,不猜测"))
125
+ if int(major) != SUPPORTED_SCHEMA_MAJOR:
126
+ return unavailable(_("inventory 的 schema_version {0} 超出本菜单支持的主版本 {1}").format(version, SUPPORTED_SCHEMA_MAJOR))
127
+ if not isinstance(data.get("skills", []), list) or not isinstance(data.get("mcps", []), list):
128
+ return unavailable(_("inventory 的 skills 或 mcps 不是列表"))
129
+ return {"state": "available", "reason": "", "inventory": data}
130
+
131
+
132
+ # ---------------------------------------------------------------- 规范化(白名单字段)
133
+
134
+ def _int(value: Any) -> int | None:
135
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
136
+
137
+
138
+ def _text(value: Any) -> str | None:
139
+ return value if isinstance(value, str) and value.strip() and value.strip().lower() != "unknown" else None
140
+
141
+
142
+ def _evidence(value: Any) -> str:
143
+ return value if value in EVIDENCE_LEVELS else "unknown"
144
+
145
+
146
+ def _origin(raw: Any) -> dict:
147
+ if isinstance(raw, str):
148
+ raw = {"type": raw}
149
+ raw = raw if isinstance(raw, dict) else {}
150
+ return {"type": _text(raw.get("type")), "id": _text(raw.get("id")), "version": _text(raw.get("version")),
151
+ "latest_known": _text(raw.get("latest_known")), "evidence": _evidence(raw.get("evidence"))}
152
+
153
+
154
+ def _referenced(raw: Any) -> list[dict]:
155
+ """opinion 预留位:只认 [{"rule_id", "source"}];缺失或形状不对就当没有。不调用任何 opinion 命令。"""
156
+ if not isinstance(raw, list):
157
+ return []
158
+ return [{"rule_id": str(item["rule_id"]), "source": str(item.get("source") or "")}
159
+ for item in raw if isinstance(item, dict) and item.get("rule_id")]
160
+
161
+
162
+ def _shadowed(raw: Any) -> dict | None:
163
+ """inventory 给出的「被谁屏蔽」:只取 store、rule、evidence、source_url 四个键。"""
164
+ if isinstance(raw, dict):
165
+ return {key: _text(raw.get(key)) for key in ("store", "rule", "evidence", "source_url")}
166
+ text = _text(raw)
167
+ return {"store": text, "rule": None, "evidence": None, "source_url": None} if text else None
168
+
169
+
170
+ def _ref(kind: str, name: str, client: str, scope: str, given: Any) -> str:
171
+ return given if isinstance(given, str) and given else f"{kind}:{name}@{client}:{scope}"
172
+
173
+
174
+ def _entry(kind: str, raw: Any) -> dict | None:
175
+ if not isinstance(raw, dict) or not isinstance(raw.get("name"), str) or not raw["name"]:
176
+ return None
177
+ name = raw["name"]
178
+ client = _text(raw.get("client")) or "unknown"
179
+ scope = _text(raw.get("scope")) or "unknown"
180
+ entry: dict[str, Any] = {"ref": _ref(kind, name, client, scope, raw.get("ref")), "kind": kind, "name": name,
181
+ "client": client, "scope": scope, "store": _text(raw.get("store")),
182
+ "evidence": _evidence(raw.get("evidence"))}
183
+ if kind == "skill":
184
+ front = raw.get("frontmatter") if isinstance(raw.get("frontmatter"), dict) else {}
185
+ description = front.get("description") if isinstance(front.get("description"), str) else None
186
+ sha = _text(raw.get("content_sha256"))
187
+ entry.update({
188
+ "description_bytes": _int(raw.get("description_bytes")), "description_chars": _int(raw.get("description_chars")),
189
+ "skill_md_bytes": _int(raw.get("skill_md_bytes")), "skill_md_lines": _int(raw.get("skill_md_lines")),
190
+ "dir_bytes": _int(raw.get("dir_bytes")), "file_count": _int(raw.get("file_count")),
191
+ "content_sha8": sha[:8] if sha else None, "_sha": sha,
192
+ "is_symlink": raw.get("is_symlink") if isinstance(raw.get("is_symlink"), bool) else raw.get("symlink")
193
+ if isinstance(raw.get("symlink"), bool) else None,
194
+ "link_target_kind": _text(raw.get("link_target_kind")),
195
+ "name_matches_dir": raw.get("name_matches_dir") if isinstance(raw.get("name_matches_dir"), bool) else None,
196
+ "frontmatter_ok": raw.get("frontmatter_ok") if isinstance(raw.get("frontmatter_ok"), bool) else None,
197
+ "frontmatter_name": _text(front.get("name")), "origin": _origin(raw.get("origin")),
198
+ "version": _text(raw.get("version")),
199
+ "stale": raw.get("stale") if isinstance(raw.get("stale"), bool) else None,
200
+ "loaded": raw.get("loaded") if isinstance(raw.get("loaded"), bool) else None,
201
+ "when_to_use_chars": _int(raw.get("when_to_use_chars")), "when_to_use_bytes": _int(raw.get("when_to_use_bytes")),
202
+ "precedence": _text(raw.get("precedence")), "shadowed_by": _shadowed(raw.get("shadowed_by")),
203
+ "_description": description})
204
+ else:
205
+ fp = _text(raw.get("fingerprint"))
206
+ names = raw.get("env_var_names")
207
+ fields = raw.get("fingerprint_fields")
208
+ entry.update({
209
+ "transport": _text(raw.get("transport")), "fingerprint8": fp[:8] if fp else None, "_fp": fp,
210
+ "fingerprint_fields": [item for item in fields if isinstance(item, str)] if isinstance(fields, list) else None,
211
+ "env_var_names": [item for item in names if isinstance(item, str)] if isinstance(names, list) else None,
212
+ "has_inline_secret": raw.get("has_inline_secret") if isinstance(raw.get("has_inline_secret"), bool) else None,
213
+ "url_host": _text(raw.get("url_host"))})
214
+ if kind == "mcp":
215
+ entry.update({"precedence": _text(raw.get("precedence")), "shadowed_by": _shadowed(raw.get("shadowed_by"))})
216
+ referenced = _referenced(raw.get("referenced_by"))
217
+ if referenced:
218
+ entry["referenced_by"] = referenced
219
+ return entry
220
+
221
+
222
+ def normalize(inventory: dict) -> dict:
223
+ entries = [item for kind, key in (("skill", "skills"), ("mcp", "mcps"))
224
+ for item in (_entry(kind, raw) for raw in inventory.get(key, [])) if item]
225
+ clients = inventory.get("clients")
226
+ names = {item if isinstance(item, str) else item.get("name") for item in clients
227
+ if isinstance(item, (str, dict))} if isinstance(clients, list) else set()
228
+ # 「文件不存在」(reason=not-found,例如还没装 Desktop)是没有这个存储,不是读不懂,不计入未知。
229
+ unknown_extra = [item for item in inventory.get("unknown") or []
230
+ if not (isinstance(item, dict) and item.get("reason") == "not-found")] \
231
+ if isinstance(inventory.get("unknown"), list) else None
232
+ projects = inventory.get("projects")
233
+ known = [{"name": item["name"], "last_synced": _text(item.get("last_synced"))} for item in projects
234
+ if isinstance(item, dict) and isinstance(item.get("name"), str)] if isinstance(projects, list) else []
235
+ rules: dict[tuple[str, str], str] = {}
236
+ duplicates = inventory.get("duplicates") if isinstance(inventory.get("duplicates"), dict) else {}
237
+ for kind_key, kind_name in (("skills", "skill"), ("mcps", "mcp")):
238
+ for item in duplicates.get(kind_key) or []:
239
+ effective = item.get("effective") if isinstance(item, dict) else None
240
+ if isinstance(effective, dict) and _text(effective.get("rule")) and _text(item.get("name")):
241
+ rules[(kind_name, item["name"])] = effective["rule"]
242
+ return {"rules": rules, "projects": known, "entries": entries,
243
+ "clients": sorted({*(name for name in names if isinstance(name, str)),
244
+ *(entry["client"] for entry in entries)}),
245
+ "unknown_extra": len(unknown_extra) if isinstance(unknown_extra, list) else 0}
246
+
247
+
248
+ def public(entry: dict) -> dict:
249
+ """对外(JSON、文本)可见的字段:去掉下划线开头的内部字段。"""
250
+ return {key: value for key, value in entry.items() if not key.startswith("_")}
251
+
252
+
253
+ # ---------------------------------------------------------------- 重复归类与「哪一份生效」
254
+
255
+ def _group_id(kind: str, label: str, key: str) -> str:
256
+ return f"{'m' if kind == 'mcp' else 's'}-{hashlib.sha1(f'{kind}|{label}|{key}'.encode()).hexdigest()[:6]}"
257
+
258
+
259
+ def _is_desktop(client: str) -> bool:
260
+ return "desktop" in client
261
+
262
+
263
+ def _client_effective(client: str, members: list[dict], rule: str | None) -> tuple[bool, str]:
264
+ """同一客户端内、同名多份时哪份生效。只用 inventory 给出的 precedence / shadowed_by,工具层不另做判断。"""
265
+ unknown = _("{0}:生效:未知({1})")
266
+ if any(member["evidence"] == "unknown" for member in members):
267
+ return False, unknown.format(client, _("有副本的证据为未知"))
268
+ precedences = [member.get("precedence") for member in members]
269
+ if all(item == "both-load" for item in precedences):
270
+ return True, _("{0}:两份都会加载,不存在屏蔽(inventory 给出的结论)").format(client)
271
+ winners = [member for member in members if member.get("precedence") == "winner"]
272
+ losers = [member for member in members if member.get("precedence") == "shadowed" and member.get("shadowed_by")]
273
+ if len(winners) == 1 and len(winners) + len(losers) == len(members):
274
+ basis = losers[0]["shadowed_by"].get("rule") or _("未给出规则")
275
+ return True, _("{0}:生效的是 {1}({2};inventory 给出的结论)").format(client, winners[0]["ref"], basis)
276
+ basis = rule or next((member["shadowed_by"]["rule"] for member in members
277
+ if member.get("shadowed_by") and member["shadowed_by"].get("rule")), None) \
278
+ or next((item for item in precedences if item and item != "unknown"), None) or _("inventory 没有给出结论")
279
+ return False, unknown.format(client, _("依据:{0}").format(basis))
280
+
281
+
282
+ def _effective(kind: str, cls: str, name: str, members: list[dict], rules: dict) -> dict:
283
+ clients: dict[str, list[dict]] = {}
284
+ for member in members:
285
+ clients.setdefault(member["client"], []).append(member)
286
+ lines: list[str] = []
287
+ known = True
288
+ if cls == "diff-name-same-fp":
289
+ return {"known": True, "basis": "distinct-names", "lines": [_("名字不同,不构成同名覆盖")]}
290
+ if any(member["evidence"] == "unknown" for member in members):
291
+ reasons = [member["ref"] for member in members if member["evidence"] == "unknown"]
292
+ return {"known": False, "basis": "evidence-unknown",
293
+ "lines": [_("生效:未知(证据不足:{0})").format(_("、").join(reasons))]}
294
+ for client, group in clients.items():
295
+ if len(group) > 1:
296
+ ok, text = _client_effective(client, group, rules.get((kind, name)))
297
+ known = known and ok
298
+ lines.append(text)
299
+ if len(clients) > 1:
300
+ lines.append(_("各客户端独立加载,彼此不冲突") if not lines else _("不同客户端之间各自独立加载,彼此不冲突"))
301
+ return {"known": known, "basis": "inventory" if known else "unknown", "lines": lines}
302
+
303
+
304
+ CLASS_LABEL = {
305
+ ("mcp", "same-name-same"): N_("同名 · 同指纹"), ("mcp", "same-name-differs"): N_("同名 · 指纹不同(内容漂移)"),
306
+ ("mcp", "same-name-unknown"): N_("同名 · 证据不足"), ("mcp", "diff-name-same-fp"): N_("不同名 · 同指纹"),
307
+ ("skill", "same-name-same"): N_("同名 · 内容相同"), ("skill", "same-name-differs"): N_("同名 · 内容不同(漂移)"),
308
+ ("skill", "same-name-unknown"): N_("同名 · 证据不足")}
309
+
310
+
311
+ def build_groups(entries: list[dict], rules: dict | None = None) -> list[dict]:
312
+ rules = rules or {}
313
+ groups: list[dict] = []
314
+ for kind in ("mcp", "skill"):
315
+ key = "_fp" if kind == "mcp" else "_sha"
316
+ scoped = [entry for entry in entries if entry["kind"] == kind]
317
+ by_name: dict[str, list[dict]] = {}
318
+ for entry in scoped:
319
+ by_name.setdefault(entry["name"], []).append(entry)
320
+ for name, members in by_name.items():
321
+ if len(members) < 2:
322
+ continue
323
+ keys = [member[key] for member in members]
324
+ cls = "same-name-unknown" if None in keys else "same-name-same" if len(set(keys)) == 1 else "same-name-differs"
325
+ groups.append(_group(kind, cls, name, members, rules))
326
+ if kind == "mcp":
327
+ by_fp: dict[str, list[dict]] = {}
328
+ for entry in scoped:
329
+ if entry["_fp"]:
330
+ by_fp.setdefault(entry["_fp"], []).append(entry)
331
+ for fingerprint, members in by_fp.items():
332
+ if len({member["name"] for member in members}) > 1:
333
+ groups.append(_group(kind, "diff-name-same-fp", fingerprint[:8], members, rules))
334
+ return sorted(groups, key=lambda group: (group["kind"] != "mcp", group["name"], group["class"]))
335
+
336
+
337
+ def _group(kind: str, cls: str, name: str, members: list[dict], rules: dict) -> dict:
338
+ clients = [member["client"] for member in members]
339
+ cross = len(set(clients)) == len(clients)
340
+ ordered = sorted(members, key=lambda member: (member["client"], member["scope"], member["store"] or ""))
341
+ return {"id": _group_id(kind, cls, name), "kind": kind, "class": cls, "name": name,
342
+ "label": CLASS_LABEL[(kind, cls)], "cross_client": cross,
343
+ "evidence": "unknown" if any(member["evidence"] == "unknown" for member in members) else
344
+ min((member["evidence"] for member in members), key=EVIDENCE_LEVELS.index),
345
+ "members": [member["ref"] for member in ordered], "effective": _effective(kind, cls, name, ordered, rules),
346
+ "_members": ordered}
347
+
348
+
349
+ def public_group(group: dict) -> dict:
350
+ return {key: value for key, value in group.items() if not key.startswith("_")}
351
+
352
+
353
+ # ---------------------------------------------------------------- 体检(只给机械事实与阈值)
354
+
355
+ def _tokens(text: str) -> set[str]:
356
+ lowered = text.lower()
357
+ words = set(re.findall(r"[a-z0-9]+", lowered))
358
+ cjk = [char for char in lowered if 0x4E00 <= ord(char) <= 0x9FFF or 0x3040 <= ord(char) <= 0x30FF]
359
+ return words | {cjk[i] + cjk[i + 1] for i in range(len(cjk) - 1)}
360
+
361
+
362
+ def _finding(entry: dict, code: str, fact: str, threshold: str | None = None, source: str | None = None) -> dict:
363
+ return {"ref": entry["ref"], "code": code, "fact": fact, "threshold": threshold, "source": source}
364
+
365
+
366
+ def skill_findings(entry: dict) -> tuple[list[dict], list[str]]:
367
+ """一个技能条目的机械发现,以及 inventory 没有提供、因此没有检查的字段。证据未知的条目不下任何结论。"""
368
+ if entry["evidence"] == "unknown":
369
+ return [], []
370
+ found: list[dict] = []
371
+ missing: list[str] = []
372
+ chars, bytes_ = entry["description_chars"], entry["description_bytes"]
373
+ if bytes_ is None and chars is None:
374
+ missing.append("description_bytes")
375
+ elif bytes_ == 0 or chars == 0:
376
+ found.append(_finding(entry, "no-description", _("缺 description"), _("规范要求必填"), _(SOURCE_SPEC)))
377
+ if chars is None:
378
+ missing.append("description_chars")
379
+ elif chars + (entry["when_to_use_chars"] or 0) > CLAUDE_DESCRIPTION_CAP_CHARS:
380
+ found.append(_finding(entry, "desc-too-long", _("description 与 when_to_use 合计 {0} 字符,超过 Claude Code 技能列表截断上限 {1},超出部分会被截断").format(
381
+ chars + (entry["when_to_use_chars"] or 0), CLAUDE_DESCRIPTION_CAP_CHARS), _("{0} 字符").format(CLAUDE_DESCRIPTION_CAP_CHARS), _(SOURCE_CLAUDE)))
382
+ elif chars > SPEC_DESCRIPTION_CHARS:
383
+ found.append(_finding(entry, "desc-too-long", _("description {0} 字符,超过规范上限 {1}").format(
384
+ chars, SPEC_DESCRIPTION_CHARS), _("{0} 字符").format(SPEC_DESCRIPTION_CHARS), _(SOURCE_SPEC)))
385
+ if entry["skill_md_lines"] is None:
386
+ missing.append("skill_md_lines")
387
+ elif entry["skill_md_lines"] > SPEC_SKILL_MD_LINES:
388
+ found.append(_finding(entry, "skill-md-long", _("SKILL.md {0} 行,超过规范建议的 {1} 行").format(
389
+ entry["skill_md_lines"], SPEC_SKILL_MD_LINES), _("{0} 行(建议值,不是强制)").format(SPEC_SKILL_MD_LINES), _(SOURCE_SPEC)))
390
+ if entry["name_matches_dir"] is None:
391
+ missing.append("name_matches_dir")
392
+ elif entry["name_matches_dir"] is False:
393
+ found.append(_finding(entry, "name-dir-mismatch", _("目录名与 name 不一致"), _("规范要求一致"), _(SOURCE_SPEC)))
394
+ if FORBIDDEN_NAME.search(entry["name"]) or any(unicodedata.category(char) == "Cc" for char in entry["name"]):
395
+ found.append(_finding(entry, "name-bad-chars", _("name 含 < >、零宽或控制字符"), _("Claude Code 会拒绝这样的 name"), _(SOURCE_CLAUDE)))
396
+ if entry["frontmatter_ok"] is None:
397
+ missing.append("frontmatter_ok")
398
+ elif entry["frontmatter_ok"] is False and not any(item["code"] == "no-description" for item in found):
399
+ found.append(_finding(entry, "frontmatter-incomplete", _("frontmatter 缺少必填字段"), _("规范要求 name 与 description"), _(SOURCE_SPEC)))
400
+ origin = entry["origin"]
401
+ if origin["version"] and origin["latest_known"] and origin["version"] != origin["latest_known"]:
402
+ found.append(_finding(entry, "stale", _("来源 {0} 已安装 {1},本机已知最新 {2}").format(
403
+ origin["id"] or origin["type"] or _("未知"), origin["version"], origin["latest_known"]),
404
+ _("版本不同即提示;不用修改时间推断"), None))
405
+ elif entry["stale"] is True:
406
+ found.append(_finding(entry, "stale", _("inventory 标记该技能有新版本"), _("不用修改时间推断"), None))
407
+ return found, missing
408
+
409
+
410
+ def cost_per_client(skills: list[dict]) -> list[dict]:
411
+ """每客户端每会话 description 常驻字节。只对「会加载」的求和:证据非 unknown,且没被屏蔽、没标为不加载。"""
412
+ result: dict[str, dict] = {}
413
+ for entry in skills:
414
+ row = result.setdefault(entry["client"], {"client": entry["client"], "bytes": 0, "counted": 0, "uncounted": 0,
415
+ "capped": 0, "evidence": set()})
416
+ known_bytes = entry["description_bytes"]
417
+ if entry["evidence"] == "unknown" or entry["loaded"] is False or entry.get("shadowed_by") or known_bytes is None:
418
+ row["uncounted"] += 1
419
+ continue
420
+ known_bytes += entry["when_to_use_bytes"] or 0
421
+ chars = (entry["description_chars"] or 0) + (entry["when_to_use_chars"] or 0)
422
+ if chars > CLAUDE_DESCRIPTION_CAP_CHARS and entry["client"] == "claude":
423
+ known_bytes = round(known_bytes * CLAUDE_DESCRIPTION_CAP_CHARS / chars)
424
+ row["capped"] += 1
425
+ row["bytes"] += known_bytes
426
+ row["counted"] += 1
427
+ row["evidence"].add(entry["evidence"])
428
+ return [{"client": row["client"], "resident_bytes": row["bytes"], "counted": row["counted"],
429
+ "uncounted": row["uncounted"], "capped": row["capped"], "evidence": sorted(row["evidence"], key=EVIDENCE_LEVELS.index),
430
+ "token_estimate": {"low": row["bytes"] // 4, "high": row["bytes"] // 2,
431
+ "label": _("估算,仅用于排序与对比;字节÷4(拉丁文)至÷2(中文),没有一手依据")}}
432
+ for row in sorted(result.values(), key=lambda row: row["client"])]
433
+
434
+
435
+ def similar_pairs(skills: list[dict]) -> tuple[list[dict], str | None]:
436
+ """description 文本相似的技能对(机械判断,不代表功能重复)。只需要 inventory 以 --include-description 输出的文本。"""
437
+ candidates = [entry for entry in skills if entry["_description"] and entry["evidence"] != "unknown"]
438
+ if len(candidates) > SIMILARITY_MAX_ENTRIES:
439
+ return [], _("技能超过 {0} 个,没有做 description 相似度比较").format(SIMILARITY_MAX_ENTRIES)
440
+ tokens = {entry["ref"]: _tokens(entry["_description"]) for entry in candidates}
441
+ pairs = []
442
+ for index, first in enumerate(candidates):
443
+ for second in candidates[index + 1:]:
444
+ if first["name"] == second["name"]:
445
+ continue
446
+ a, b = tokens[first["ref"]], tokens[second["ref"]]
447
+ if a and b and len(a & b) / len(a | b) >= SIMILARITY_THRESHOLD:
448
+ pairs.append({"refs": sorted([first["ref"], second["ref"]]), "jaccard": round(len(a & b) / len(a | b), 2)})
449
+ return sorted(pairs, key=lambda pair: pair["refs"]), None
450
+
451
+
452
+ def check(norm: dict, include_description: bool) -> dict:
453
+ skills = [entry for entry in norm["entries"] if entry["kind"] == "skill"]
454
+ findings: list[dict] = []
455
+ missing_counts: dict[str, int] = {}
456
+ for entry in skills:
457
+ found, missing = skill_findings(entry)
458
+ findings += found
459
+ for field in missing:
460
+ missing_counts[field] = missing_counts.get(field, 0) + 1
461
+ groups = build_groups(norm["entries"], norm["rules"])
462
+ for group in groups:
463
+ if group["kind"] == "skill" and group["class"] == "same-name-differs":
464
+ for ref in group["members"]:
465
+ findings.append({"ref": ref, "code": "drift", "fact": _("同名技能内容不一致({0} 份),来源是否相同需要 origin 才能判断").format(
466
+ len(group["members"])), "threshold": None, "source": None, "group": group["id"]})
467
+ notes = [_("{0} 个技能缺少 {1}:这一项没有检查(inventory 未提供)").format(count, field)
468
+ for field, count in sorted(missing_counts.items())]
469
+ stale_unknown = sum(1 for entry in skills if entry["evidence"] != "unknown" and not entry["origin"]["version"]
470
+ and entry["stale"] is None)
471
+ if stale_unknown:
472
+ notes.append(_("过期:{0} 个技能的来源或版本无法识别,显示为未知(不用修改时间推断)").format(stale_unknown))
473
+ similar: list[dict] = []
474
+ if include_description:
475
+ similar, why = similar_pairs(skills)
476
+ if why:
477
+ notes.append(why)
478
+ else:
479
+ notes.append(_("description 相似度提示默认不做;加 --include-description 才比较(文本只在本机内存里用)"))
480
+ notes.append(_("MCP 工具定义的上下文成本:未知(需要连接服务器,本命令不连接)"))
481
+ return {"findings": findings, "cost": cost_per_client(skills), "similar": similar, "notes": notes,
482
+ "similarity": {"threshold": SIMILARITY_THRESHOLD, "enabled": include_description,
483
+ "basis": _("初始值 0.6,没有外部依据;只作提示")},
484
+ "thresholds": {"description_chars_spec": SPEC_DESCRIPTION_CHARS, "description_chars_claude": CLAUDE_DESCRIPTION_CAP_CHARS,
485
+ "skill_md_lines_advisory": SPEC_SKILL_MD_LINES}}
486
+
487
+
488
+ # ---------------------------------------------------------------- 组合:清单、概览、详情
489
+
490
+ def tags_for(entries: list[dict], groups: list[dict], findings: list[dict]) -> dict[str, list[str]]:
491
+ result: dict[str, list[str]] = {entry["ref"]: [] for entry in entries}
492
+ size: dict[str, int] = {}
493
+ for group in groups:
494
+ for ref in group["members"]:
495
+ size[ref] = max(size.get(ref, 0), len(group["members"]))
496
+ for entry in entries:
497
+ tags = result[entry["ref"]]
498
+ if entry["evidence"] == "unknown":
499
+ tags.append(_("未知"))
500
+ if size.get(entry["ref"]):
501
+ tags.append(_("重复 {0}").format(size[entry["ref"]]))
502
+ if entry.get("has_inline_secret"):
503
+ tags.append(_("含内联密钥值"))
504
+ seen: set[tuple[str, str]] = set() # 同一条目同一类发现只标一次(按代码去重,不比较译文)
505
+ for finding in findings:
506
+ if finding["code"] in TAG_LABEL and finding["ref"] in result and (finding["ref"], finding["code"]) not in seen:
507
+ seen.add((finding["ref"], finding["code"]))
508
+ result[finding["ref"]].append(_(TAG_LABEL[finding["code"]]))
509
+ return result
510
+
511
+
512
+ def summarize(norm: dict, groups: list[dict], cost: list[dict]) -> dict:
513
+ entries = norm["entries"]
514
+ unknown_entries = sum(1 for entry in entries if entry["evidence"] == "unknown")
515
+ return {"skills": sum(entry["kind"] == "skill" for entry in entries), "mcps": sum(entry["kind"] == "mcp" for entry in entries),
516
+ "clients": norm["clients"], "per_client": cost,
517
+ "duplicate_groups": {"total": len(groups), "mcp": sum(group["kind"] == "mcp" for group in groups),
518
+ "skill": sum(group["kind"] == "skill" for group in groups)},
519
+ "unknown": unknown_entries + norm["unknown_extra"],
520
+ "unknown_detail": {"entries": unknown_entries, "unreadable_sources": norm["unknown_extra"]}}
521
+
522
+
523
+ def analyse(inventory: dict) -> dict:
524
+ norm = normalize(inventory)
525
+ groups = build_groups(norm["entries"], norm["rules"])
526
+ skills = [entry for entry in norm["entries"] if entry["kind"] == "skill"]
527
+ findings = [finding for entry in skills for finding in skill_findings(entry)[0]]
528
+ return {"norm": norm, "groups": groups, "findings": findings,
529
+ "tags": tags_for(norm["entries"], groups, findings),
530
+ "summary": summarize(norm, groups, cost_per_client(skills))}
531
+
532
+
533
+ SORT_KIND = {"skill": 0, "mcp": 1}
534
+
535
+
536
+ def listing(analysis: dict, *, kind: str | None = None, client: str | None = None, scope: str | None = None,
537
+ group: str = "client") -> dict:
538
+ entries = [entry for entry in analysis["norm"]["entries"]
539
+ if (kind is None or entry["kind"] == kind) and (client is None or entry["client"] == client)
540
+ and (scope is None or entry["scope"] == scope)]
541
+ entries.sort(key=lambda entry: (entry["client"], SORT_KIND[entry["kind"]], entry["scope"], entry["store"] or "", entry["name"]))
542
+ rows = [{**public(entry), "tags": analysis["tags"][entry["ref"]]} for entry in entries]
543
+ if group == "dup":
544
+ parts = []
545
+ for item in analysis["groups"]:
546
+ members = [row for row in rows if row["ref"] in item["members"]]
547
+ if members and (kind is None or item["kind"] == kind):
548
+ parts.append({"key": item["id"], "label": item["label"], "name": item["name"], "entries": members})
549
+ return {"group_by": group, "groups": parts}
550
+ field = "scope" if group == "scope" else "client"
551
+ keys: dict[str, list[dict]] = {}
552
+ for row in rows:
553
+ keys.setdefault(row[field], []).append(row)
554
+ return {"group_by": group, "groups": [{"key": key, "label": key, "entries": members} for key, members in keys.items()]}
555
+
556
+
557
+ def dups(analysis: dict, kind: str | None = None) -> dict:
558
+ return {"groups": [public_group(group) for group in analysis["groups"] if kind is None or group["kind"] == kind]}
559
+
560
+
561
+ REACH = {"project": "project", "local": "project", "user": "all", "personal": "all", "managed": "all", "enterprise": "all",
562
+ "desktop": "app"}
563
+ REACH_LABEL = {"project": N_("本项目(仅在此项目里生效)"), "all": N_("所有项目共用(用户级)"),
564
+ "app": N_("仅 Desktop 应用"), "unknown": N_("作用域未知")}
565
+
566
+
567
+ def by_project(analysis: dict, kind: str | None = None) -> dict:
568
+ """按「在哪些项目里生效」看:本项目专有 / 所有项目共用 / Desktop 应用 / 未知。只含本项目与本机已知存储。"""
569
+ rows = listing(analysis, kind=kind)["groups"]
570
+ entries = [row for part in rows for row in part["entries"]]
571
+ parts = []
572
+ for key in ("project", "all", "app", "unknown"):
573
+ members = [row for row in entries if ("app" if _is_desktop(row["client"]) else REACH.get(row["scope"], "unknown")) == key]
574
+ if members:
575
+ parts.append({"key": key, "label": _(REACH_LABEL[key]), "entries": members})
576
+ return {"group_by": "project", "groups": parts, "known_projects": analysis["norm"]["projects"]}
577
+
578
+
579
+ def find_entries(analysis: dict, token: str) -> list[dict]:
580
+ entries = analysis["norm"]["entries"]
581
+ for matches in (lambda entry: entry["ref"] == token,
582
+ lambda entry: entry["ref"].split(":", 1)[-1] == token, # 省略类型前缀:name@client:scope
583
+ lambda entry: entry["name"] == token):
584
+ found = [entry for entry in entries if matches(entry)]
585
+ if found:
586
+ return found
587
+ return []
588
+
589
+
590
+ def show_entry(analysis: dict, entry: dict) -> dict:
591
+ groups = [group["id"] for group in analysis["groups"] if entry["ref"] in group["members"]]
592
+ findings = [finding for finding in analysis["findings"] if finding["ref"] == entry["ref"]]
593
+ return {**public(entry), "tags": analysis["tags"][entry["ref"]], "groups": groups, "findings": findings}
594
+
595
+
596
+ # ---------------------------------------------------------------- 渲染(文字)
597
+
598
+ def pad(text: str, width: int) -> str:
599
+ return text + " " * max(0, width - display_width(text))
600
+
601
+
602
+ def fmt_bytes(value: int | None) -> str:
603
+ if value is None:
604
+ return _("未知")
605
+ return f"{value} B" if value < 1024 else f"{value / 1024:.1f} KB"
606
+
607
+
608
+ def scope_text(scope: str) -> str:
609
+ return _(SCOPE_LABEL[scope]) if scope in SCOPE_LABEL else scope
610
+
611
+
612
+ def evidence_text(evidence: str) -> str:
613
+ return _("未知") if evidence == "unknown" else evidence
614
+
615
+
616
+ def badge(entry: dict) -> str:
617
+ mark = BADGE.get(entry["evidence"], "?")
618
+ return S.dim(mark) if entry["evidence"] == "unknown" else mark
619
+
620
+
621
+ def origin_value(entry: dict) -> str:
622
+ origin = entry.get("origin") or {}
623
+ if not origin.get("type") and not origin.get("id"):
624
+ return _("未知")
625
+ base = origin.get("id") or origin.get("type")
626
+ kind = f"{origin['type']}:" if origin.get("type") and origin.get("id") else ""
627
+ return kind + base + (f"@{origin['version']}" if origin.get("version") else "")
628
+
629
+
630
+ def origin_text(entry: dict) -> str:
631
+ return _("来源 {0}").format(origin_value(entry))
632
+
633
+
634
+ def entry_columns(entry: dict, show_refs: bool = False) -> list[tuple[str, str]]:
635
+ """(列名, 文字);缩列时按 来源 → 体积 → desc 字节 的顺序先丢,条目名与作用域永不丢。
636
+ show_refs:清单里至少有一项带 referenced_by 时整列显示(缺失的行显示 —),否则整列不出现。"""
637
+ if entry["kind"] == "skill":
638
+ columns = [("size", fmt_bytes(entry.get("skill_md_bytes"))),
639
+ ("desc", _("desc {0}").format(fmt_bytes(entry.get("description_bytes")))),
640
+ ("origin", origin_text(entry))]
641
+ else:
642
+ columns = [("transport", entry.get("transport") or _("未知")),
643
+ ("fingerprint", _("指纹 {0}…").format(entry["fingerprint8"]) if entry.get("fingerprint8") else _("指纹 未知"))]
644
+ if show_refs:
645
+ refs = entry.get("referenced_by")
646
+ columns.append(("refs", _("被 {0} 条规则引用").format(len(refs)) if refs else _("被引用 —")))
647
+ return columns
648
+
649
+
650
+ SHRINK_ORDER = ("origin", "size", "desc") # 横向放不下时先丢哪一列
651
+
652
+
653
+ def entry_line(entry: dict, name_width: int, *, show_client: bool = False, width: int | None = None,
654
+ show_refs: bool = False) -> list[str]:
655
+ """一个条目的一行;放不下时先按 来源 → 体积 → desc 字节 缩列,标签仍放不下就整块移到下一行。
656
+ 条目名与作用域永不省略,也不在词内换行。"""
657
+ width = width or term_width()
658
+ scope = scope_text(entry["scope"])
659
+ place = f"{entry['client']}:{scope}" if show_client else scope
660
+ columns = entry_columns(entry, show_refs)
661
+ tags = " ".join(f"[{tag}]" for tag in entry.get("tags", []))
662
+ head = f" {badge(entry)} {S.bold(pad(entry['name'], name_width))} {pad(place, 10)}"
663
+ head_width = display_width(f" X {pad(entry['name'], name_width)} {pad(place, 10)}")
664
+
665
+ def total(items: list[tuple[str, str]], with_tags: bool) -> int:
666
+ body = " ".join(text for _col, text in items)
667
+ return head_width + (2 + display_width(body) if body else 0) + (2 + display_width(tags) if tags and with_tags else 0)
668
+
669
+ while total(columns, True) > width:
670
+ drop = next((name for name in SHRINK_ORDER if any(col[0] == name for col in columns)), None)
671
+ if drop is None:
672
+ break
673
+ columns = [col for col in columns if col[0] != drop]
674
+ body = " ".join(text for _col, text in columns)
675
+ line = f"{head} {S.dim(body)}" if body else head
676
+ if not tags:
677
+ return [line]
678
+ if total(columns, True) <= width:
679
+ return [f"{line} {S.yellow(tags)}"]
680
+ return [line, f" {S.yellow(tags)}"]
681
+
682
+
683
+ def render_summary(summary: dict) -> list[str]:
684
+ clients = " / ".join(f"{name}{_('(只读)') if _is_desktop(name) else ''}" for name in summary["clients"]) or _("无")
685
+ lines = [_("技能 {0} 个 · MCP {1} 个 · 客户端 {2}").format(summary["skills"], summary["mcps"], clients)]
686
+ for row in summary["per_client"]:
687
+ if not row["counted"] and not row["uncounted"]:
688
+ continue
689
+ evidence = _("、").join(evidence_text(item) for item in row["evidence"]) or _("未知")
690
+ extra = _(";另有 {0} 个未计入").format(row["uncounted"]) if row["uncounted"] else ""
691
+ if not row["counted"]:
692
+ lines.append(_("每会话 description 常驻:{0} 未知(没有可计入的条目){1}").format(row["client"], extra))
693
+ continue
694
+ lines.append(_("每会话 description 常驻:{0} ≈ {1}(证据:{2}){3}").format(
695
+ row["client"], fmt_bytes(row["resident_bytes"]), evidence, extra))
696
+ dup = summary["duplicate_groups"]
697
+ lines.append(_("重复 {0} 组(MCP {1} · 技能 {2}) 未知 {3} 项(证据不足,不做结论)").format(
698
+ dup["total"], dup["mcp"], dup["skill"], summary["unknown"]))
699
+ return lines
700
+
701
+
702
+ def render_unavailable(reason: str) -> list[str]:
703
+ return [S.yellow(_("不可用:{0}").format(reason)),
704
+ S.dim(_("需要 agent-pack 提供 agenthelm inventory;更新 agent-pack 或运行时后再试。其他功能不受影响。"))]
705
+
706
+
707
+ def render_list(data: dict, summary: dict) -> list[str]:
708
+ lines = render_summary(summary)
709
+ if not data["groups"]:
710
+ return lines + [S.dim(_("没有匹配的条目。"))]
711
+ show_client = data["group_by"] != "client"
712
+ show_refs = any(row.get("referenced_by") for part in data["groups"] for row in part["entries"])
713
+ name_width = min(40, max(display_width(row["name"]) for part in data["groups"] for row in part["entries"]))
714
+ for part in data["groups"]:
715
+ evidences = {row["evidence"] for row in part["entries"]}
716
+ label = _("{0} · 证据 {1}").format(part["label"], _("、").join(evidence_text(item) for item in sorted(evidences, key=EVIDENCE_LEVELS.index)))
717
+ lines.append(S.bold(label))
718
+ previous = None
719
+ for row in part["entries"]:
720
+ section = (row["kind"], row["scope"], row["store"])
721
+ if data["group_by"] == "client" and section != previous:
722
+ previous = section
723
+ count = sum((r["kind"], r["scope"], r["store"]) == section for r in part["entries"])
724
+ lines.append(S.dim(_(" {0} · {1} · {2} {3} 个").format(
725
+ _(KIND_LABEL[row["kind"]]), scope_text(row["scope"]), row["store"] or _("未知"), count)))
726
+ lines += entry_line(row, name_width, show_client=show_client, show_refs=show_refs)
727
+ lines.append(S.dim(_("证据:● file(读到文件)· ⚙ setting · ⌘ cli · ? 未知(不做结论)")))
728
+ return lines
729
+
730
+
731
+ def render_projects(data: dict, summary: dict) -> list[str]:
732
+ lines = render_list(data, summary)
733
+ projects = data.get("known_projects") or []
734
+ if projects:
735
+ lines.append(S.bold(_("已同步过的其他项目")))
736
+ lines += [f" {item['name']}" + (f" {item['last_synced']}" if item.get("last_synced") else "") for item in projects]
737
+ else:
738
+ lines.append(S.dim(_("其他项目:inventory 没有提供已知项目列表,这里只显示本项目;没在本机同步过的项目不可见")))
739
+ return lines
740
+
741
+
742
+ def render_dups(data: dict) -> tuple[list[str], list[dict]]:
743
+ lines: list[str] = []
744
+ numbered: list[dict] = []
745
+ for kind, title in (("mcp", _("重复 MCP({0} 组)")), ("skill", _("重复技能({0} 组)"))):
746
+ members = [group for group in data["groups"] if group["kind"] == kind]
747
+ if not members:
748
+ continue
749
+ lines.append(S.bold(title.format(len(members))))
750
+ for group in members:
751
+ numbered.append(group)
752
+ lines += render_group(len(numbered), group)
753
+ if not numbered:
754
+ lines.append(S.green(_("没有发现重复。")))
755
+ return lines, numbered
756
+
757
+
758
+ def render_group(number: int, group: dict) -> list[str]:
759
+ head = f" {S.bold(S.cyan(f'{number:>2}'))} {S.bold(group['name'])} {_(group['label'])}"
760
+ if group["cross_client"]:
761
+ head += S.dim(_("(跨客户端)"))
762
+ lines = [head + S.dim(_(" 分组 {0}").format(group["id"]))]
763
+ for ref in group["members"]:
764
+ lines.append(f" {ref}")
765
+ for text in group["effective"]["lines"]:
766
+ lines.append(" " + (S.yellow(text) if not group["effective"]["known"] else text))
767
+ if group["cross_client"] and group["class"] != "same-name-unknown":
768
+ lines.append(S.dim(_(" 跨客户端重复:各客户端加载各自的配置,可保留,不推荐退役")))
769
+ return lines
770
+
771
+
772
+ def render_show(detail: dict) -> list[str]:
773
+ def row(label: str, value: Any) -> str:
774
+ text = _("未知") if value is None else (_("是") if value is True else _("否") if value is False else str(value))
775
+ return f" {pad(label, 18)}{text}"
776
+
777
+ lines = [f"{S.bold(detail['name'])} {S.dim(detail['ref'])}",
778
+ row(_("类型"), _(KIND_LABEL[detail["kind"]])), row(_("客户端"), detail["client"]),
779
+ row(_("作用域"), scope_text(detail["scope"])), row(_("存储"), detail["store"]),
780
+ row(_("证据"), evidence_text(detail["evidence"]))]
781
+ if detail["kind"] == "skill":
782
+ origin = detail["origin"]
783
+ lines += [row(_("SKILL.md 体积"), fmt_bytes(detail["skill_md_bytes"])),
784
+ row(_("SKILL.md 行数"), detail["skill_md_lines"]),
785
+ row(_("description 字节"), fmt_bytes(detail["description_bytes"])),
786
+ row(_("description 字符"), detail["description_chars"]),
787
+ row(_("目录体积 / 文件数"), f"{fmt_bytes(detail['dir_bytes'])} / {detail['file_count'] if detail['file_count'] is not None else _('未知')}"),
788
+ row(_("内容摘要(前 8 位)"), detail["content_sha8"]),
789
+ row(_("符号链接"), detail["is_symlink"]),
790
+ row(_("来源"), origin_value(detail)),
791
+ row(_("最新已知版本"), origin["latest_known"]), row(_("是否加载"), detail["loaded"])]
792
+ else:
793
+ lines += [row(_("传输"), detail["transport"]), row(_("指纹(前 8 位)"), detail["fingerprint8"]),
794
+ row(_("环境变量名"), _("、").join(detail["env_var_names"]) if detail["env_var_names"] else
795
+ (_("无") if detail["env_var_names"] == [] else None)),
796
+ row(_("含内联密钥值"), detail["has_inline_secret"]), row(_("远程主机"), detail["url_host"]),
797
+ S.dim(_(" 不显示命令行参数、url 全文、环境变量值与 headers。"))]
798
+ if detail.get("referenced_by"):
799
+ lines.append(row(_("被引用"), _("被 {0} 条规则引用").format(len(detail["referenced_by"]))))
800
+ lines += [f" {item['rule_id']}" + (f" {item['source']}" if item["source"] else "") for item in detail["referenced_by"]]
801
+ if detail["tags"]:
802
+ lines.append(row(_("机械发现"), " ".join(f"[{tag}]" for tag in detail["tags"])))
803
+ for finding in detail["findings"]:
804
+ lines.append(f" {finding['fact']}" + (S.dim(_("(阈值:{0};来源:{1})").format(finding["threshold"], finding["source"]))
805
+ if finding.get("threshold") and finding.get("source") else ""))
806
+ return lines
807
+
808
+
809
+ def render_check(data: dict) -> list[str]:
810
+ lines = [S.bold(_("技能体检:只列机械事实与阈值;不打分、不排名、不建议删除"))]
811
+ by_ref: dict[str, list[dict]] = {}
812
+ for finding in data["findings"]:
813
+ by_ref.setdefault(finding["ref"], []).append(finding)
814
+ if by_ref:
815
+ for ref, items in sorted(by_ref.items()):
816
+ lines.append(f" {S.bold(ref)}")
817
+ for item in items:
818
+ extra = S.dim(_("(阈值:{0};来源:{1})").format(item["threshold"], item["source"])) if item.get("threshold") and item.get("source") else ""
819
+ lines.append(f" · {item['fact']}{extra}")
820
+ else:
821
+ lines.append(S.green(_("没有机械发现。")))
822
+ lines.append(S.bold(_("每会话 description 加载成本")))
823
+ for row in data["cost"]:
824
+ evidence = _("、").join(evidence_text(item) for item in row["evidence"]) or _("未知")
825
+ if not row["counted"]:
826
+ lines.append(_(" {0}:未知(没有可计入的条目;{1} 个未计入)").format(row["client"], row["uncounted"]))
827
+ continue
828
+ lines.append(_(" {0}:{1}({2} 个已计入,{3} 个未计入;证据 {4})").format(
829
+ row["client"], fmt_bytes(row["resident_bytes"]), row["counted"], row["uncounted"], evidence))
830
+ estimate = row["token_estimate"]
831
+ lines.append(S.dim(_(" 粗估 {0}–{1} token({2})").format(estimate["low"], estimate["high"], estimate["label"])))
832
+ if row["capped"]:
833
+ lines.append(S.dim(_(" 其中 {0} 个按 Claude 的 {1} 字符截断上限折算").format(row["capped"], CLAUDE_DESCRIPTION_CAP_CHARS)))
834
+ if not data["cost"]:
835
+ lines.append(S.dim(_(" 没有技能条目。")))
836
+ if data["similarity"]["enabled"]:
837
+ lines.append(S.bold(_("description 相似(机械判断,不代表功能重复;阈值 {0},没有外部依据)").format(data["similarity"]["threshold"])))
838
+ lines += [f" {pair['refs'][0]} ≈ {pair['refs'][1]}" for pair in data["similar"]] or [S.dim(_(" 没有达到阈值的技能对。"))]
839
+ lines += [S.dim(f" {note}") for note in data["notes"]]
840
+ return lines
841
+
842
+
843
+ # ---------------------------------------------------------------- provider 共用方法(真实与演示项目各自提供 _ext_load)
844
+
845
+ class ExtensionsMixin:
846
+ """``extensions_*`` 方法:一次取数、会话内缓存、只读。子类实现 ``_ext_load(include_description)`` 返回 {state, reason, inventory}。"""
847
+
848
+ def _ext_load(self, include_description: bool) -> dict: # pragma: no cover - 子类实现
849
+ raise NotImplementedError
850
+
851
+ def extensions_refresh(self) -> None:
852
+ self.__dict__["_ext_cache"] = {}
853
+ self.__dict__.pop("_ext_dedupe", None)
854
+
855
+ def extensions_dedupe_groups(self) -> list[dict]:
856
+ """``agenthelm dedupe --list`` 的分组(写入动作只认这些);演示项目与旧版 agenthelm 为空。"""
857
+ if getattr(self, "simulated", False):
858
+ return []
859
+ if "_ext_dedupe" not in self.__dict__:
860
+ import project_ext_actions as actions # noqa: PLC0415
861
+
862
+ self.__dict__["_ext_dedupe"] = actions.dedupe_groups(self.host, self.root) or []
863
+ return self.__dict__["_ext_dedupe"]
864
+
865
+ def _extensions(self, include_description: bool = False) -> dict:
866
+ cache = self.__dict__.setdefault("_ext_cache", {})
867
+ key = True if True in cache else bool(include_description)
868
+ if key not in cache:
869
+ result = self._ext_load(key)
870
+ cache[key] = {**result, "analysis": analyse(result["inventory"])} if result["state"] == "available" else result
871
+ return cache[key]
872
+
873
+ def extensions_state(self) -> dict:
874
+ result = self._extensions()
875
+ return {"state": result["state"], "reason": result["reason"]}
876
+
877
+ def extensions_summary(self) -> dict:
878
+ result = self._extensions()
879
+ return {**self.extensions_state(), **({"summary": result["analysis"]["summary"]} if result["state"] == "available" else {})}
880
+
881
+ def extensions_list(self, kind: str | None = None, client: str | None = None, scope: str | None = None,
882
+ group: str = "client") -> dict:
883
+ result = self._extensions()
884
+ if result["state"] != "available":
885
+ return self.extensions_state()
886
+ analysis = result["analysis"]
887
+ return {**self.extensions_state(), **listing(analysis, kind=kind, client=client, scope=scope, group=group),
888
+ "filters": {"kind": kind, "client": client, "scope": scope}, "summary": analysis["summary"],
889
+ "notes": [_("只含本项目与本机的已知存储;没在本机同步过的项目不可见")]}
890
+
891
+ def extensions_dups(self, kind: str | None = None) -> dict:
892
+ result = self._extensions()
893
+ if result["state"] != "available":
894
+ return self.extensions_state()
895
+ analysis = result["analysis"]
896
+ return {**self.extensions_state(), **dups(analysis, kind), "summary": analysis["summary"],
897
+ "notes": [_("只含本项目与本机的已知存储;没在本机同步过的项目不可见")]}
898
+
899
+ def extensions_show(self, token: str) -> dict:
900
+ from project_base import EntryError # noqa: PLC0415
901
+
902
+ result = self._extensions()
903
+ if result["state"] != "available":
904
+ return self.extensions_state()
905
+ analysis = result["analysis"]
906
+ for group in analysis["groups"]:
907
+ if group["id"] == token:
908
+ return {**self.extensions_state(), "view": "group", "group": public_group(group)}
909
+ found = find_entries(analysis, token)
910
+ if not found:
911
+ raise EntryError(_("没有这个条目:{0}").format(token), "not-found",
912
+ [_("用 extensions list 查看全部条目的引用(ref)")])
913
+ if len(found) > 1:
914
+ raise EntryError(_("“{0}”对应多个条目,请用完整引用").format(token), "ambiguous",
915
+ [entry["ref"] for entry in found])
916
+ return {**self.extensions_state(), "view": "entry", "entry": show_entry(analysis, found[0])}
917
+
918
+ def extensions_projects(self, kind: str | None = None) -> dict:
919
+ result = self._extensions()
920
+ if result["state"] != "available":
921
+ return self.extensions_state()
922
+ analysis = result["analysis"]
923
+ return {**self.extensions_state(), **by_project(analysis, kind), "summary": analysis["summary"]}
924
+
925
+ def extensions_health_finding(self) -> dict | None:
926
+ """health 里的一条建议级(info)发现:有需要关注的重复时指向第 9 屏。跨客户端的重复不计入;不改变 ok 与退出码。"""
927
+ if self.extensions_capability()[0] != "available":
928
+ return None
929
+ result = self._extensions()
930
+ if result["state"] != "available":
931
+ return None
932
+ groups = [group for group in result["analysis"]["groups"] if not group["cross_client"]]
933
+ if not groups:
934
+ return None
935
+ names = _("、").join(group["name"] for group in groups[:3]) + (_("……共 {0} 组").format(len(groups)) if len(groups) > 3 else "")
936
+ return {"id": "extensions-duplicates", "level": "info", "area": _("技能与 MCP"),
937
+ "title": _("发现 {0} 组重复的技能或 MCP").format(len(groups)),
938
+ "reason": names + _("(跨客户端的重复不计入)"),
939
+ "impact": _("只影响 AI 客户端加载(可能重复占用上下文,或发生同名覆盖);不影响本菜单与项目文件"),
940
+ "next": [{"label": _("在「技能与 MCP」里查看重复(只读)"), "action": f"ext:{groups[0]['id']}"}]}
941
+
942
+ # ---- 写入动作(默认预览):转发给 agenthelm relocate / dedupe,或写 Profile 声明(见 project_ext_actions)
943
+ def _ext_actions(self):
944
+ import project_ext_actions as actions # noqa: PLC0415
945
+
946
+ if getattr(self, "simulated", False):
947
+ from project_base import EntryError # noqa: PLC0415
948
+
949
+ raise EntryError(_("演示项目不执行技能与 MCP 的写入动作"), "unavailable", [_("在真实项目里运行")])
950
+ return actions
951
+
952
+ def extensions_move(self, ref: str, to: str, **options: Any) -> dict:
953
+ return self._ext_actions().move(self.host, self.root, ref, to, **options)
954
+
955
+ def extensions_dedupe(self, group_id: str, **options: Any) -> dict:
956
+ return self._ext_actions().dedupe(self.host, self.root, group_id, **options)
957
+
958
+ def extensions_scope(self, ref: str, effective: str, **options: Any) -> dict:
959
+ return self._ext_actions().scope(self, ref, effective, **options)
960
+
961
+ def extensions_readback(self, action: str, result: dict, group_id: str | None = None) -> dict:
962
+ actions = self._ext_actions()
963
+ if action == "move":
964
+ return actions.readback_move(self.host, self.root, result)
965
+ return actions.readback_dedupe(self.host, self.root, group_id or "", result)
966
+
967
+ def extensions_check(self, include_description: bool = False) -> dict:
968
+ result = self._extensions(include_description)
969
+ if result["state"] != "available":
970
+ return self.extensions_state()
971
+ return {**self.extensions_state(), **check(result["analysis"]["norm"], include_description)}