@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,989 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only observation of the Skills and MCP servers each client can see (``agenthelm inventory``).
3
+
4
+ The JSON shape is a contract (``schema_version``, documented in ``references/inventory-contract.md``): later write
5
+ commands and menus build on it, so keys are only ever appended. Nothing here writes, runs a client command line or
6
+ reads a settings key; every observation is ``evidence: file`` (read from a file) or ``unknown`` (could not be
7
+ decided, for example a corrupt file). MCP ``env`` values, ``headers`` values and tokens never appear in any output.
8
+
9
+ Reuses ``agent_pack_config`` for JSON/TOML readers, the MCP normaliser's secret patterns and version parsing.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ import tomllib
20
+ from pathlib import Path
21
+ from typing import Any
22
+ from urllib.parse import parse_qsl, urlsplit, urlunsplit
23
+
24
+ RUNTIME_DIR = Path(__file__).resolve().parent
25
+ if str(RUNTIME_DIR) not in sys.path:
26
+ sys.path.insert(0, str(RUNTIME_DIR))
27
+ import agent_pack_config as core # noqa: E402
28
+ from i18n_agent_pack import _, N_ # noqa: E402
29
+ import agent_pack_clients as client_registry # noqa: E402
30
+
31
+ SCHEMA_VERSION = 1
32
+ CLIENTS = client_registry.default_ids()
33
+ DESKTOP = "claude-desktop" # a separate target: the standalone CLI does not read claude_desktop_config.json
34
+ ALL_CLIENTS = client_registry.all_ids() # the default set is CLIENTS; claude-desktop must be named (or ``all``)
35
+ TYPES = ("skills", "mcp", "all")
36
+ SCOPES = ("project", "user", "all")
37
+ EVIDENCE = ("file", "setting", "cli", "unknown") # setting / cli are reserved: this version never reads them
38
+ AGENTHELM_PLUGINS = frozenset({"agent-pack", "agents-init", "opinion-manager", "project-orchestrator"})
39
+ AGENTHELM_REPOSITORY = "lc4t/agenthelm"
40
+ OVERLAP_THRESHOLD = 0.8 # token Jaccard similarity; a hint only, never a semantic judgement
41
+ OVERLAP_MIN_TOKENS = 5
42
+ MAX_SKILL_MD = 4 * 1024 * 1024
43
+ MAX_CONFIG = 32 * 1024 * 1024
44
+ PROJECT = "<project>"
45
+ DESCRIPTION_LIMIT = 1536 # characters of description text shown with --include-description
46
+ MAX_DIR_FILES = 20000
47
+ PRIMARY_SKILL_STORE = { # refs of entries in any other store carry a ``#agents`` suffix so a ref stays unique
48
+ ("claude", "user"): "~/.claude/skills", ("claude", "project"): f"{PROJECT}/.claude/skills",
49
+ ("codex", "user"): "~/.codex/skills", ("codex", "project"): f"{PROJECT}/.agents/skills",
50
+ ("cursor", "user"): "~/.cursor/skills", ("cursor", "project"): f"{PROJECT}/.cursor/skills",
51
+ }
52
+
53
+ # Official documentation the precedence conclusions rest on (read 2026-11-11, see references/inventory-contract.md).
54
+ DOC_CLAUDE_MCP = "https://code.claude.com/docs/en/mcp"
55
+ DOC_CLAUDE_SKILLS = "https://code.claude.com/docs/en/skills"
56
+ DOC_CODEX_SKILLS = "https://learn.chatgpt.com/docs/build-skills"
57
+ DOC_CODEX_MCP = "https://learn.chatgpt.com/docs/extend/mcp?surface=cli"
58
+ DOC_DESKTOP_PATHS = "https://modelcontextprotocol.io/docs/develop/connect-local-servers"
59
+ DOC_DESKTOP_MCP = "https://code.claude.com/docs/en/desktop#mcp-servers-from-the-claude-desktop-chat-app"
60
+ DESKTOP_FILE = "claude_desktop_config.json"
61
+ DESKTOP_STORE_NAME = "desktop-config" # the ``store`` label of Desktop entries; the real path is in ``desktop.path``
62
+ DESKTOP_STORES = { # official documentation (MCP site, read 2026-11-18); Windows (%APPDATA%\\Claude) is documentation only
63
+ "darwin": f"~/Library/Application Support/Claude/{DESKTOP_FILE}",
64
+ "linux": f"~/.config/Claude/{DESKTOP_FILE}",
65
+ }
66
+
67
+ # (scope, store) per client, in listing order. ``~`` is the home directory, ``<project>`` the project root.
68
+ SKILL_STORES = {
69
+ "claude": (("user", "~/.claude/skills"), ("project", f"{PROJECT}/.claude/skills")),
70
+ "codex": (("user", "~/.codex/skills"), ("user", "~/.agents/skills"), ("project", f"{PROJECT}/.agents/skills")),
71
+ "cursor": (("user", "~/.cursor/skills"), ("user", "~/.agents/skills"),
72
+ ("project", f"{PROJECT}/.cursor/skills"), ("project", f"{PROJECT}/.agents/skills")),
73
+ }
74
+ MCP_STORES = {
75
+ "claude": (("user", "~/.claude.json"), ("local", "~/.claude.json#projects"), ("project", f"{PROJECT}/.mcp.json")),
76
+ "codex": (("user", "~/.codex/config.toml"), ("project", f"{PROJECT}/.codex/config.toml")),
77
+ "cursor": (("user", "~/.cursor/mcp.json"), ("project", f"{PROJECT}/.cursor/mcp.json")),
78
+ }
79
+ SCOPE_ORDER = {"user": 0, "local": 1, "project": 2}
80
+
81
+ # Reason codes in ``unknown[]`` and per-entry ``issues[]`` / ``notes[]`` stay English identifiers (data); the text
82
+ # renderer translates them.
83
+ REASON_TEXT = {
84
+ "invalid-json": N_("JSON 无法解析"),
85
+ "invalid-toml": N_("TOML 无法解析"),
86
+ "unreadable": N_("无法读取"),
87
+ "too-large": N_("文件过大,未读取"),
88
+ "unexpected-structure": N_("结构不是预期的对象"),
89
+ "not-found": N_("文件不存在"),
90
+ "platform-unsupported": N_("本命令只解析 macOS 与 Linux 的路径"),
91
+ "claude-local-structure-unrecognized": N_("~/.claude.json 里按项目路径存放的条目结构无法识别"),
92
+ "broken-symlink": N_("符号链接已失效"),
93
+ "frontmatter-missing": N_("SKILL.md 没有可读的 frontmatter"),
94
+ "description-missing": N_("frontmatter 没有 description"),
95
+ "name-mismatch": N_("frontmatter 的 name 与目录名不同"),
96
+ "skill-md-too-large": N_("SKILL.md 过大,未解析"),
97
+ "variable-expansion-unconfirmed": N_("官方文档没有说明该文件是否展开 ${VAR}"),
98
+ "dir-too-large": N_("目录文件过多,未统计大小与文件数"),
99
+ "codex-project-requires-trust": N_("Codex 只在受信任的项目里读取项目级配置;本工具读不到信任记录"),
100
+ }
101
+
102
+
103
+ # ------------------------------------------------------------------ paths and redaction
104
+
105
+ def display_path(path: Path | str, home: Path, project: Path | None) -> str:
106
+ """``~``-abbreviated and ``<project>``-relative form of an absolute path, so output never leaks the home layout."""
107
+ text = str(path)
108
+ for base, label in ((project, PROJECT), (home, "~")):
109
+ if base is None:
110
+ continue
111
+ prefix = str(base)
112
+ if text == prefix:
113
+ return label
114
+ if text.startswith(prefix + os.sep):
115
+ return label + text[len(prefix):]
116
+ return text
117
+
118
+
119
+ def resolve_store(store: str, home: Path, project: Path | None) -> Path | None:
120
+ if store.startswith(PROJECT):
121
+ return None if project is None else project / store[len(PROJECT) + 1:]
122
+ if store.startswith("~"):
123
+ return home / store[2:].split("#", 1)[0]
124
+ return Path(store)
125
+
126
+
127
+ ENV_REF = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}")
128
+ _VAR_DEFAULT_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*):-[^}]*\}")
129
+ REDACTED = "<redacted>"
130
+
131
+
132
+ def _plain_variables(text: str) -> str:
133
+ """``${VAR:-default}`` keeps only the variable name: a default value is a value."""
134
+ return _VAR_DEFAULT_RE.sub(lambda match: "${" + match.group(1) + "}", text)
135
+
136
+
137
+ def _safe_reference(text: str) -> bool:
138
+ return core._safe_env_reference(text)
139
+
140
+
141
+ def _redact_args(args: list[Any]) -> list[str]:
142
+ """Arguments with credential-looking values replaced; ``${VAR}`` references (names) stay."""
143
+ result: list[str] = []
144
+ previous_secret_flag = False
145
+ for raw in args:
146
+ text = _plain_variables(str(raw))
147
+ secret = False
148
+ if previous_secret_flag and not text.startswith("-") and not _safe_reference(text):
149
+ result.append(REDACTED)
150
+ previous_secret_flag = False
151
+ continue
152
+ previous_secret_flag = False
153
+ if text.startswith("-") and "=" in text:
154
+ flag, value = text.split("=", 1)
155
+ if (core.SECRET_NAME_RE.search(flag) or core._secret_like_arg(value)) and not _safe_reference(value):
156
+ result.append(f"{flag}={REDACTED}")
157
+ continue
158
+ elif text.startswith("-") and core.SECRET_NAME_RE.search(text):
159
+ previous_secret_flag = True
160
+ if core.SECRET_VALUE_RE.search(text) and not _safe_reference(text):
161
+ secret = True
162
+ elif not text.startswith("-") and not _safe_reference(text) and core.looks_like_token(text):
163
+ secret = True
164
+ result.append(REDACTED if secret else text)
165
+ return result
166
+
167
+
168
+ def _credential_query(key: str, value: str) -> bool:
169
+ return bool(core.SECRET_NAME_RE.search(key) or core.SECRET_VALUE_RE.search(value) or core.looks_like_token(value))
170
+
171
+
172
+ def _url_has_credential(url: str | None) -> bool:
173
+ if not url:
174
+ return False
175
+ try:
176
+ parts = urlsplit(_plain_variables(url))
177
+ return bool(parts.username or parts.password or any(
178
+ not _safe_reference(val) and _credential_query(key, val) for key, val in parse_qsl(parts.query)))
179
+ except ValueError:
180
+ return False
181
+
182
+
183
+ def _redact_url(value: str) -> str:
184
+ text = _plain_variables(value)
185
+ try:
186
+ parts = urlsplit(text)
187
+ host = parts.hostname or ""
188
+ netloc = host + (f":{parts.port}" if parts.port else "")
189
+ query = "&".join(
190
+ f"{key}={val if _safe_reference(val) else REDACTED}" if val else key
191
+ for key, val in parse_qsl(parts.query, keep_blank_values=True))
192
+ return urlunsplit((parts.scheme, netloc, parts.path, query, ""))
193
+ except ValueError:
194
+ return REDACTED
195
+
196
+
197
+ def _host(url: str) -> str | None:
198
+ try:
199
+ return urlsplit(url).hostname
200
+ except ValueError:
201
+ return None
202
+
203
+
204
+ def _digest(*parts: str) -> str:
205
+ return hashlib.sha256("\0".join(parts).encode("utf-8")).hexdigest()
206
+
207
+
208
+ # ------------------------------------------------------------------ file reading (never raises)
209
+
210
+ def _read_bytes(path: Path, limit: int) -> tuple[bytes | None, str | None]:
211
+ try:
212
+ if path.stat().st_size > limit:
213
+ return None, "too-large"
214
+ return path.read_bytes(), None
215
+ except OSError:
216
+ return None, "unreadable"
217
+
218
+
219
+ def read_json_object(path: Path) -> tuple[dict | None, str | None]:
220
+ """(object, None) | (None, None) when absent | (None, reason) when present but unusable."""
221
+ if not path.exists():
222
+ return None, None
223
+ if not path.is_file():
224
+ return None, "unreadable"
225
+ raw, reason = _read_bytes(path, MAX_CONFIG)
226
+ if raw is None:
227
+ return None, reason
228
+ try:
229
+ data = json.loads(raw.decode("utf-8"))
230
+ except (UnicodeDecodeError, ValueError):
231
+ return None, "invalid-json"
232
+ return (data, None) if isinstance(data, dict) else (None, "unexpected-structure")
233
+
234
+
235
+ def read_toml_object(path: Path) -> tuple[dict | None, str | None]:
236
+ if not path.exists():
237
+ return None, None
238
+ if not path.is_file():
239
+ return None, "unreadable"
240
+ raw, reason = _read_bytes(path, MAX_CONFIG)
241
+ if raw is None:
242
+ return None, reason
243
+ try:
244
+ return tomllib.loads(raw.decode("utf-8")), None
245
+ except (UnicodeDecodeError, tomllib.TOMLDecodeError):
246
+ return None, "invalid-toml"
247
+
248
+
249
+ # ------------------------------------------------------------------ skills
250
+
251
+ _KEY_RE = re.compile(r"^([A-Za-z0-9_-]+):[ \t]*(.*)$")
252
+
253
+
254
+ def parse_frontmatter(text: str) -> dict[str, str] | None:
255
+ """Top-level ``key: value`` pairs of a leading ``---`` block (plain, quoted and ``>`` / ``|`` block scalars)."""
256
+ lines = text.lstrip("\ufeff").splitlines()
257
+ if not lines or lines[0].strip() != "---":
258
+ return None
259
+ end = next((index for index in range(1, len(lines)) if lines[index].strip() == "---"), None)
260
+ if end is None:
261
+ return None
262
+ result: dict[str, str] = {}
263
+ index = 1
264
+ while index < end:
265
+ match = _KEY_RE.match(lines[index])
266
+ index += 1
267
+ if not match:
268
+ continue
269
+ key, value = match.group(1), match.group(2).strip()
270
+ block: list[str] = []
271
+ while index < end and (lines[index].startswith((" ", "\t")) or not lines[index].strip()):
272
+ block.append(lines[index].strip())
273
+ index += 1
274
+ if value[:1] in (">", "|"):
275
+ joiner = "\n" if value[:1] == "|" else " "
276
+ value = joiner.join(part for part in block if part)
277
+ elif not value:
278
+ value = " ".join(part for part in block if part)
279
+ elif block:
280
+ value = " ".join([value, *[part for part in block if part]])
281
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
282
+ value = value[1:-1]
283
+ result[key] = value
284
+ return result
285
+
286
+
287
+ def _plugin_manifest(path: Path) -> dict | None:
288
+ data, _reason = read_json_object(path / "plugin.json")
289
+ return data
290
+
291
+
292
+ def known_plugin_versions(home: Path) -> dict[str, tuple[str, ...]]:
293
+ """Versions of each agenthelm plugin found in the client plugin roots of this machine."""
294
+ found: dict[str, list[str]] = {}
295
+ roots: list[Path] = []
296
+ for client in CLIENTS:
297
+ try:
298
+ for parent in core._client_plugin_roots(client, home):
299
+ if parent.is_dir():
300
+ roots.extend(child for child in sorted(parent.iterdir()) if child.is_dir())
301
+ roots.extend(core._client_marketplace_plugins(client, home))
302
+ except (OSError, core.AgentPackError):
303
+ continue
304
+ for root in roots:
305
+ manifest = _plugin_manifest(root)
306
+ if manifest and manifest.get("name") in AGENTHELM_PLUGINS and isinstance(manifest.get("version"), str):
307
+ found.setdefault(manifest["name"], []).append(manifest["version"])
308
+ return {name: tuple(versions) for name, versions in found.items()}
309
+
310
+
311
+ def _state_skill_names(home: Path) -> dict[str, str]:
312
+ """Skill name -> package name, from the Claude sync state records (``~/.claude/agent-pack/state/<package>.json``)."""
313
+ owned: dict[str, str] = {}
314
+ directory = home / ".claude" / "agent-pack" / "state"
315
+ if not directory.is_dir():
316
+ return owned
317
+ for path in sorted(directory.glob("*.json")):
318
+ data, _reason = read_json_object(path)
319
+ if not data or data.get("schema_version") != 1:
320
+ continue
321
+ skills = data.get("skills")
322
+ for name in skills if isinstance(skills, list) else ():
323
+ if isinstance(name, str):
324
+ owned.setdefault(name, path.stem)
325
+ return owned
326
+
327
+
328
+ def _state_mcp_names(home: Path) -> dict[str, str]:
329
+ owned: dict[str, str] = {}
330
+ directory = home / ".claude" / "agent-pack" / "state"
331
+ if not directory.is_dir():
332
+ return owned
333
+ for path in sorted(directory.glob("*.json")):
334
+ data, _reason = read_json_object(path)
335
+ if not data or data.get("schema_version") != 1:
336
+ continue
337
+ mcps = data.get("mcps")
338
+ for name in mcps if isinstance(mcps, dict) else ():
339
+ owned.setdefault(str(name), path.stem)
340
+ return owned
341
+
342
+
343
+ def _origin(kind: str, detail: str | None, otype: str, oid: str | None, version: str | None, latest: str,
344
+ evidence: str = "file") -> dict:
345
+ """``kind`` / ``detail`` are the first-version keys; ``type`` / ``id`` / ``version`` / ``latest_known`` /
346
+ ``evidence`` are the structured form (``latest_known`` is the highest version found on this machine, offline)."""
347
+ return {"kind": kind, "detail": detail, "type": otype, "id": oid, "version": version, "latest_known": latest,
348
+ "evidence": evidence}
349
+
350
+
351
+ def _git_root(real: Path, home: Path) -> Path | None:
352
+ for parent in real.parents:
353
+ if parent == home or parent == parent.parent:
354
+ return None
355
+ if (parent / ".git").exists():
356
+ return parent
357
+ return None
358
+
359
+
360
+ def _skill_origin(entry: Path, client: str, scope: str, name: str, versions: dict[str, tuple[str, ...]],
361
+ state: dict[str, str], home: Path) -> tuple[dict, str | None, Any]:
362
+ """(origin, version, stale): only an entry whose source and version can be read gets a stale verdict."""
363
+ unknown = _origin("unknown", None, "unknown", None, None, "unknown", "unknown")
364
+ try:
365
+ real = entry.resolve()
366
+ except OSError:
367
+ return unknown, None, "unknown"
368
+ manifest = _plugin_manifest(real.parent.parent) if real.parent.name == "skills" else None
369
+ if (manifest and manifest.get("name") in AGENTHELM_PLUGINS and isinstance(manifest.get("version"), str)
370
+ and AGENTHELM_REPOSITORY in str(manifest.get("repository", ""))):
371
+ plugin, version = manifest["name"], manifest["version"]
372
+ newest = max([*versions.get(plugin, ()), version], key=core._version_tuple)
373
+ stale: Any = core._version_tuple(version) < core._version_tuple(newest)
374
+ return _origin("agenthelm-plugin", f"{plugin}@{version}", "plugin", plugin, version, newest), version, stale
375
+ if client == "claude" and scope == "user" and name in state and entry.is_symlink():
376
+ return _origin("state-record", state[name], "unknown", state[name], None, "unknown"), None, "unknown"
377
+ if manifest and isinstance(manifest.get("name"), str) and any(part in real.parts for part in ("cache", "marketplaces")) \
378
+ and "plugins" in real.parts:
379
+ version = manifest.get("version") if isinstance(manifest.get("version"), str) else None
380
+ return _origin("unknown", None, "marketplace", manifest["name"], version, "unknown"), version, "unknown"
381
+ if entry.is_symlink():
382
+ root = _git_root(real, home)
383
+ if root is not None:
384
+ return _origin("unknown", None, "git", root.name, None, "unknown"), None, "unknown"
385
+ return unknown, None, "unknown"
386
+
387
+
388
+ def _link_kind(entry: Path, home: Path) -> str | None:
389
+ if not entry.is_symlink():
390
+ return None
391
+ try:
392
+ raw = os.readlink(entry)
393
+ except OSError:
394
+ return None
395
+ if not os.path.isabs(raw):
396
+ return "relative"
397
+ return "absolute" if raw == str(home) or raw.startswith(str(home) + os.sep) else "outside-home"
398
+
399
+
400
+ def _dir_stats(entry: Path) -> tuple[int | None, int | None]:
401
+ """(total bytes, file count) of the skill directory; symlinks inside are counted, not followed."""
402
+ total = count = 0
403
+ try:
404
+ for current, dirs, files in os.walk(entry, followlinks=False):
405
+ dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(current, d))]
406
+ for file in files:
407
+ count += 1
408
+ if count > MAX_DIR_FILES:
409
+ return None, None
410
+ try:
411
+ total += os.lstat(os.path.join(current, file)).st_size
412
+ except OSError:
413
+ pass
414
+ except OSError:
415
+ return None, None
416
+ return total, count
417
+
418
+
419
+ def observe_skill(entry: Path, client: str, scope: str, store: str, home: Path, project: Path | None,
420
+ versions: dict[str, tuple[str, ...]], state: dict[str, str],
421
+ include_description: bool = False) -> dict | None:
422
+ """One skill directory entry, or ``None`` when it is not a skill (no ``SKILL.md``)."""
423
+ name = entry.name
424
+ link = entry.is_symlink()
425
+ target = None
426
+ if link:
427
+ try:
428
+ target = display_path(os.readlink(entry), home, project)
429
+ except OSError:
430
+ target = None
431
+ record: dict[str, Any] = {
432
+ "name": name, "client": client, "scope": scope, "store": store,
433
+ "path": f"{store}/{name}",
434
+ "frontmatter": None, "description_bytes": 0, "skill_md_bytes": 0, "content_sha256": None,
435
+ "origin": _origin("unknown", None, "unknown", None, None, "unknown", "unknown"),
436
+ "symlink": {"is_symlink": link, "target": target},
437
+ "version": None, "stale": "unknown", "evidence": "file", "issues": [],
438
+ "description_chars": 0, "when_to_use_chars": 0, "when_to_use_bytes": 0, "skill_md_lines": 0,
439
+ "dir_bytes": None, "file_count": None, "is_symlink": link, "link_target_kind": _link_kind(entry, home),
440
+ "name_matches_dir": None, "frontmatter_ok": False,
441
+ "loaded": "unknown", "precedence": "unique", "shadowed_by": None,
442
+ }
443
+ skill_md = entry / "SKILL.md"
444
+ try:
445
+ isdir = entry.is_dir()
446
+ has_md = skill_md.is_file()
447
+ except OSError:
448
+ isdir = has_md = False
449
+ if link and not isdir:
450
+ record["issues"].append("broken-symlink")
451
+ record["evidence"] = "unknown"
452
+ return record
453
+ if not isdir or not has_md:
454
+ return None
455
+ record["origin"], record["version"], record["stale"] = _skill_origin(entry, client, scope, name, versions, state, home)
456
+ record["dir_bytes"], record["file_count"] = _dir_stats(entry.resolve() if link else entry)
457
+ if record["file_count"] is None:
458
+ record["issues"].append("dir-too-large")
459
+ raw, reason = _read_bytes(skill_md, MAX_SKILL_MD)
460
+ if raw is None:
461
+ record["issues"].append("skill-md-too-large" if reason == "too-large" else "frontmatter-missing")
462
+ record["evidence"] = "unknown"
463
+ try:
464
+ record["skill_md_bytes"] = skill_md.stat().st_size
465
+ except OSError:
466
+ pass
467
+ return record
468
+ record["skill_md_bytes"] = len(raw)
469
+ record["content_sha256"] = hashlib.sha256(raw).hexdigest()
470
+ text = raw.decode("utf-8", errors="replace")
471
+ record["skill_md_lines"] = len(text.splitlines())
472
+ meta = parse_frontmatter(text)
473
+ if meta is None:
474
+ record["issues"].append("frontmatter-missing")
475
+ return record
476
+ record["frontmatter"] = {"name": meta.get("name")}
477
+ description = meta.get("description")
478
+ if description is None:
479
+ record["issues"].append("description-missing")
480
+ else:
481
+ record["description_bytes"] = len(description.encode("utf-8"))
482
+ record["description_chars"] = len(description)
483
+ record["_description"] = description # for the overlap hints; removed before output
484
+ if include_description:
485
+ record["frontmatter"]["description"] = description[:DESCRIPTION_LIMIT]
486
+ when = meta.get("when_to_use")
487
+ if when is not None:
488
+ record["when_to_use_chars"], record["when_to_use_bytes"] = len(when), len(when.encode("utf-8"))
489
+ record["name_matches_dir"] = meta.get("name") == name if meta.get("name") is not None else None
490
+ if meta.get("name") is not None and meta["name"] != name:
491
+ record["issues"].append("name-mismatch")
492
+ record["frontmatter_ok"] = bool(meta.get("name") and description)
493
+ return record
494
+
495
+
496
+ def _scan_skill_store(client: str, scope: str, store: str, root: Path, home: Path, project: Path | None,
497
+ versions: dict[str, tuple[str, ...]], state: dict[str, str],
498
+ include_description: bool = False) -> list[dict]:
499
+ try:
500
+ if not root.is_dir():
501
+ return []
502
+ children = sorted(root.iterdir(), key=lambda item: item.name)
503
+ except OSError:
504
+ return []
505
+ found = []
506
+ for child in children:
507
+ if child.name.startswith("."):
508
+ continue
509
+ record = observe_skill(child, client, scope, store, home, project, versions, state, include_description)
510
+ if record is not None:
511
+ found.append(record)
512
+ return found
513
+
514
+
515
+ # ------------------------------------------------------------------ MCP
516
+
517
+ def _names(mapping: Any) -> list[str]:
518
+ return sorted(str(key) for key in mapping) if isinstance(mapping, dict) else []
519
+
520
+
521
+ def normalize_mcp(name: str, raw: Any, client: str, scope: str, store: str, home: Path,
522
+ state: dict[str, str]) -> dict:
523
+ """A server entry reduced to what may be shown: no ``env`` / ``headers`` values, no tokens."""
524
+ item = raw if isinstance(raw, dict) else {}
525
+ command = item.get("command") if isinstance(item.get("command"), str) else None
526
+ url = item.get("url") if isinstance(item.get("url"), str) else None
527
+ declared = str(item.get("type") or item.get("transport") or "").lower()
528
+ if declared in ("stdio", "sse", "http"):
529
+ transport = declared
530
+ elif declared in ("streamable-http", "streamable_http"):
531
+ transport = "http"
532
+ elif command:
533
+ transport = "stdio"
534
+ elif url:
535
+ transport = "http"
536
+ else:
537
+ transport = "unknown"
538
+ args = _redact_args(item["args"]) if isinstance(item.get("args"), list) else []
539
+ env_names = set(_names(item.get("env")))
540
+ env_vars = item.get("env_vars")
541
+ if isinstance(env_vars, list):
542
+ env_names.update(str(value) for value in env_vars if isinstance(value, str))
543
+ header_names = set(_names(item.get("headers"))) | set(_names(item.get("http_headers"))) \
544
+ | set(_names(item.get("env_http_headers")))
545
+ if item.get("bearer_token_env_var"):
546
+ header_names.add("Authorization")
547
+ shown_command = _plain_variables(display_path(command, home, None)) if command else None
548
+ shown_url = _redact_url(url) if url else None
549
+ if transport == "stdio" and shown_command:
550
+ fingerprint = _digest("stdio", shown_command, *args)
551
+ elif shown_url:
552
+ fingerprint = _digest("url", shown_url)
553
+ else:
554
+ fingerprint = None
555
+ refs = set(ENV_REF.findall(" ".join(filter(None, [command or "", url or "", *map(str, item["args"] if isinstance(item.get("args"), list) else [])]))))
556
+ for container in ("env", "headers", "http_headers"):
557
+ if isinstance(item.get(container), dict):
558
+ for value in item[container].values():
559
+ refs.update(ENV_REF.findall(str(value)))
560
+ secret = any(part == REDACTED or part.endswith("=" + REDACTED) for part in args) or _url_has_credential(url)
561
+ for container in ("env", "headers", "http_headers"):
562
+ if isinstance(item.get(container), dict):
563
+ for key, value in item[container].items():
564
+ text = str(value)
565
+ if not _safe_reference(text) and not ENV_REF.fullmatch(text) and (
566
+ core.SECRET_NAME_RE.search(str(key)) or core.SECRET_VALUE_RE.search(text) or core.looks_like_token(text)):
567
+ secret = True
568
+ record: dict[str, Any] = {
569
+ "name": name, "client": client, "scope": scope, "store": store, "transport": transport,
570
+ "command": shown_command, "args": args,
571
+ "url": shown_url, "env_names": sorted(env_names), "header_names": sorted(header_names),
572
+ "fingerprint": fingerprint,
573
+ "origin": {"kind": "unknown", "detail": None},
574
+ "evidence": "file", "notes": [],
575
+ "env_var_names": sorted(env_names | refs), "has_inline_secret": secret,
576
+ "fingerprint_fields": ["command", "args"] if fingerprint and transport == "stdio" else (["url"] if fingerprint else []),
577
+ "url_host": _host(shown_url) if shown_url and transport != "stdio" else None,
578
+ "loaded": "unknown", "precedence": "unique", "shadowed_by": None,
579
+ }
580
+ if client == "claude" and scope == "user" and name in state:
581
+ record["origin"] = {"kind": "state-record", "detail": state[name]}
582
+ if client == "codex" and scope == "project":
583
+ record["notes"].append("codex-project-requires-trust")
584
+ if not command and not url:
585
+ record["evidence"] = "unknown"
586
+ return record
587
+
588
+
589
+ def _servers(data: dict | None, key: str = "mcpServers") -> dict | None:
590
+ value = (data or {}).get(key)
591
+ return value if isinstance(value, dict) else None
592
+
593
+
594
+ def _claude_local_servers(data: dict, project: Path) -> tuple[dict | None, str | None]:
595
+ """Entries kept under the project's own path in ``~/.claude.json`` (``projects[<absolute path>].mcpServers``).
596
+
597
+ The documentation says only "under that project's path", so anything else than that shape is ``unknown``.
598
+ """
599
+ projects = data.get("projects")
600
+ if projects is None:
601
+ return {}, None
602
+ if not isinstance(projects, dict):
603
+ return None, "claude-local-structure-unrecognized"
604
+ for key in dict.fromkeys((str(project), str(project.resolve()))):
605
+ if key in projects:
606
+ section = projects[key]
607
+ if not isinstance(section, dict):
608
+ return None, "claude-local-structure-unrecognized"
609
+ servers = section.get("mcpServers", {})
610
+ if servers is None:
611
+ return {}, None
612
+ return (servers, None) if isinstance(servers, dict) else (None, "claude-local-structure-unrecognized")
613
+ return {}, None
614
+
615
+
616
+ def _observe_mcp_store(client: str, scope: str, store: str, home: Path, project: Path | None,
617
+ state: dict[str, str], unknown: list[dict]) -> list[dict]:
618
+ path = resolve_store(store, home, project)
619
+ if path is None:
620
+ return []
621
+ if client == "codex":
622
+ data, reason = read_toml_object(path)
623
+ servers = _servers(data, "mcp_servers")
624
+ else:
625
+ data, reason = read_json_object(path)
626
+ if scope == "local":
627
+ if data is None:
628
+ servers = None
629
+ else:
630
+ servers, local_reason = _claude_local_servers(data, project) if project else ({}, None)
631
+ reason = local_reason or reason
632
+ else:
633
+ servers = _servers(data)
634
+ if reason:
635
+ unknown.append({"store": store, "client": client, "reason": reason})
636
+ return []
637
+ if servers is None:
638
+ if data is not None and scope != "local" and (data.get("mcpServers" if client != "codex" else "mcp_servers") is not None):
639
+ unknown.append({"store": store, "client": client, "reason": "unexpected-structure"})
640
+ return []
641
+ return [normalize_mcp(str(name), raw, client, scope, store, home, state) for name, raw in sorted(servers.items())]
642
+
643
+
644
+ # ------------------------------------------------------------------ Claude Desktop (claude_desktop_config.json)
645
+
646
+ def desktop_store(platform: str | None = None) -> str | None:
647
+ """The documented ``claude_desktop_config.json`` location for this platform (``None`` where it is not resolved)."""
648
+ name = sys.platform if platform is None else platform
649
+ return DESKTOP_STORES.get("darwin" if name == "darwin" else "linux" if name.startswith("linux") else "")
650
+
651
+
652
+ def desktop_info(home: Path, platform: str | None = None) -> dict:
653
+ """``{path, exists, parse_ok}`` of ``claude_desktop_config.json`` (``parse_ok`` is ``null`` when absent)."""
654
+ store = desktop_store(platform)
655
+ path = resolve_store(store, home, None) if store else None
656
+ if path is None:
657
+ return {"path": None, "exists": False, "parse_ok": None}
658
+ exists = path.exists()
659
+ data, reason = read_json_object(path) if exists else (None, None)
660
+ return {"path": display_path(path, home, None), "exists": exists,
661
+ "parse_ok": (reason is None and data is not None) if exists else None}
662
+
663
+
664
+ def observe_desktop(home: Path, platform: str | None = None) -> tuple[list[dict], list[dict]]:
665
+ """(entries, unknown) of ``claude_desktop_config.json``; a missing or corrupt file is ``unknown``, never an error."""
666
+ store = desktop_store(platform)
667
+ label = DESKTOP_STORE_NAME
668
+ if store is None:
669
+ return [], [{"store": label, "client": DESKTOP, "reason": "platform-unsupported"}]
670
+ path = resolve_store(store, home, None)
671
+ data, reason = read_json_object(path) if path is not None else (None, "unreadable")
672
+ if reason is None and data is None:
673
+ reason = "not-found"
674
+ if reason:
675
+ return [], [{"store": label, "client": DESKTOP, "reason": reason}]
676
+ servers = _servers(data)
677
+ if servers is None:
678
+ return [], ([{"store": label, "client": DESKTOP, "reason": "unexpected-structure"}] if "mcpServers" in data else [])
679
+ entries = [normalize_mcp(str(name), raw, DESKTOP, "user", label, home, {}) for name, raw in sorted(servers.items())]
680
+ for entry in entries:
681
+ if any("${" in str(value) for value in (entry["command"], entry["url"], *entry["args"])):
682
+ entry["notes"].append("variable-expansion-unconfirmed")
683
+ return entries, []
684
+
685
+
686
+ def desktop_report(home: Path, platform: str | None = None) -> dict:
687
+ """What ``doctor --client claude-desktop`` shows: read-only, nothing here is a drift issue."""
688
+ entries, unknown = observe_desktop(home.expanduser().resolve(), platform)
689
+ report = {"client": DESKTOP, "store": DESKTOP_STORE_NAME, "path": desktop_info(home.expanduser().resolve(), platform)["path"],
690
+ "evidence": "unknown" if unknown else "file",
691
+ "servers": [entry["name"] for entry in entries], "unknown": unknown, "source_url": DOC_DESKTOP_PATHS}
692
+ report["warnings"] = [_("{0}:{1}({2})").format(DESKTOP, item["store"], _(REASON_TEXT.get(item["reason"], item["reason"])))
693
+ for item in unknown if item["reason"] != "not-found"]
694
+ return report
695
+
696
+
697
+ def desktop_shadow_findings(home: Path, names: list[str], platform: str | None = None) -> list[dict]:
698
+ """Advisory: servers the project manages (``names``) that ``claude_desktop_config.json`` also defines.
699
+
700
+ The Desktop app loads that file's servers into local Code tab sessions alongside ``~/.claude.json`` and ``.mcp.json``
701
+ (https://code.claude.com/docs/en/desktop, read 2026-11-18). An earlier reading (design #82, 2026-11-11) quoted a
702
+ sentence that the Code tab then uses the ``claude_desktop_config.json`` definition; the page read on 2026-11-18 no
703
+ longer contains it, so the precedence is reported as unconfirmed. Applies to the Desktop local Code tab only; the
704
+ standalone CLI is unaffected.
705
+ """
706
+ entries, _unknown = observe_desktop(home.expanduser().resolve(), platform)
707
+ wanted = set(names)
708
+ return [{"name": entry["name"], "by": DESKTOP_FILE, "store": entry["store"], "applies_to": "desktop-local-code-tab",
709
+ "cli_affected": False, "severity": "advisory", "evidence": "file", "precedence_confirmed": False,
710
+ "source_url": DOC_DESKTOP_MCP} for entry in entries if entry["name"] in wanted]
711
+
712
+
713
+ def shadow_warning(item: dict) -> str:
714
+ return _("claude:{0} 在 claude_desktop_config.json 里也有定义;Claude Desktop 的本地 Code 标签可能改用那一份(官方文档当前没有明确同名优先级),独立 CLI 不受影响").format(item["name"])
715
+
716
+
717
+ # ------------------------------------------------------------------ duplicates
718
+
719
+ def _tokens(text: str) -> set[str]:
720
+ words = re.findall(r"[a-z0-9]+", text.lower())
721
+ cjk = re.findall("[\\u4e00-\\u9fff]", text)
722
+ bigrams = [a + b for a, b in zip(cjk, cjk[1:])]
723
+ return set(words) | set(bigrams)
724
+
725
+
726
+ def overlap_hints(skills: list[dict]) -> list[dict]:
727
+ """Different names with strongly overlapping descriptions (token Jaccard). A mechanical hint, not a judgement."""
728
+ hints = []
729
+ by_client: dict[str, list[dict]] = {}
730
+ for item in skills:
731
+ description = item.get("_description")
732
+ if description:
733
+ by_client.setdefault(item["client"], []).append({**item, "_t": _tokens(description)})
734
+ for client, items in sorted(by_client.items()):
735
+ for index, left in enumerate(items):
736
+ for right in items[index + 1:]:
737
+ if left["name"] == right["name"] or min(len(left["_t"]), len(right["_t"])) < OVERLAP_MIN_TOKENS:
738
+ continue
739
+ union = left["_t"] | right["_t"]
740
+ similarity = len(left["_t"] & right["_t"]) / len(union) if union else 0.0
741
+ if similarity >= OVERLAP_THRESHOLD:
742
+ hints.append({"client": client, "names": sorted([left["name"], right["name"]]),
743
+ "paths": sorted([left["path"], right["path"]]),
744
+ "similarity": round(similarity, 2), "basis": "description-token-jaccard",
745
+ "hint_only": True})
746
+ return sorted(hints, key=lambda hint: (hint["client"], hint["names"], hint["paths"]))
747
+
748
+
749
+ def _real(entry_path: Path | None) -> str | None:
750
+ try:
751
+ return str(entry_path.resolve()) if entry_path is not None else None
752
+ except OSError:
753
+ return None
754
+
755
+
756
+ def _skill_effective(client: str, group: list[dict]) -> dict:
757
+ scopes = {item["scope"] for item in group}
758
+ if client == "claude" and scopes == {"user", "project"}:
759
+ # Claude Code: enterprise > personal > project (enterprise level is not read here).
760
+ return {"store": next(item["store"] for item in group if item["scope"] == "user"), "rule": "personal-over-project",
761
+ "evidence": "file", "source_url": DOC_CLAUDE_SKILLS}
762
+ if client == "codex":
763
+ return {"store": None, "rule": "both-load", "evidence": "file", "source_url": DOC_CODEX_SKILLS}
764
+ return {"store": None, "rule": "precedence-undocumented" if client == "cursor" else "unknown",
765
+ "evidence": "unknown", "source_url": None}
766
+
767
+
768
+ def skill_duplicates(skills: list[dict], real_paths: dict[str, str]) -> list[dict]:
769
+ result = []
770
+ by_key: dict[tuple[str, str], list[dict]] = {}
771
+ for item in skills:
772
+ by_key.setdefault((item["client"], item["name"]), []).append(item)
773
+ for (client, name), group in sorted(by_key.items()):
774
+ stores = sorted({item["path"] for item in group})
775
+ if len(stores) < 2:
776
+ continue
777
+ reals = {real_paths.get(item["path"]) for item in group}
778
+ hashes = {item["content_sha256"] for item in group}
779
+ if None in hashes:
780
+ relation = "unknown"
781
+ elif len(reals) == 1 and None not in reals:
782
+ relation = "same-file"
783
+ elif len(hashes) == 1:
784
+ relation = "identical"
785
+ else:
786
+ relation = "different"
787
+ result.append({"client": client, "name": name, "stores": stores, "relation": relation,
788
+ "effective": _skill_effective(client, group) if relation != "same-file" else None})
789
+ return result
790
+
791
+
792
+ def _mcp_effective(client: str, group: list[dict]) -> dict:
793
+ stores = {item["scope"]: item["store"] for item in group}
794
+ if client == "claude":
795
+ # Claude Code: local > project > user (entry used whole, no field merge). A project-file winner depends on
796
+ # the per-project approval (a setting this version does not read), so only a local winner is concluded.
797
+ if "local" in stores:
798
+ return {"store": stores["local"], "rule": "local-over-project-over-user", "evidence": "file",
799
+ "source_url": DOC_CLAUDE_MCP}
800
+ return {"store": None, "rule": "project-approval-unknown", "evidence": "unknown", "source_url": DOC_CLAUDE_MCP}
801
+ if client == "codex":
802
+ return {"store": None, "rule": "project-trust-unknown", "evidence": "unknown", "source_url": DOC_CODEX_MCP}
803
+ return {"store": None, "rule": "precedence-undocumented", "evidence": "unknown", "source_url": None}
804
+
805
+
806
+ def mcp_duplicates(mcps: list[dict]) -> list[dict]:
807
+ result = []
808
+ by_name: dict[tuple[str, str], list[dict]] = {}
809
+ by_print: dict[tuple[str, str], list[dict]] = {}
810
+ for item in mcps:
811
+ by_name.setdefault((item["client"], item["name"]), []).append(item)
812
+ if item["fingerprint"]:
813
+ by_print.setdefault((item["client"], item["fingerprint"]), []).append(item)
814
+ for (client, name), group in sorted(by_name.items()):
815
+ stores = sorted({item["store"] for item in group})
816
+ if len(stores) < 2:
817
+ continue
818
+ prints = {item["fingerprint"] for item in group}
819
+ relation = "unknown" if None in prints else ("identical" if len(prints) == 1 else "different")
820
+ result.append({"kind": "same-name", "client": client, "names": [name], "stores": stores,
821
+ "relation": relation, "effective": _mcp_effective(client, group)})
822
+ for (client, fingerprint), group in sorted(by_print.items()):
823
+ names = sorted({item["name"] for item in group})
824
+ if len(names) < 2:
825
+ continue
826
+ result.append({"kind": "same-fingerprint", "client": client, "names": names,
827
+ "stores": sorted({item["store"] for item in group}), "relation": "identical",
828
+ "fingerprint": fingerprint, "effective": None})
829
+ return result
830
+
831
+
832
+ def entry_ref(item: dict, kind: str) -> str:
833
+ """``<kind>:<name>@<client>:<scope>``; a skill outside the client's primary store for that scope gets ``#agents``."""
834
+ ref = f"{kind}:{item['name']}@{item['client']}:{item['scope']}"
835
+ if kind == "skill" and item["store"] != PRIMARY_SKILL_STORE.get((item["client"], item["scope"]), item["store"]):
836
+ ref += "#agents"
837
+ return ref
838
+
839
+
840
+ def _annotate(skills: list[dict], mcps: list[dict], duplicates: dict) -> None:
841
+ """Stable ``ref`` for every entry, and ``precedence`` / ``shadowed_by`` from the duplicate groups' ``effective``."""
842
+ for kind, items, groups in (("skill", skills, duplicates["skills"]), ("mcp", mcps, duplicates["mcps"])):
843
+ for item in items:
844
+ item["ref"] = entry_ref(item, kind)
845
+ for group in groups:
846
+ if group.get("kind", "same-name") != "same-name" or group["relation"] == "same-file":
847
+ continue
848
+ effective = group.get("effective") or {}
849
+ for item in items:
850
+ if item["client"] != group["client"] or item["name"] not in (group.get("names") or [group.get("name")]):
851
+ continue
852
+ if (item["path"] if kind == "skill" else item["store"]) not in group["stores"]:
853
+ continue
854
+ if effective.get("rule") == "both-load":
855
+ item["precedence"] = "both-load"
856
+ elif effective.get("store"):
857
+ won = item["store"] == effective["store"]
858
+ item["precedence"] = "winner" if won else "shadowed"
859
+ if not won:
860
+ item["shadowed_by"] = {"store": effective["store"], "rule": effective["rule"],
861
+ "evidence": effective["evidence"], "source_url": effective["source_url"]}
862
+ else:
863
+ item["precedence"] = "unknown"
864
+
865
+
866
+ # ------------------------------------------------------------------ entry point
867
+
868
+ def observe(home: Path, project: Path | None = None, clients: list[str] | None = None, types: str = "all",
869
+ scope: str = "all", platform: str | None = None, include_description: bool = False) -> dict:
870
+ """Everything the chosen clients can see, as the ``schema_version`` 1 document. Read-only and never raises on
871
+ bad input files (they become ``unknown`` entries)."""
872
+ home = home.expanduser().resolve()
873
+ project = project.expanduser().resolve() if project is not None else None
874
+ requested = list(ALL_CLIENTS) if clients and "all" in clients else (clients or list(CLIENTS))
875
+ chosen = [client for client in ALL_CLIENTS if client in requested]
876
+ want_skills, want_mcp = types in ("skills", "all"), types in ("mcp", "all")
877
+
878
+ def wanted(item_scope: str) -> bool:
879
+ return scope == "all" or item_scope == scope or (scope == "project" and item_scope == "local")
880
+
881
+ versions = known_plugin_versions(home) if want_skills else {}
882
+ skill_state = _state_skill_names(home) if want_skills else {}
883
+ mcp_state = _state_mcp_names(home) if want_mcp else {}
884
+ skills: list[dict] = []
885
+ mcps: list[dict] = []
886
+ unknown: list[dict] = []
887
+ real_paths: dict[str, str] = {}
888
+ for client in chosen:
889
+ if client == DESKTOP:
890
+ if want_mcp and wanted("user"): # Desktop has no Skill directory and no project level
891
+ found, missing = observe_desktop(home, platform)
892
+ mcps.extend(found)
893
+ unknown.extend(missing)
894
+ continue
895
+ if want_skills:
896
+ for item_scope, store in SKILL_STORES[client]:
897
+ root = resolve_store(store, home, project)
898
+ if root is None or not wanted(item_scope):
899
+ continue
900
+ for record in _scan_skill_store(client, item_scope, store, root, home, project, versions, skill_state,
901
+ include_description):
902
+ skills.append(record)
903
+ real = _real(root / record["name"])
904
+ if real:
905
+ real_paths[record["path"]] = real
906
+ if want_mcp:
907
+ for item_scope, store in MCP_STORES[client]:
908
+ if wanted(item_scope):
909
+ mcps.extend(_observe_mcp_store(client, item_scope, store, home, project, mcp_state, unknown))
910
+ order = {client: index for index, client in enumerate(ALL_CLIENTS)}
911
+ skills.sort(key=lambda item: (order[item["client"]], SCOPE_ORDER[item["scope"]], item["store"], item["name"]))
912
+ mcps.sort(key=lambda item: (order[item["client"]], SCOPE_ORDER[item["scope"]], item["store"], item["name"]))
913
+ duplicates = {"skills": skill_duplicates(skills, real_paths), "mcps": mcp_duplicates(mcps)}
914
+ hints = overlap_hints(skills)
915
+ _annotate(skills, mcps, duplicates)
916
+ for item in skills:
917
+ item.pop("_description", None)
918
+ summary: dict[str, dict] = {}
919
+ for client in chosen:
920
+ mine = [item for item in skills if item["client"] == client]
921
+ distinct: dict[str, int] = {}
922
+ for item in mine:
923
+ distinct.setdefault(real_paths.get(item["path"], item["path"]), item["description_bytes"])
924
+ summary[client] = {
925
+ "skill_count": len(mine),
926
+ "description_bytes_total": sum(item["description_bytes"] for item in mine),
927
+ "description_bytes_distinct_files": sum(distinct.values()),
928
+ "mcp_count": sum(1 for item in mcps if item["client"] == client),
929
+ }
930
+ report = {
931
+ "schema_version": SCHEMA_VERSION,
932
+ "generated_by": "agenthelm inventory",
933
+ "project": display_path(project, home, None) if project else None,
934
+ "clients": chosen,
935
+ "filters": {"type": types, "scope": scope},
936
+ "skills": skills,
937
+ "mcps": mcps,
938
+ "summary": {"per_client": summary},
939
+ "duplicates": duplicates,
940
+ "overlap_hints": hints,
941
+ "unknown": unknown,
942
+ }
943
+ if DESKTOP in chosen:
944
+ report["desktop"] = desktop_info(home, platform)
945
+ return report
946
+
947
+
948
+ # ------------------------------------------------------------------ text rendering
949
+
950
+ RULE_TEXT = {
951
+ "personal-over-project": N_("用户级优先于项目级(官方文档)"),
952
+ "both-load": N_("两份都会出现在选择器里(官方文档)"),
953
+ "precedence-undocumented": N_("官方文档没有说明优先级"),
954
+ "local-over-project-over-user": N_("local 优先于 project 优先于 user(官方文档)"),
955
+ "project-approval-unknown": N_("项目级条目是否已批准未读取,无法判定哪份生效"),
956
+ "project-trust-unknown": N_("项目是否受信任未读取,无法判定哪份生效"),
957
+ "unknown": N_("无法判定"),
958
+ }
959
+ RELATION_TEXT = {"same-file": N_("同一个文件"), "identical": N_("内容相同"), "different": N_("内容不同"),
960
+ "unknown": N_("无法比较")}
961
+
962
+
963
+ def render_text(report: dict) -> str:
964
+ lines: list[str] = []
965
+ if report["project"]:
966
+ lines.append(_("项目:{0}").format(report["project"]))
967
+ for client, numbers in report["summary"]["per_client"].items():
968
+ lines.append(_("[{0}] Skill {1} 个,每次会话开始加载的 description 共 {2} 字节;MCP {3} 个").format(
969
+ client, numbers["skill_count"], numbers["description_bytes_total"], numbers["mcp_count"]))
970
+ for item in report["skills"]:
971
+ note = f" [{', '.join(_(REASON_TEXT.get(code, code)) for code in item['issues'])}]" if item["issues"] else ""
972
+ lines.append(f" skill {item['client']} {item['name']} {item['path']} {item['description_bytes']}B{note}")
973
+ for item in report["mcps"]:
974
+ target = item["url"] or " ".join(filter(None, [item["command"], *item["args"]]))
975
+ lines.append(f" mcp {item['client']} {item['name']} {item['store']} {item['transport']} {target}")
976
+ for group in report["duplicates"]["skills"] + report["duplicates"]["mcps"]:
977
+ label = ", ".join(group.get("names") or [group["name"]])
978
+ verdict = (group.get("effective") or {}).get("rule")
979
+ lines.append(_("重复 [{0}] {1}({2}):{3}").format(
980
+ group["client"], label, _(RELATION_TEXT[group["relation"]]), ", ".join(group["stores"]))
981
+ + (f" — {_(RULE_TEXT.get(verdict, verdict))}" if verdict else ""))
982
+ for hint in report["overlap_hints"]:
983
+ lines.append(_("相似提示(仅机械比对,不是语义判断)[{0}] {1}:{2}").format(
984
+ hint["client"], " / ".join(hint["names"]), hint["similarity"]))
985
+ for item in report["unknown"]:
986
+ lines.append(_("无法判定:{0}({1})").format(item["store"], _(REASON_TEXT.get(item["reason"], item["reason"]))))
987
+ if not (report["skills"] or report["mcps"] or report["unknown"]):
988
+ lines.append(_("没有发现任何 Skill 或 MCP 配置。"))
989
+ return "\n".join(lines) + "\n"