@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.
- package/package.json +1 -1
- package/runtime/index.json +6 -6
- package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agent-pack/plugin.json +1 -1
- package/runtime/plugins/agent-pack/references/capability-config.md +10 -0
- package/runtime/plugins/agent-pack/references/check-opinion-migrate.en.md +31 -0
- package/runtime/plugins/agent-pack/references/check-opinion-migrate.md +31 -0
- package/runtime/plugins/agent-pack/references/dedupe-contract.en.md +27 -0
- package/runtime/plugins/agent-pack/references/dedupe-contract.md +27 -0
- package/runtime/plugins/agent-pack/references/inventory-contract.en.md +83 -0
- package/runtime/plugins/agent-pack/references/inventory-contract.md +83 -0
- package/runtime/plugins/agent-pack/references/nudge.en.md +10 -2
- package/runtime/plugins/agent-pack/references/nudge.md +10 -2
- package/runtime/plugins/agent-pack/references/relocate-contract.en.md +41 -0
- package/runtime/plugins/agent-pack/references/relocate-contract.md +41 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +572 -30
- package/runtime/plugins/agent-pack/runtime/agent_pack_clients.py +233 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +112 -4
- package/runtime/plugins/agent-pack/runtime/agent_pack_dedupe.py +502 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_desktop.py +92 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_ext_common.py +251 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_inventory.py +989 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_mcp_write.py +447 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +29 -4
- package/runtime/plugins/agent-pack/runtime/agent_pack_relocate.py +385 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_scope.py +233 -0
- package/runtime/plugins/agent-pack/runtime/agenthelm.py +183 -14
- package/runtime/plugins/agent-pack/runtime/locale/en.json +250 -1
- package/runtime/plugins/agent-pack/runtime/mcp_server.py +12 -0
- package/runtime/plugins/agent-pack/runtime/nudge_text.py +8 -2
- package/runtime/plugins/agent-pack/runtime/user_settings.py +2 -1
- package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +15 -0
- package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agents-init/content.json +4 -2
- package/runtime/plugins/agents-init/plugin.json +1 -1
- package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +2 -0
- package/runtime/plugins/agents-init/skills/agents-init/launcher.en.sh +93 -0
- package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +27 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +4 -1
- package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +24 -9
- package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
- package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/catalog/README.md +3 -1
- package/runtime/plugins/opinion-manager/catalog/rules/om.align-requirements/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.assumptions-authority/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.batch-questions/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.bilingual-terms/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.calculations/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.chinese-response/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.clean-deliverable/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.complete-options/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.conclusion-first/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.concrete-titles/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.consistent-items/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.device-readable/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.editable-diagrams/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.evidence-inference/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-chinese/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-project-language/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.markdown-structure/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.portable-files/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.report-context/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.report-formats/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.report-review/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.response-brief/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.response-dense/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.rules-tools/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.semantic-wrap/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-proportional/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-three-level/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.tables-compact/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.tables-list-first/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.test-evidence/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.versioned-files/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/compact-tables/versions/1.1.0.json +32 -0
- package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/list-first/versions/1.1.0.json +32 -0
- package/runtime/plugins/opinion-manager/catalog/templates/development-standard/chinese-maintenance/versions/1.1.0.json +26 -0
- package/runtime/plugins/opinion-manager/catalog/templates/development-standard/project-language/versions/1.1.0.json +26 -0
- package/runtime/plugins/opinion-manager/catalog/templates/response-style/brief-chinese/versions/1.1.0.json +30 -0
- package/runtime/plugins/opinion-manager/catalog/templates/response-style/dense-chinese/versions/1.1.0.json +30 -0
- package/runtime/plugins/opinion-manager/catalog/templates/scenario/concise-project/versions/1.1.0.json +181 -0
- package/runtime/plugins/opinion-manager/catalog/templates/scenario/reviewed-project/versions/1.1.0.json +179 -0
- package/runtime/plugins/opinion-manager/catalog/templates/work-method/proportional/versions/1.1.0.json +31 -0
- package/runtime/plugins/opinion-manager/catalog/templates/work-method/three-level/versions/1.1.0.json +31 -0
- package/runtime/plugins/opinion-manager/content.json +44 -3
- package/runtime/plugins/opinion-manager/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/references/inbox.en.md +25 -4
- package/runtime/plugins/opinion-manager/references/inbox.md +25 -4
- package/runtime/plugins/opinion-manager/references/profile.schema.json +19 -2
- package/runtime/plugins/opinion-manager/references/rule.schema.json +25 -3
- package/runtime/plugins/opinion-manager/references/versioned-template.schema.json +5 -4
- package/runtime/plugins/opinion-manager/references/versioning.md +89 -4
- package/runtime/plugins/opinion-manager/runtime/context.py +26 -19
- package/runtime/plugins/opinion-manager/runtime/inbox.py +400 -25
- package/runtime/plugins/opinion-manager/runtime/inbox_relations.py +106 -0
- package/runtime/plugins/opinion-manager/runtime/inbox_routes.py +132 -0
- package/runtime/plugins/opinion-manager/runtime/inbox_text.py +117 -11
- package/runtime/plugins/opinion-manager/runtime/lifecycle.py +35 -5
- package/runtime/plugins/opinion-manager/runtime/locale/en.json +137 -2
- package/runtime/plugins/opinion-manager/runtime/migrate.py +582 -0
- package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +9 -4
- package/runtime/plugins/opinion-manager/runtime/rule_lines.py +247 -0
- package/runtime/plugins/opinion-manager/runtime/tags.py +217 -0
- package/runtime/plugins/opinion-manager/runtime/versioned.py +289 -41
- package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +8 -7
- package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/runtime/locale/en.json +305 -3
- package/runtime/plugins/project-orchestrator/runtime/private_paths.py +11 -1
- package/runtime/plugins/project-orchestrator/runtime/project_cli.py +101 -1
- package/runtime/plugins/project-orchestrator/runtime/project_demo.py +13 -1
- package/runtime/plugins/project-orchestrator/runtime/project_ext_actions.py +415 -0
- package/runtime/plugins/project-orchestrator/runtime/project_extensions.py +971 -0
- package/runtime/plugins/project-orchestrator/runtime/project_extensions_demo.py +86 -0
- package/runtime/plugins/project-orchestrator/runtime/project_menu.py +345 -2
- package/runtime/plugins/project-orchestrator/runtime/project_real.py +17 -1
- package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +2 -0
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""``agenthelm relocate``: move or copy one Skill to another client / scope (preview by default, ``--apply`` writes).
|
|
3
|
+
|
|
4
|
+
Flow: plan (pure, reads only) -> ``plan_digest`` -> apply (recomputes the plan and refuses on any difference).
|
|
5
|
+
Write order: recovery directory -> copy beside the target under a temporary name -> read back (relative paths and
|
|
6
|
+
content digests, ``SKILL.md`` included) -> rename into place -> archive the source (a move, never a delete).
|
|
7
|
+
Any failure undoes only what this run created and puts archived sources back; an existing target is never touched.
|
|
8
|
+
|
|
9
|
+
Skills are handled here; ``mcp:`` refs go to ``agent_pack_mcp_write`` (same plan shell, digest and apply protocol).
|
|
10
|
+
Plans and outputs never contain file contents or values, only names, paths and digests.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
RUNTIME_DIR = Path(__file__).resolve().parent
|
|
22
|
+
if str(RUNTIME_DIR) not in sys.path:
|
|
23
|
+
sys.path.insert(0, str(RUNTIME_DIR))
|
|
24
|
+
import agent_pack_ext_common as ext # noqa: E402
|
|
25
|
+
import agent_pack_inventory as inv # noqa: E402
|
|
26
|
+
from i18n_agent_pack import _, N_ # noqa: E402
|
|
27
|
+
|
|
28
|
+
# The one data table of target stores (no per-client branches elsewhere in this module): where a Skill for
|
|
29
|
+
# ``client:scope`` is written. ``codex:user`` / ``cursor:project`` use the shared ``.agents/skills``
|
|
30
|
+
# (decision D-CB11); a Skill already sitting in a store that client reads natively is a zero-write ``native`` plan.
|
|
31
|
+
TARGET_STORE = {
|
|
32
|
+
("claude", "user"): "~/.claude/skills", ("claude", "project"): f"{inv.PROJECT}/.claude/skills",
|
|
33
|
+
("codex", "user"): "~/.agents/skills", ("codex", "project"): f"{inv.PROJECT}/.agents/skills",
|
|
34
|
+
("cursor", "user"): "~/.cursor/skills", ("cursor", "project"): f"{inv.PROJECT}/.agents/skills",
|
|
35
|
+
}
|
|
36
|
+
WIDEN_WARNING = N_("放宽:这个 Skill 之后在所有项目里可见")
|
|
37
|
+
RANK = {"project": 0, "user": 1} # scope breadth: moving to a higher rank widens
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_ref(ref: str) -> tuple[str, str, str, str] | None:
|
|
41
|
+
"""``skill:<name>@<client>:<scope>[#agents]`` -> (kind, name, client, scope); ``None`` when malformed."""
|
|
42
|
+
base = ref.split("#", 1)[0]
|
|
43
|
+
kind, sep, rest = base.partition(":")
|
|
44
|
+
name, at, where = rest.rpartition("@")
|
|
45
|
+
client, colon, scope = where.partition(":")
|
|
46
|
+
if not (sep and at and colon and kind and name and client and scope):
|
|
47
|
+
return None
|
|
48
|
+
return kind, name, client, scope
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def parse_target(text: str) -> tuple[str, str] | None:
|
|
52
|
+
client, colon, scope = text.partition(":")
|
|
53
|
+
if colon and (client, scope) in TARGET_STORE:
|
|
54
|
+
return client, scope
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _candidates(report: dict, name: str) -> list[str]:
|
|
59
|
+
return sorted(item["ref"] for item in report["skills"] if item["name"] == name)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def build_plan(home: Path, project: Path, ref: str, to: str, mode: str = "copy", allow_widen: bool = False,
|
|
63
|
+
keep_source: bool = False, recovery_override: Path | None = None) -> tuple[dict, dict]:
|
|
64
|
+
"""The plan (JSON-safe) and a private context with absolute paths for apply. Reads only, never writes."""
|
|
65
|
+
home = home.expanduser().resolve()
|
|
66
|
+
project = project.expanduser().resolve()
|
|
67
|
+
parsed_early = parse_ref(ref)
|
|
68
|
+
if parsed_early is not None and parsed_early[0] == "mcp":
|
|
69
|
+
import agent_pack_mcp_write as mcp_write # noqa: PLC0415 - shipped next to this file
|
|
70
|
+
return mcp_write.build_plan(home, project, ref, to, allow_widen, keep_source, recovery_override, mode)
|
|
71
|
+
plan: dict[str, Any] = {
|
|
72
|
+
"ref": ref, "kind": "skill", "source": None, "target": None, "mode": mode, "retire_source": False,
|
|
73
|
+
"direction": None, "status": "blocked", "steps": [], "blocked": [], "warnings": [], "confirmations": [],
|
|
74
|
+
"recovery_base": ext.display(ext.recovery_base(home, recovery_override), home, project),
|
|
75
|
+
}
|
|
76
|
+
ctx: dict[str, Any] = {}
|
|
77
|
+
blocks = plan["blocked"]
|
|
78
|
+
|
|
79
|
+
parsed = parse_ref(ref)
|
|
80
|
+
target = parse_target(to)
|
|
81
|
+
if parsed is None:
|
|
82
|
+
blocks.append(ext.blocked("invalid-ref", _("引用格式应为 skill:<名>@<客户端>:<作用域>")))
|
|
83
|
+
elif parsed[0] != "skill":
|
|
84
|
+
blocks.append(ext.blocked("unsupported-kind", _("本版本只处理 Skill 与 MCP")))
|
|
85
|
+
if target is None:
|
|
86
|
+
blocks.append(ext.blocked("invalid-target", _("目标格式应为 <客户端>:<作用域>,客户端为 {0},作用域为 user|project").format("|".join(sorted({client for client, _scope in TARGET_STORE})))))
|
|
87
|
+
if blocks:
|
|
88
|
+
return _finish(plan), ctx
|
|
89
|
+
assert parsed is not None and target is not None
|
|
90
|
+
_kind, name, _src_client, _src_scope = parsed
|
|
91
|
+
target_client, target_scope = target
|
|
92
|
+
|
|
93
|
+
report = inv.observe(home, project, None, "skills", "all")
|
|
94
|
+
item = next((entry for entry in report["skills"] if entry["ref"] == ref), None)
|
|
95
|
+
if item is None:
|
|
96
|
+
near = _candidates(report, name)
|
|
97
|
+
blocks.append(ext.blocked("source-not-found", _("没有找到这个 Skill 引用"), candidates=near))
|
|
98
|
+
return _finish(plan), ctx
|
|
99
|
+
source_root = inv.resolve_store(item["store"], home, project)
|
|
100
|
+
source_path = source_root / item["name"] if source_root else None
|
|
101
|
+
plan["source"] = {"ref": ref, "name": name, "client": item["client"], "scope": item["scope"], "store": item["store"],
|
|
102
|
+
"path": item["path"], "is_symlink": item["is_symlink"], "content_sha256": item["content_sha256"]}
|
|
103
|
+
if source_path is None:
|
|
104
|
+
blocks.append(ext.blocked("project-not-found", _("需要项目目录,请用 --project 指定")))
|
|
105
|
+
return _finish(plan), ctx
|
|
106
|
+
if not project.is_dir() and (target_scope == "project" or item["scope"] == "project"):
|
|
107
|
+
blocks.append(ext.blocked("project-not-found", _("需要项目目录,请用 --project 指定")))
|
|
108
|
+
return _finish(plan), ctx
|
|
109
|
+
if item["evidence"] != "file" or not item["content_sha256"]:
|
|
110
|
+
blocks.append(ext.blocked("source-not-file-evidence", _("源条目没有文件级证据(目录损坏或没有可读的 SKILL.md),只读,不能迁移")))
|
|
111
|
+
store = TARGET_STORE[(target_client, target_scope)]
|
|
112
|
+
target_root = inv.resolve_store(store, home, project)
|
|
113
|
+
target_path = target_root / name
|
|
114
|
+
plan["target"] = {"client": target_client, "scope": target_scope, "store": store, "path": f"{store}/{name}"}
|
|
115
|
+
direction = "same" if item["scope"] == target_scope else ("widen" if RANK[target_scope] > RANK[item["scope"]] else "narrow")
|
|
116
|
+
plan["direction"] = direction
|
|
117
|
+
|
|
118
|
+
native = [s for sc, s in inv.SKILL_STORES[target_client] if sc == target_scope]
|
|
119
|
+
if item["store"] in native and not blocks:
|
|
120
|
+
plan["status"] = "native"
|
|
121
|
+
plan["steps"].append(ext.step("s1", "native-noop", "certain", to=plan["source"]["path"]))
|
|
122
|
+
plan["warnings"].append(ext.warning("native", _("这个客户端已经原生读取该存储,无需写入")))
|
|
123
|
+
return _finish(plan, status="native"), ctx
|
|
124
|
+
if direction == "widen" and not allow_widen:
|
|
125
|
+
blocks.append(ext.blocked("widen-needs-flag", _("项目级 → 用户级会放宽作用域(所有项目都会看到),需要 --allow-widen")))
|
|
126
|
+
if direction == "widen":
|
|
127
|
+
plan["warnings"].append(ext.warning("widen", _(WIDEN_WARNING)))
|
|
128
|
+
|
|
129
|
+
manifest = ext.tree_manifest(source_path) if not blocks else None
|
|
130
|
+
if not blocks:
|
|
131
|
+
if manifest is None:
|
|
132
|
+
blocks.append(ext.blocked("dir-too-large", _("Skill 目录文件过多(超过 {0} 个),不迁移").format(ext.MAX_TREE_FILES)))
|
|
133
|
+
else:
|
|
134
|
+
outside = ext.external_links(source_path, manifest)
|
|
135
|
+
if outside:
|
|
136
|
+
blocks.append(ext.blocked("source-has-external-symlink", _("Skill 目录内有指向目录外的符号链接,复制后会失效"), paths=outside))
|
|
137
|
+
effective_mode = mode
|
|
138
|
+
if mode == "link":
|
|
139
|
+
if item["scope"] != target_scope:
|
|
140
|
+
blocks.append(ext.blocked("link-cross-scope", _("跨作用域(家目录 ↔ 项目)不能用符号链接,只能复制")))
|
|
141
|
+
else:
|
|
142
|
+
hint = ext.sync_folder_hint(target_path) or ext.sync_folder_hint(source_path)
|
|
143
|
+
if hint:
|
|
144
|
+
effective_mode = "copy"
|
|
145
|
+
plan["warnings"].append(ext.warning("sync-folder-demoted", _("检测到同步盘位置({0}):同步盘对符号链接的行为没有一手文档,已降级为复制").format(hint), folder=hint))
|
|
146
|
+
plan["sync_folder"] = hint
|
|
147
|
+
plan["mode"] = effective_mode
|
|
148
|
+
if effective_mode == "link" and not keep_source:
|
|
149
|
+
plan["warnings"].append(ext.warning("link-keeps-source", _("符号链接模式必然保留源(目标指向它);两处内容同步变化")))
|
|
150
|
+
plan["retire_source"] = effective_mode == "copy" and not keep_source
|
|
151
|
+
|
|
152
|
+
if target_path.exists() or target_path.is_symlink():
|
|
153
|
+
if target_path.is_symlink() and not target_path.exists():
|
|
154
|
+
relation = "different"
|
|
155
|
+
else:
|
|
156
|
+
existing = ext.tree_manifest(target_path) if target_path.is_dir() else None
|
|
157
|
+
relation = "identical" if manifest is not None and existing == manifest else "different"
|
|
158
|
+
blocks.append(ext.blocked("target-exists-" + relation, _("目标已存在同名条目(内容{0}),不覆盖、不改名、不合并").format(
|
|
159
|
+
_("相同") if relation == "identical" else _("不同")), target=plan["target"]["path"]))
|
|
160
|
+
if os.path.realpath(source_path) == os.path.realpath(target_path):
|
|
161
|
+
blocks.append(ext.blocked("target-is-source", _("目标就是源本身")))
|
|
162
|
+
|
|
163
|
+
if target_scope == "project" and item["scope"] == "user":
|
|
164
|
+
relative = f"{store[len(inv.PROJECT) + 1:]}/{name}"
|
|
165
|
+
plan["confirmations"].append({
|
|
166
|
+
"id": "project-content",
|
|
167
|
+
"text": _("将进入项目目录:{0}(可能被提交到版本库);请自行确认其许可证与是否含私有内容,工具无法判断").format(relative),
|
|
168
|
+
"flag": "--confirm-project-content"})
|
|
169
|
+
|
|
170
|
+
if not blocks:
|
|
171
|
+
steps = plan["steps"]
|
|
172
|
+
steps.append(ext.step("s1", "create-recovery-dir", "certain", to=plan["recovery_base"]))
|
|
173
|
+
if effective_mode == "link":
|
|
174
|
+
steps.append(ext.step("s2", "create-link", "best-effort", to=plan["target"]["path"], target=plan["source"]["path"]))
|
|
175
|
+
else:
|
|
176
|
+
steps.append(ext.step("s2", "copy-tree", "certain", from_=plan["source"]["path"], to=plan["target"]["path"],
|
|
177
|
+
files=len(manifest or []), tree_digest=ext.tree_digest(manifest or [])))
|
|
178
|
+
steps.append(ext.step("s3", "verify-readback", "certain", to=plan["target"]["path"]))
|
|
179
|
+
steps.append(ext.step("s4", "archive-source" if plan["retire_source"] else "keep-source", "certain",
|
|
180
|
+
from_=plan["source"]["path"]))
|
|
181
|
+
steps.append(ext.step("s5", "confirm-in-client", "cannot-promise" if plan.get("sync_folder") else "best-effort",
|
|
182
|
+
client=target_client))
|
|
183
|
+
plan["status"] = "blocked" if blocks else "ready"
|
|
184
|
+
ctx.update(source=source_path, target=target_path, manifest=manifest, home=home, project=project,
|
|
185
|
+
recovery_override=recovery_override)
|
|
186
|
+
return _finish(plan), ctx
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _finish(plan: dict, status: str | None = None) -> dict:
|
|
190
|
+
for entry in plan["steps"]:
|
|
191
|
+
if "from_" in entry:
|
|
192
|
+
entry["from"] = entry.pop("from_")
|
|
193
|
+
if status:
|
|
194
|
+
plan["status"] = status
|
|
195
|
+
plan["plan_digest"] = ext.plan_digest(plan)
|
|
196
|
+
return plan
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def next_command(plan: dict, args_text: str) -> str:
|
|
200
|
+
return f"agenthelm relocate {args_text} --apply --expect-plan {plan['plan_digest']}" + (
|
|
201
|
+
" --confirm-project-content" if plan["confirmations"] else "")
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ------------------------------------------------------------------ apply
|
|
205
|
+
|
|
206
|
+
def apply_plan(plan: dict, ctx: dict, confirm_project: bool) -> dict:
|
|
207
|
+
"""Execute a ready plan. Never raises for expected failures; returns the ``applied`` record."""
|
|
208
|
+
if plan["kind"] == "mcp":
|
|
209
|
+
import agent_pack_mcp_write as mcp_write # noqa: PLC0415
|
|
210
|
+
return mcp_write.apply_plan(plan, ctx, confirm_project)
|
|
211
|
+
home, project = ctx["home"], ctx["project"]
|
|
212
|
+
source: Path = ctx["source"]
|
|
213
|
+
target: Path = ctx["target"]
|
|
214
|
+
manifest = ctx["manifest"]
|
|
215
|
+
if plan["status"] == "native":
|
|
216
|
+
return {"status": "native", "written": False}
|
|
217
|
+
if plan["confirmations"] and not confirm_project:
|
|
218
|
+
return {"status": "refused", "reason": "project-content-unconfirmed", "written": False,
|
|
219
|
+
"message": _("需要确认:{0}(加 --confirm-project-content)").format(plan["confirmations"][0]["text"])}
|
|
220
|
+
base = ext.recovery_base(home, ctx["recovery_override"])
|
|
221
|
+
moved: list[tuple[Path, Path]] = []
|
|
222
|
+
created: list[Path] = []
|
|
223
|
+
made_dirs: list[Path] = []
|
|
224
|
+
recovery: Path | None = None
|
|
225
|
+
staging: Path | None = None
|
|
226
|
+
try:
|
|
227
|
+
recovery = ext.new_recovery_dir(base, f"relocate-{plan['source']['name']}")
|
|
228
|
+
ext.write_private_json(recovery / "relocate.json", {
|
|
229
|
+
"schema_version": ext.SCHEMA_VERSION, "ref": plan["ref"], "source": plan["source"]["path"],
|
|
230
|
+
"target": plan["target"]["path"], "mode": plan["mode"], "plan_digest": plan["plan_digest"]})
|
|
231
|
+
if target.exists() or target.is_symlink():
|
|
232
|
+
raise ext.ExtError("target appeared after the preview")
|
|
233
|
+
made_dirs = ext.make_parents(target.parent)
|
|
234
|
+
if plan["mode"] == "link":
|
|
235
|
+
relative = os.path.relpath(source, target.parent)
|
|
236
|
+
os.symlink(relative, target, target_is_directory=True)
|
|
237
|
+
created.append(target)
|
|
238
|
+
if os.readlink(target) != relative or os.path.realpath(target) != os.path.realpath(source):
|
|
239
|
+
raise ext.ExtError("link read-back mismatch")
|
|
240
|
+
else:
|
|
241
|
+
staging = target.parent / f".{target.name}.agenthelm-tmp-{os.getpid()}"
|
|
242
|
+
ext.copy_tree(source, staging)
|
|
243
|
+
created.append(staging)
|
|
244
|
+
if not ext.readback_matches(manifest, staging):
|
|
245
|
+
raise ext.ExtError("copy read-back mismatch")
|
|
246
|
+
if target.exists() or target.is_symlink():
|
|
247
|
+
raise ext.ExtError("target appeared after the preview")
|
|
248
|
+
os.rename(staging, target)
|
|
249
|
+
created.remove(staging)
|
|
250
|
+
created.append(target)
|
|
251
|
+
if not ext.readback_matches(manifest, target):
|
|
252
|
+
raise ext.ExtError("installed copy read-back mismatch")
|
|
253
|
+
archived = None
|
|
254
|
+
if plan["retire_source"]:
|
|
255
|
+
archived = ext.archive(source, recovery, "skills", plan["source"]["name"])
|
|
256
|
+
moved.append((archived, source))
|
|
257
|
+
except Exception as exc: # noqa: BLE001 - every failure must roll back the same way
|
|
258
|
+
ext.rollback_moves(moved)
|
|
259
|
+
for path in reversed(created):
|
|
260
|
+
ext.remove_created(path)
|
|
261
|
+
ext.remove_empty_parents(made_dirs)
|
|
262
|
+
return {"status": "rolled-back", "written": False, "reason": type(exc).__name__,
|
|
263
|
+
"message": _("失败,已回滚:{0}").format(str(exc)),
|
|
264
|
+
"recovery_dir": ext.display(recovery, home, project) if recovery else None}
|
|
265
|
+
applied: dict[str, Any] = {
|
|
266
|
+
"status": "applied", "written": True, "mode": plan["mode"],
|
|
267
|
+
"target": plan["target"]["path"], "readback": {"files": len(manifest), "ok": True,
|
|
268
|
+
"skill_md_sha256": plan["source"]["content_sha256"]},
|
|
269
|
+
"recovery_dir": ext.display(recovery, home, project), "archived": None, "restore": [],
|
|
270
|
+
}
|
|
271
|
+
if archived is not None:
|
|
272
|
+
applied["archived"] = ext.display(archived, home, project)
|
|
273
|
+
applied["restore"] = [ext.restore_line(archived, source, home)]
|
|
274
|
+
applied["restore_note"] = _("恢复:把归档目录移回原位(本版没有 restore 命令)")
|
|
275
|
+
return applied
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
# ------------------------------------------------------------------ text
|
|
279
|
+
|
|
280
|
+
ACTION_TEXT = {
|
|
281
|
+
"native-noop": N_("无需写入:{to} 已被该客户端原生读取"),
|
|
282
|
+
"create-recovery-dir": N_("在 {to} 下建恢复目录(权限 0700)"),
|
|
283
|
+
"copy-tree": N_("复制 {from} → {to}({files} 个条目,目录内符号链接保持为链接)"),
|
|
284
|
+
"create-link": N_("建立相对符号链接 {to} → {target}"),
|
|
285
|
+
"verify-readback": N_("读回校验 {to}:逐文件比较相对路径与内容摘要,SKILL.md 摘要与源一致"),
|
|
286
|
+
"archive-source": N_("校验通过后把源 {from} 归档到恢复目录(归档不是删除)"),
|
|
287
|
+
"keep-source": N_("保留源 {from}"),
|
|
288
|
+
"confirm-in-client": N_("下一步:重启 {client} 或重新进入项目,确认它出现(工具不执行客户端命令)"),
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def render_text(plan: dict, applied: dict | None, command: str, color: bool = False) -> str:
|
|
293
|
+
import agent_pack_mcp_write as mcp_write # noqa: PLC0415
|
|
294
|
+
lines = []
|
|
295
|
+
preview = applied is None
|
|
296
|
+
lines.append(_("agenthelm relocate:预览(未写入任何文件)") if preview else _("agenthelm relocate:已执行"))
|
|
297
|
+
lines.append(_("来源:{0}").format(plan["ref"]))
|
|
298
|
+
if plan["target"]:
|
|
299
|
+
lines.append(_("目标:{0}:{1} {2}").format(plan["target"]["client"], plan["target"]["scope"], plan["target"]["path"]))
|
|
300
|
+
direction = {"narrow": _("收窄"), "same": _("同级"), "widen": _("放宽")}[plan["direction"]]
|
|
301
|
+
text = _("方式:{0};方向:{1}").format(plan["mode"], direction)
|
|
302
|
+
lines.append(ext.red(text, color) if plan["direction"] == "widen" else text)
|
|
303
|
+
for entry in plan["steps"]:
|
|
304
|
+
template = ACTION_TEXT.get(entry["action"]) or mcp_write.ACTION_TEXT[entry["action"]]
|
|
305
|
+
body = _(template).format(**entry)
|
|
306
|
+
lines.append(f" {entry['id']} [{entry['promise']}] {body}")
|
|
307
|
+
for entry in plan.get("manual", []):
|
|
308
|
+
lines.append(_("手工(不可由工具归档):{0}").format(entry.get("command") or entry.get("instruction")))
|
|
309
|
+
if entry.get("backup"):
|
|
310
|
+
lines.append(_(" 先备份:{0}").format(entry["backup"]))
|
|
311
|
+
for warning in plan["warnings"]:
|
|
312
|
+
text = _("注意:{0}").format(warning["message"])
|
|
313
|
+
lines.append(ext.red(text, color) if warning["code"] == "widen" else text)
|
|
314
|
+
for entry in plan["confirmations"]:
|
|
315
|
+
lines.append(_("需要确认({0}):{1}").format(entry["flag"], entry["text"]))
|
|
316
|
+
for entry in plan["blocked"]:
|
|
317
|
+
lines.append(_("已阻止 [{0}]:{1}").format(entry["code"], entry["message"]))
|
|
318
|
+
for candidate in entry.get("candidates", []):
|
|
319
|
+
lines.append(f" - {candidate}")
|
|
320
|
+
if preview:
|
|
321
|
+
lines.append(_("计划指纹:{0}").format(plan["plan_digest"]))
|
|
322
|
+
if plan["status"] == "ready":
|
|
323
|
+
lines.append(_("确认后执行:{0}").format(command))
|
|
324
|
+
else:
|
|
325
|
+
lines.append(_("结果:{0}").format(applied["status"]))
|
|
326
|
+
if applied.get("message"):
|
|
327
|
+
lines.append(applied["message"])
|
|
328
|
+
if applied.get("recovery_dir"):
|
|
329
|
+
lines.append(_("恢复目录:{0}").format(applied["recovery_dir"]))
|
|
330
|
+
for line in applied.get("restore", []):
|
|
331
|
+
lines.append(_("手工恢复:{0}").format(line))
|
|
332
|
+
return "\n".join(lines) + "\n"
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# ------------------------------------------------------------------ CLI
|
|
336
|
+
|
|
337
|
+
def run(args: Any, home: Path) -> int:
|
|
338
|
+
"""Entry for ``agenthelm relocate``. Exit codes: 0 ok / preview without blocks, 1 blocked or failed, 2 usage."""
|
|
339
|
+
if args.lang and args.lang != "auto":
|
|
340
|
+
os.environ["AGENTHELM_LANG"] = args.lang
|
|
341
|
+
if sys.platform not in ("darwin",) and not sys.platform.startswith("linux"):
|
|
342
|
+
sys.stderr.write(_("只支持 macOS 与 Linux\n"))
|
|
343
|
+
return 2
|
|
344
|
+
if args.apply and not args.expect_plan:
|
|
345
|
+
sys.stderr.write(_("--apply 必须带 --expect-plan <计划指纹>(先预览取得)\n"))
|
|
346
|
+
return 2
|
|
347
|
+
project = (args.project or Path.cwd()).resolve()
|
|
348
|
+
recovery_override = getattr(args, "recovery_root", None)
|
|
349
|
+
plan, ctx = build_plan(home, project, args.ref, args.to, args.mode, args.allow_widen, args.keep_source, recovery_override)
|
|
350
|
+
args_text = _command_text(args)
|
|
351
|
+
command = next_command(plan, args_text)
|
|
352
|
+
plan["next"] = {"apply": command}
|
|
353
|
+
applied = None
|
|
354
|
+
code = 1 if plan["blocked"] else 0
|
|
355
|
+
if args.apply:
|
|
356
|
+
if plan["plan_digest"] != args.expect_plan:
|
|
357
|
+
applied = {"status": "refused", "reason": "plan-digest-mismatch", "written": False,
|
|
358
|
+
"message": _("计划指纹与预览不一致(源、目标或参数已变化),未写入;请重新预览。当前指纹:{0}").format(plan["plan_digest"])}
|
|
359
|
+
code = 1
|
|
360
|
+
elif plan["blocked"]:
|
|
361
|
+
applied = {"status": "refused", "reason": "blocked", "written": False}
|
|
362
|
+
else:
|
|
363
|
+
applied = apply_plan(plan, ctx, args.confirm_project_content)
|
|
364
|
+
code = 0 if applied["status"] in ("applied", "native") else 1
|
|
365
|
+
if args.output == "json":
|
|
366
|
+
document = {"schema_version": ext.SCHEMA_VERSION, "command": "relocate",
|
|
367
|
+
"mode": "apply" if args.apply else "preview", "plan": plan, "applied": applied}
|
|
368
|
+
print(json.dumps(document, ensure_ascii=False, indent=2))
|
|
369
|
+
else:
|
|
370
|
+
sys.stdout.write(render_text(plan, applied, command, ext.use_color()))
|
|
371
|
+
return code
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _command_text(args: Any) -> str:
|
|
375
|
+
import shlex # noqa: PLC0415
|
|
376
|
+
parts = [shlex.quote(args.ref), "--to", shlex.quote(args.to)]
|
|
377
|
+
if args.mode != "copy":
|
|
378
|
+
parts += ["--mode", args.mode]
|
|
379
|
+
if args.project:
|
|
380
|
+
parts += ["--project", shlex.quote(str(args.project))]
|
|
381
|
+
if args.allow_widen:
|
|
382
|
+
parts.append("--allow-widen")
|
|
383
|
+
if args.keep_source:
|
|
384
|
+
parts.append("--keep-source")
|
|
385
|
+
return " ".join(parts)
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Scope view of a Claude sync (#67): which entries are user-level, which the project declares as project-level,
|
|
2
|
+
what a narrowing would take away from other projects, and how the preview groups them.
|
|
3
|
+
|
|
4
|
+
Pure helpers over plain data so the preview and ``--apply`` read one plan: ``agent_pack_claude.plan_project``
|
|
5
|
+
decides, this module only describes. Nothing here writes. Output never carries configuration values.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
RUNTIME_DIR = Path(__file__).resolve().parent
|
|
16
|
+
if str(RUNTIME_DIR) not in sys.path:
|
|
17
|
+
sys.path.insert(0, str(RUNTIME_DIR))
|
|
18
|
+
from i18n_agent_pack import _, N_ # noqa: E402
|
|
19
|
+
|
|
20
|
+
SCOPE_FILTERS = ("user", "project", "all")
|
|
21
|
+
STATE_SCHEMA = 1
|
|
22
|
+
|
|
23
|
+
# store ids (the ``store`` field of an operation); a later store is added only with the code that writes it
|
|
24
|
+
USER_SKILLS, USER_MCP = "claude-user-skills", "claude-user"
|
|
25
|
+
PROJECT_SKILLS, LOCAL_MCP, FILE_MCP = "project-skills", "claude-local", "project-file"
|
|
26
|
+
|
|
27
|
+
STORE_TITLE = {
|
|
28
|
+
USER_SKILLS: N_("用户级 · 对所有项目生效"),
|
|
29
|
+
USER_MCP: N_("用户级 · 对所有项目生效"),
|
|
30
|
+
PROJECT_SKILLS: N_("项目级 · 仅此项目 · .claude/skills"),
|
|
31
|
+
LOCAL_MCP: N_("项目级 · 仅此项目 · local(~/.claude.json,不进版本库)"),
|
|
32
|
+
FILE_MCP: N_("项目级 · 仅此项目 · 项目文件 .mcp.json"),
|
|
33
|
+
}
|
|
34
|
+
STORE_ORDER = (USER_SKILLS, USER_MCP, LOCAL_MCP, FILE_MCP, PROJECT_SKILLS)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def normalize_scope(scope: str | None) -> str:
|
|
38
|
+
value = scope or "all"
|
|
39
|
+
if value not in SCOPE_FILTERS:
|
|
40
|
+
raise ValueError(f"unknown --scope: {value} (choose from {', '.join(SCOPE_FILTERS)})")
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def other_projects(home: Path, package: str) -> list[dict[str, Any]]:
|
|
45
|
+
"""Ownership records of the other projects synced on this machine (``~/.claude/agent-pack/state/*.json``).
|
|
46
|
+
|
|
47
|
+
Only projects that were synced here are visible; a project never synced on this machine cannot be counted.
|
|
48
|
+
"""
|
|
49
|
+
directory = home / ".claude" / "agent-pack" / "state"
|
|
50
|
+
found: list[dict[str, Any]] = []
|
|
51
|
+
if not directory.is_dir():
|
|
52
|
+
return found
|
|
53
|
+
for path in sorted(directory.glob("*.json")):
|
|
54
|
+
if path.stem == package or path.is_symlink():
|
|
55
|
+
continue
|
|
56
|
+
try:
|
|
57
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
58
|
+
except (OSError, ValueError):
|
|
59
|
+
continue
|
|
60
|
+
if not isinstance(data, dict) or data.get("schema_version") != STATE_SCHEMA:
|
|
61
|
+
continue
|
|
62
|
+
skills = data.get("skills")
|
|
63
|
+
mcps = data.get("mcps")
|
|
64
|
+
found.append({"package": path.stem,
|
|
65
|
+
"skills": {name for name in skills if isinstance(name, str)} if isinstance(skills, list) else set(),
|
|
66
|
+
"mcps": {str(name) for name in mcps} if isinstance(mcps, dict) else set()})
|
|
67
|
+
return found
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def narrowing_entry(kind: str, name: str, from_store: str, to_store: str, others: list[dict[str, Any]]) -> dict[str, Any]:
|
|
71
|
+
key = "skills" if kind == "skill" else "mcps"
|
|
72
|
+
return {"kind": kind, "name": name, "from_store": from_store, "to_store": to_store,
|
|
73
|
+
"other_projects": len(others),
|
|
74
|
+
"also_declared_by": sorted(item["package"] for item in others if name in item[key]),
|
|
75
|
+
"counted_from": "state", "status": "not-applied"}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def narrowing_note() -> str:
|
|
79
|
+
return _("只统计在本机同步过的项目(~/.claude/agent-pack/state),未同步过的项目看不到,也无法计入")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# ---------------------------------------------------------------- preview text
|
|
83
|
+
|
|
84
|
+
def _line(operation: dict[str, Any]) -> str:
|
|
85
|
+
target = operation.get("to") or operation.get("from", "")
|
|
86
|
+
return f"- {operation['action']}: {operation.get('name', '')} -> {target}"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def grouped_lines(value: dict[str, Any]) -> list[str]:
|
|
90
|
+
"""Operations of a scope-aware preview, one heading per store (user level first)."""
|
|
91
|
+
lines: list[str] = []
|
|
92
|
+
operations = value.get("operations", [])
|
|
93
|
+
unscoped = [item for item in operations if "store" not in item]
|
|
94
|
+
for item in unscoped:
|
|
95
|
+
lines.append(_line(item))
|
|
96
|
+
for store in STORE_ORDER:
|
|
97
|
+
group = [item for item in operations if item.get("store") == store]
|
|
98
|
+
if not group:
|
|
99
|
+
continue
|
|
100
|
+
lines.append(f"[{_(STORE_TITLE[store])}]")
|
|
101
|
+
lines.extend(" " + _line(item) for item in group)
|
|
102
|
+
return lines
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def narrowing_lines(value: dict[str, Any]) -> list[str]:
|
|
106
|
+
lines: list[str] = []
|
|
107
|
+
for item in value.get("narrowing", []):
|
|
108
|
+
known = item["other_projects"]
|
|
109
|
+
lines.append("~ " + _("收窄:{n} 个项目将不再看到 {kind} {name}").format(
|
|
110
|
+
n=known, kind=item["kind"], name=item["name"]))
|
|
111
|
+
if item["also_declared_by"]:
|
|
112
|
+
lines.append(" " + _("其中也声明了它的项目记录:{names}").format(names=", ".join(item["also_declared_by"])))
|
|
113
|
+
if item.get("status") == "planned":
|
|
114
|
+
lines.append(" " + _("用户级原条目将归档到恢复目录(可取回)"))
|
|
115
|
+
else:
|
|
116
|
+
lines.append(" " + _("本次不改动用户级原条目"))
|
|
117
|
+
return lines
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def skipped_lines(value: dict[str, Any]) -> list[str]:
|
|
121
|
+
return ["~ " + _("跳过 {kind} {name}({client}):{reason}").format(
|
|
122
|
+
kind=item["kind"], name=item["name"], client=item["client"], reason=_(REASONS.get(item["reason"], item["reason"])))
|
|
123
|
+
for item in value.get("skipped", [])]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
REASONS = {
|
|
127
|
+
"project-skills-symlink": N_("项目 .claude/skills 或 .claude 是符号链接,未写入"),
|
|
128
|
+
"skill-source-outside-project": N_("Skill 源目录不在项目内,未写入"),
|
|
129
|
+
"local-structure-unrecognized": N_("~/.claude.json 里按项目路径存放的条目结构无法识别,未写入"),
|
|
130
|
+
"target-not-writable": N_("目标位置不可写,未写入"),
|
|
131
|
+
"mcp-json-symlink": N_(".mcp.json 是符号链接,未写入"),
|
|
132
|
+
"mcp-json-unreadable": N_(".mcp.json 无法解析,未写入"),
|
|
133
|
+
"project-write-unavailable": N_("项目级写入尚未提供;不会回退写入用户级"),
|
|
134
|
+
"project-native": N_("Skill 由项目 .agents/skills 原生加载,不写用户级包"),
|
|
135
|
+
"client-project-unsupported": N_("该客户端的项目级 MCP 写入尚未提供;不会回退写入用户级"),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def skipped_warning(item: dict[str, str]) -> str:
|
|
140
|
+
"""The warning for one skipped project-declared entry (a client whose project level is not written yet)."""
|
|
141
|
+
return _("{kind} {name} 声明为项目级,对 {client} 跳过:{reason}").format(
|
|
142
|
+
kind=item["kind"], name=item["name"], client=item["client"], reason=_(REASONS.get(item["reason"], item["reason"])))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def undeclared_warning(names: list[str]) -> str:
|
|
146
|
+
return _("为项目里不存在的条目声明了作用域:{names}").format(names=", ".join(names))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def project_replace_warning(count: int) -> str:
|
|
150
|
+
return _("替换 {n} 个项目级 MCP 条目;它们只对本项目生效(被替换的原文件进恢复目录)").format(n=count)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# ---------------------------------------------------------------- migration and shadowing
|
|
154
|
+
|
|
155
|
+
def migration_entry(kind: str, name: str, direction: str, from_store: str, to_store: str, *,
|
|
156
|
+
write_new: str, retire: dict[str, str]) -> dict[str, Any]:
|
|
157
|
+
"""One entry whose declared scope changed: write the new location, then retire the old one.
|
|
158
|
+
|
|
159
|
+
``direction`` is ``narrow`` (user -> project) or ``widen`` (project -> user). A Skill's old location is
|
|
160
|
+
archived by the same plan; an MCP entry's old location is only named (``manual``), never edited here.
|
|
161
|
+
"""
|
|
162
|
+
return {"kind": kind, "name": name, "direction": direction, "from_store": from_store, "to_store": to_store,
|
|
163
|
+
"steps": [{"step": "write-new", "action": write_new}, {"step": "retire-old", **retire}]}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def migration_lines(value: dict[str, Any]) -> list[str]:
|
|
167
|
+
lines: list[str] = []
|
|
168
|
+
for item in value.get("migrations", []):
|
|
169
|
+
arrow = _("收窄") if item["direction"] == "narrow" else _("放宽")
|
|
170
|
+
lines.append("~ " + _("作用域迁移({direction}):{kind} {name}").format(
|
|
171
|
+
direction=arrow, kind=item["kind"], name=item["name"]))
|
|
172
|
+
new, old = item["steps"]
|
|
173
|
+
lines.append(" 1. " + _("写入新位置:{action}").format(action=new["action"]))
|
|
174
|
+
if old["action"] == "manual":
|
|
175
|
+
lines.append(" 2. " + _("从旧位置退役(不自动编辑,请手工执行):{command}").format(command=old["command"]))
|
|
176
|
+
elif old["action"] == "none":
|
|
177
|
+
lines.append(" 2. " + _("旧位置不由本包创建,不退役"))
|
|
178
|
+
else:
|
|
179
|
+
lines.append(" 2. " + _("从旧位置退役:{action}").format(action=old["action"]))
|
|
180
|
+
return lines
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def widen_warning(kind: str, name: str) -> str:
|
|
184
|
+
return _("放宽:此后所有项目都会看到 {kind} {name}").format(kind=kind, name=name)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _inventory():
|
|
188
|
+
import agent_pack_inventory # noqa: PLC0415 - read-only observation layer (M1); only its precedence rules are used
|
|
189
|
+
|
|
190
|
+
return agent_pack_inventory
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def skill_shadow(name: str) -> dict[str, Any] | None:
|
|
194
|
+
"""A project-level Skill that a same-name user-level Skill outranks, by the precedence the inventory layer
|
|
195
|
+
already encodes (Claude: personal over project, from the official Skills documentation). None when the
|
|
196
|
+
documentation states no precedence."""
|
|
197
|
+
inventory = _inventory()
|
|
198
|
+
group = [{"scope": "user", "store": "~/.claude/skills"}, {"scope": "project", "store": ".claude/skills"}]
|
|
199
|
+
effective = inventory._skill_effective("claude", group)
|
|
200
|
+
if effective.get("evidence") == "unknown" or not effective.get("store"):
|
|
201
|
+
return None
|
|
202
|
+
return {"kind": "skill", "name": name, "client": "claude", "effective_store": effective["store"],
|
|
203
|
+
"shadowed_store": ".claude/skills", "rule": effective["rule"], "evidence": effective["evidence"],
|
|
204
|
+
"source_url": effective["source_url"], "advisory": True}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def mcp_shadow(name: str, project_store: str) -> dict[str, Any] | None:
|
|
208
|
+
"""A same-name user-level MCP entry next to the new project-level one. Only a Claude ``local`` winner is
|
|
209
|
+
concluded (``.mcp.json`` depends on a per-project approval this version does not read)."""
|
|
210
|
+
inventory = _inventory()
|
|
211
|
+
scope = "local" if project_store == "local" else "project"
|
|
212
|
+
group = [{"scope": "user", "store": "~/.claude.json"}, {"scope": scope, "store": project_store}]
|
|
213
|
+
effective = inventory._mcp_effective("claude", group)
|
|
214
|
+
if effective.get("evidence") == "unknown" or not effective.get("store"):
|
|
215
|
+
return None
|
|
216
|
+
return {"kind": "mcp", "name": name, "client": "claude", "effective_store": effective["store"],
|
|
217
|
+
"shadowed_store": "~/.claude.json", "rule": effective["rule"], "evidence": effective["evidence"],
|
|
218
|
+
"source_url": effective["source_url"], "advisory": True}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def project_skills_replace_warning(count: int) -> str:
|
|
222
|
+
return _("替换 {n} 个项目级 Skill;它们只对本项目生效(被替换的原件进恢复目录)").format(n=count)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def sync_folder_warning(service: str | None) -> str:
|
|
226
|
+
return _("项目位于同步盘({service}):项目级 Skill 改为复制而不是符号链接(同步盘对符号链接的行为未核实)").format(
|
|
227
|
+
service=service or "?")
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def shadow_warning(item: dict[str, Any]) -> str:
|
|
231
|
+
return _("{kind} {name}:{shadowed} 的同名项被 {winner} 优先({rule},仅建议)").format(
|
|
232
|
+
kind=item["kind"], name=item["name"], shadowed=item["shadowed_store"], winner=item["effective_store"],
|
|
233
|
+
rule=item["rule"])
|