@sakanano-moe/agenthelm 6.13.1 → 6.14.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,415 @@
1
+ """技能与 MCP 的写入动作:move / dedupe / scope(默认预览,``--apply`` 才写)。
2
+
3
+ - move、dedupe 全部转发给 agent-pack 的 ``agenthelm relocate`` / ``agenthelm dedupe``(参数列表形式的子进程,``--output json``),
4
+ 不 import agent-pack。它们的 plan(含 ``plan_digest``、``blocked``、``promise``、``confirmations``)原样展示;
5
+ ``--apply`` 时先重新预览并比对摘要,不一致就拒绝(没有任何写入),一致才用 ``--expect-plan`` 回传同一摘要。
6
+ - scope 把「生效范围」写成 Project Profile 的 ``capabilities.mcp_scope`` / ``skill_scope`` 声明(agent-pack 的 sync / reconcile 读取它):
7
+ 预览给 diff 与可粘贴片段;``--apply`` 先把 Profile 备份到恢复目录,再原子写入,写后读回。
8
+ - 输出里不含 env 值、headers、令牌:转发来的 plan 经过一次递归清洗,只留白名单之外的键被丢弃。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import difflib
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import tempfile
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from i18n_orchestrator import _, N_ # noqa: E402
23
+ from wf import S
24
+ import project_extensions as ext
25
+ from project_base import PROFILE, EntryError, read_profile
26
+
27
+ ACTION_TIMEOUT_SECONDS = 180
28
+ SECRET_KEYS = frozenset({"env", "headers", "token", "secret", "password", "authorization", "args", "command_line"})
29
+ REF_RE = re.compile(r"^(skill|mcp):([^@\s]+)@([a-z0-9-]+):([a-z]+)(#[a-z0-9-]+)?$")
30
+ SCOPE_KEY = {"skill": "skill_scope", "mcp": "mcp_scope"}
31
+ NO_WRITE_GROUP = N_("此类重复(跨客户端或证据不足)本版没有写入动作")
32
+ EXT_HINT = N_("更新 agent-pack 或运行时(需要 agenthelm relocate / dedupe)后再试")
33
+ DISPOSITIONS = ("retire-others", "keep-all", "ignore", "unignore")
34
+
35
+
36
+ # ---------------------------------------------------------------- 子进程与清洗
37
+
38
+ def scrub(value: Any) -> Any:
39
+ """递归去掉可能携带值的键:env、headers、令牌类。agent-pack 本身不输出它们,这里是第二道防线。"""
40
+ if isinstance(value, dict):
41
+ return {key: scrub(item) for key, item in value.items() if str(key).lower() not in SECRET_KEYS}
42
+ if isinstance(value, list):
43
+ return [scrub(item) for item in value]
44
+ return value
45
+
46
+
47
+ def run_agenthelm(host: Any, tail: list[str]) -> tuple[int, dict]:
48
+ command = ext.agenthelm_command(host)
49
+ if command is None:
50
+ raise EntryError(_("未找到 agent-pack 的 agenthelm 命令"), "unavailable", [_(EXT_HINT)])
51
+ try:
52
+ code, out, err = ext._run([*command, *tail], ACTION_TIMEOUT_SECONDS)
53
+ except OSError as exc:
54
+ raise EntryError(_("无法运行 agenthelm:{0}").format(exc), "unavailable") from exc
55
+ try:
56
+ data = json.loads(out)
57
+ except ValueError:
58
+ data = None
59
+ if not isinstance(data, dict):
60
+ if code == 2:
61
+ raise EntryError(_("当前的 agenthelm 不认识这个命令或参数(需要更新 agent-pack):{0}").format(err or tail[0]), "unavailable")
62
+ raise EntryError(_("agenthelm {0} 没有返回可解析的结果:{1}").format(tail[0], err or _("输出不是 JSON")), "failed")
63
+ return code, scrub(data)
64
+
65
+
66
+ def _blocked(plan: dict) -> bool:
67
+ return bool(plan.get("blocked")) or plan.get("status") == "blocked"
68
+
69
+
70
+ def _forward(host: Any, root: Path, tail: list[str], *, apply: bool, expect: str | None) -> dict:
71
+ """预览一次;--apply 时重算摘要并比对,一致才转发 --apply --expect-plan。返回 {mode, plan, applied, refused?}。"""
72
+ base = [*tail, "--project", str(root), "--output", "json"]
73
+ _code, preview = run_agenthelm(host, base)
74
+ plan = preview.get("plan")
75
+ if not isinstance(plan, dict):
76
+ raise EntryError(_("agenthelm 没有给出计划:{0}").format(preview.get("error") or _("无详情")), "failed")
77
+ result = {"mode": "preview", "plan": plan, "applied": None, "blocked": _blocked(plan)}
78
+ if not apply:
79
+ return result
80
+ if not expect:
81
+ raise EntryError(_("--apply 需要 --expect-plan <预览里的 plan_digest>"), "usage",
82
+ [_("先不加 --apply 运行一次预览,复制其中的 plan_digest")])
83
+ result["mode"] = "apply"
84
+ if plan.get("plan_digest") != expect:
85
+ return {**result, "applied": {"status": "refused", "reason": "plan-changed"}, "refused": "plan-changed"}
86
+ if _blocked(plan):
87
+ return {**result, "applied": {"status": "refused", "reason": "blocked"}, "refused": "blocked"}
88
+ code, done = run_agenthelm(host, [*base, "--apply", "--expect-plan", expect])
89
+ applied = done.get("applied")
90
+ if not isinstance(applied, dict):
91
+ applied = {"status": "failed", "reason": str(done.get("error") or code)}
92
+ result["applied"] = applied
93
+ if isinstance(done.get("plan"), dict):
94
+ result["plan"] = done["plan"]
95
+ return result
96
+
97
+
98
+ # ---------------------------------------------------------------- move / dedupe
99
+
100
+ def move(host: Any, root: Path, ref: str, to: str, *, mode: str | None = None, keep_source: bool = False,
101
+ allow_widen: bool = False, confirm_content: bool = False, apply: bool = False, expect: str | None = None) -> dict:
102
+ parsed = REF_RE.match(ref)
103
+ if parsed is None:
104
+ raise EntryError(_("条目引用不合法:{0}").format(ref), "usage", [_("形如 skill:<名>@<客户端>:<作用域>;用 extensions list 查看")])
105
+ tail = ["relocate", ref, "--to", to]
106
+ if mode:
107
+ tail += ["--mode", mode]
108
+ for flag, on in (("--keep-source", keep_source), ("--allow-widen", allow_widen), ("--confirm-project-content", confirm_content)):
109
+ if on:
110
+ tail.append(flag)
111
+ result = _forward(host, root, tail, apply=apply, expect=expect)
112
+ result["action"] = "move"
113
+ return result
114
+
115
+
116
+ def dedupe_groups(host: Any, root: Path) -> list[dict] | None:
117
+ """dedupe --list 的分组;旧版 agenthelm 或失败时返回 None(交给 dedupe 自己判断)。"""
118
+ try:
119
+ _code, data = run_agenthelm(host, ["dedupe", "--list", "--project", str(root), "--output", "json"])
120
+ except EntryError:
121
+ return None
122
+ groups = data.get("groups")
123
+ return [group for group in groups if isinstance(group, dict)] if isinstance(groups, list) else None
124
+
125
+
126
+ def unsupported_group(group_id: str) -> dict:
127
+ return {"mode": "preview", "action": "dedupe", "plan": None, "applied": None, "blocked": True, "group": group_id,
128
+ "unsupported": True, "message": _(NO_WRITE_GROUP)}
129
+
130
+
131
+ def dedupe(host: Any, root: Path, group_id: str, *, keep: str | None = None, retire_others: bool = False,
132
+ keep_all: bool = False, note: str | None = None, ignore: bool = False, unignore: bool = False,
133
+ apply: bool = False, expect: str | None = None) -> dict:
134
+ chosen = sum(bool(item) for item in (retire_others, keep_all, ignore, unignore))
135
+ if chosen != 1:
136
+ raise EntryError(_("请选择且只选择一种处置:--keep <ref> --retire-others、--keep-all --note …、--ignore、--unignore"), "usage")
137
+ if retire_others and not keep:
138
+ raise EntryError(_("--retire-others 需要 --keep <ref>"), "usage")
139
+ if keep_all and not note:
140
+ raise EntryError(_("--keep-all 需要 --note 说明原因"), "usage")
141
+ groups = dedupe_groups(host, root)
142
+ if groups is not None and group_id not in {group.get("id") for group in groups}:
143
+ return unsupported_group(group_id)
144
+ tail = ["dedupe", group_id]
145
+ if retire_others:
146
+ tail += ["--keep", keep, "--retire-others"]
147
+ elif keep_all:
148
+ tail += ["--keep-all", "--note", note or ""]
149
+ elif ignore:
150
+ tail.append("--ignore")
151
+ else:
152
+ tail.append("--unignore")
153
+ result = _forward(host, root, tail, apply=apply, expect=expect)
154
+ result["action"] = "dedupe"
155
+ return result
156
+
157
+
158
+ # ---------------------------------------------------------------- 读回(再次取 inventory,与计划逐项比对)
159
+
160
+ def _inventory_entries(host: Any, root: Path, kind: str) -> list[dict] | None:
161
+ loaded = ext.load(host, root)
162
+ if loaded["state"] != "available":
163
+ return None
164
+ items = loaded["inventory"].get("skills" if kind == "skill" else "mcps")
165
+ return [item for item in items if isinstance(item, dict)] if isinstance(items, list) else []
166
+
167
+
168
+ def _find(entries: list[dict], name: str, client: str, scope: str) -> dict | None:
169
+ return next((item for item in entries if (item.get("name"), item.get("client"), item.get("scope")) == (name, client, scope)), None)
170
+
171
+
172
+ def readback_move(host: Any, root: Path, result: dict) -> dict:
173
+ """relocate 之后:目标存在且 content_sha256 与源一致;需要退役时源不再出现在原作用域。"""
174
+ plan = result["plan"]
175
+ status = (result.get("applied") or {}).get("status")
176
+ if status == "native":
177
+ return {"ok": True, "checks": [], "note": "native"}
178
+ source, target = plan.get("source") or {}, plan.get("target") or {}
179
+ entries = _inventory_entries(host, root, plan.get("kind") or "skill")
180
+ if entries is None:
181
+ return {"ok": False, "checks": [{"id": "inventory", "ok": False, "message": _("读回时 inventory 不可用")}]}
182
+ checks = []
183
+ found = _find(entries, source.get("name", ""), target.get("client", ""), target.get("scope", ""))
184
+ checks.append({"id": "target-present", "ok": found is not None, "message": _("目标条目存在")})
185
+ if found is not None and source.get("content_sha256"):
186
+ same = found.get("content_sha256") == source["content_sha256"]
187
+ checks.append({"id": "target-digest", "ok": same, "message": _("目标内容摘要与源一致")})
188
+ if plan.get("mode") != "link" and plan.get("retire_source") and (source.get("client"), source.get("scope")) != \
189
+ (target.get("client"), target.get("scope")):
190
+ gone = _find(entries, source.get("name", ""), source.get("client", ""), source.get("scope", "")) is None
191
+ checks.append({"id": "source-retired", "ok": gone, "message": _("源条目已归档")})
192
+ return {"ok": all(check["ok"] for check in checks), "checks": checks}
193
+
194
+
195
+ def readback_dedupe(host: Any, root: Path, group_id: str, result: dict) -> dict:
196
+ plan = result["plan"]
197
+ disposition = plan.get("disposition")
198
+ groups = dedupe_groups(host, root)
199
+ if groups is None:
200
+ return {"ok": False, "checks": [{"id": "list", "ok": False, "message": _("读回时 dedupe --list 不可用")}]}
201
+ group = next((item for item in groups if item.get("id") == group_id), None)
202
+ if disposition in ("keep-all", "ignore"):
203
+ ok = bool(group and group.get("decision"))
204
+ return {"ok": ok, "checks": [{"id": "decision", "ok": ok, "message": _("决定已记录")}]}
205
+ if disposition == "unignore":
206
+ ok = not (group and group.get("decision"))
207
+ return {"ok": ok, "checks": [{"id": "decision", "ok": ok, "message": _("决定已撤销")}]}
208
+ if disposition == "retire-others" and (result.get("applied") or {}).get("status") == "applied":
209
+ retired = [item.get("ref") if isinstance(item, dict) else item for item in plan.get("retire") or []]
210
+ left = {member.get("ref") for member in (group or {}).get("members", [])}
211
+ ok = not (set(retired) & left)
212
+ return {"ok": ok, "checks": [{"id": "retired", "ok": ok, "message": _("被退役的副本不再出现")}]}
213
+ return {"ok": True, "checks": []}
214
+
215
+
216
+ def finish(provider: Any, view: str, result: dict, group_id: str | None = None) -> bool:
217
+ """应用之后读回并写进 result["readback"];返回是否需要关注(blocked、拒绝、回滚、失败、读回不一致)。"""
218
+ attention = bool(result.get("blocked")) or bool(result.get("refused"))
219
+ if result["mode"] != "apply" or result.get("refused") or result.get("unsupported"):
220
+ return attention
221
+ status = (result.get("applied") or {}).get("status")
222
+ if view != "scope" and status in ("applied", "recorded"):
223
+ result["readback"] = provider.extensions_readback(view, result, group_id)
224
+ attention = attention or not result["readback"]["ok"]
225
+ return attention or status in ("rolled-back", "failed", "refused")
226
+
227
+
228
+ # ---------------------------------------------------------------- scope:写 Project Profile 的声明
229
+
230
+ def _profile_text(profile: dict) -> str:
231
+ return json.dumps(profile, ensure_ascii=False, indent=2) + "\n"
232
+
233
+
234
+ def scope_plan(host: Any, root: Path, ref: str, effective: str, *, allow_widen: bool = False) -> dict:
235
+ parsed = REF_RE.match(ref)
236
+ if parsed is None:
237
+ raise EntryError(_("条目引用不合法:{0}").format(ref), "usage", [_("形如 skill:<名>@<客户端>:<作用域>;用 extensions list 查看")])
238
+ if effective not in ("project", "user"):
239
+ raise EntryError(_("--effective 只能是 project 或 user"), "usage")
240
+ kind, name, client, scope = parsed.group(1), parsed.group(2), parsed.group(3), parsed.group(4)
241
+ key = SCOPE_KEY[kind]
242
+ profile = read_profile(root)
243
+ capabilities = profile.get("capabilities")
244
+ blocked: list[dict] = []
245
+ if not isinstance(capabilities, dict):
246
+ blocked.append({"code": "profile-no-capabilities", "message": _("Profile 没有 capabilities 对象,不自动创建")})
247
+ capabilities = {}
248
+ current_map = capabilities.get(key) or {}
249
+ if not isinstance(current_map, dict):
250
+ blocked.append({"code": "scope-map-invalid", "message": _("Profile 的 {0} 不是对象").format(key)})
251
+ current_map = {}
252
+ default = capabilities.get("default_scope", "user")
253
+ if default not in ("user", "project"):
254
+ blocked.append({"code": "default-scope-invalid", "message": _("Profile 的 default_scope 取值非法:{0}").format(default)})
255
+ current = current_map.get(name, default)
256
+ if current not in ("user", "project"):
257
+ blocked.append({"code": "scope-value-invalid", "message": _("Profile 里 {0}.{1} 的取值非法").format(key, name)})
258
+ entries = _inventory_entries(host, root, kind)
259
+ entry = _find(entries, name, client, scope) if entries is not None else None
260
+ if entries is not None and entry is None:
261
+ blocked.append({"code": "entry-not-found", "message": _("inventory 里没有这个条目:{0}").format(ref)})
262
+ if entry is not None and entry.get("evidence") == "unknown":
263
+ blocked.append({"code": "evidence-unknown", "message": _("条目的证据为未知:只读,不写声明")})
264
+ direction = "same" if current == effective else ("narrow" if effective == "project" else "widen")
265
+ if direction == "widen" and not allow_widen:
266
+ blocked.append({"code": "widen-needs-flag", "message": _("放宽(项目→用户级)需要 --allow-widen:此后所有项目都会看到它")})
267
+ updated = json.loads(json.dumps(profile))
268
+ if direction != "same" and not blocked:
269
+ scopes = updated["capabilities"].setdefault(key, {})
270
+ scopes[name] = effective
271
+ before, after = _profile_text(profile), _profile_text(updated)
272
+ diff = "".join(difflib.unified_diff(before.splitlines(True), after.splitlines(True), PROFILE.as_posix(), PROFILE.as_posix()))
273
+ status = "blocked" if blocked else ("unchanged" if direction == "same" else "ready")
274
+ plan = {"ref": ref, "kind": kind, "name": name, "key": key, "effective": effective, "current": current,
275
+ "direction": direction, "status": status, "blocked": blocked, "profile": PROFILE.as_posix(), "diff": diff,
276
+ "snippet": {"capabilities": {key: {name: effective}}},
277
+ "steps": [{"id": "s1", "action": "backup-profile", "promise": "certain"},
278
+ {"id": "s2", "action": "write-profile-declaration", "promise": "certain"},
279
+ {"id": "s3", "action": "verify-readback", "promise": "certain"},
280
+ {"id": "s4", "action": "preview-sync", "promise": "cannot-promise"}],
281
+ "warnings": [{"code": "declaration-only", "message": _("只写声明;条目要等 sync / reconcile 预览并应用后才真正移动,客户端行为工具不承诺")}],
282
+ "next": {"sync": _("agent-pack 的 sync / reconcile 预览(不加 --apply):看这条声明会让哪些文件变化")}}
283
+ if kind == "mcp":
284
+ plan["warnings"].append({"code": "mcp-declaration-only", "message": _("MCP 的实际写入由 agent-pack 的 sync 负责;本命令不编辑任何客户端配置")})
285
+ plan["plan_digest"] = hashlib.sha256(json.dumps(
286
+ {"ref": ref, "effective": effective, "direction": direction, "before": hashlib.sha256(before.encode()).hexdigest(),
287
+ "after": hashlib.sha256(after.encode()).hexdigest(), "blocked": [item["code"] for item in blocked]},
288
+ sort_keys=True).encode()).hexdigest()
289
+ plan["_updated"] = after
290
+ return plan
291
+
292
+
293
+ def scope_apply(provider: Any, root: Path, plan: dict, recovery: str) -> dict:
294
+ """备份 Profile → 原子写入 → 读回。写前再确认 Profile 没有变过。"""
295
+ path = root / PROFILE
296
+ updated = plan["_updated"]
297
+ backup_dir = Path(recovery)
298
+ backup_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
299
+ backup = backup_dir / PROFILE.name
300
+ shutil.copy2(path, backup)
301
+ fd, tmp = tempfile.mkstemp(prefix=".project-", suffix=".json", dir=str(path.parent))
302
+ try:
303
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
304
+ handle.write(updated)
305
+ os.chmod(tmp, path.stat().st_mode & 0o777)
306
+ os.replace(tmp, path)
307
+ except OSError as exc:
308
+ Path(tmp).unlink(missing_ok=True)
309
+ return {"status": "failed", "reason": str(exc), "recovery_dir": str(backup_dir)}
310
+ ok = read_profile(root).get("capabilities", {}).get(plan["key"], {}).get(plan["name"]) == plan["effective"]
311
+ return {"status": "applied" if ok else "failed", "recovery_dir": str(backup_dir),
312
+ "restore": "cp {0} {1}".format(backup, path), "readback": {"ok": ok}}
313
+
314
+
315
+ def public_scope_plan(plan: dict) -> dict:
316
+ return {key: value for key, value in plan.items() if not key.startswith("_")}
317
+
318
+
319
+ def scope(provider: Any, ref: str, effective: str, *, allow_widen: bool = False, apply: bool = False,
320
+ expect: str | None = None) -> dict:
321
+ root = provider.root
322
+ plan = scope_plan(provider.host, root, ref, effective, allow_widen=allow_widen)
323
+ blocked = plan["status"] == "blocked"
324
+ result = {"mode": "preview", "action": "scope", "plan": public_scope_plan(plan), "applied": None, "blocked": blocked}
325
+ if not apply:
326
+ return result
327
+ if not expect:
328
+ raise EntryError(_("--apply 需要 --expect-plan <预览里的 plan_digest>"), "usage",
329
+ [_("先不加 --apply 运行一次预览,复制其中的 plan_digest")])
330
+ result["mode"] = "apply"
331
+ if plan["plan_digest"] != expect:
332
+ return {**result, "applied": {"status": "refused", "reason": "plan-changed"}, "refused": "plan-changed"}
333
+ if blocked:
334
+ return {**result, "applied": {"status": "refused", "reason": "blocked"}, "refused": "blocked"}
335
+ if plan["status"] == "unchanged":
336
+ return {**result, "applied": {"status": "unchanged"}}
337
+ from project_maintain import _recovery_dir # noqa: PLC0415 延迟导入,避免循环依赖
338
+
339
+ result["applied"] = scope_apply(provider, root, plan, _recovery_dir(provider, "scope"))
340
+ return result
341
+
342
+
343
+ # ---------------------------------------------------------------- 文字渲染
344
+
345
+ PROMISE_LABEL = {"certain": N_("确定"), "best-effort": N_("尽力而为(需在客户端里确认)"), "cannot-promise": N_("无法承诺(只保证文件改动,不保证客户端行为)")}
346
+ DIRECTION_LABEL = {"narrow": N_("收窄"), "same": N_("不变"), "widen": N_("放宽:此后所有项目都会看到它")}
347
+ APPLIED_LABEL = {"applied": N_("已应用"), "native": N_("无需写入(客户端已原生加载)"), "manual-only": N_("只给手工步骤,没有写入"),
348
+ "rolled-back": N_("失败,已回滚"), "refused": N_("已拒绝,没有写入"), "failed": N_("失败"),
349
+ "unchanged": N_("没有变化"), "recorded": N_("已记录")}
350
+ REFUSED_REASON = {"plan-changed": N_("预览之后内容有变化(摘要不一致):请重新预览,再用新的 plan_digest 确认"),
351
+ "blocked": N_("计划有 blocked 项,不可执行")}
352
+
353
+
354
+ def _line_items(items: Any, key: str = "message") -> list[str]:
355
+ out = []
356
+ for item in items or []:
357
+ out.append(f" - {item.get(key) or item.get('code')}" if isinstance(item, dict) else f" - {item}")
358
+ return out
359
+
360
+
361
+ def render_plan(plan: dict) -> list[str]:
362
+ lines = [S.bold(plan.get("ref") or plan.get("group") or "")]
363
+ direction = plan.get("direction")
364
+ if direction:
365
+ label = _(DIRECTION_LABEL.get(direction, direction))
366
+ lines.append(_("方向:{0}").format(S.red(label) if direction == "widen" else label))
367
+ if plan.get("status"):
368
+ lines.append(_("状态:{0}").format(plan["status"]))
369
+ for step in plan.get("steps") or []:
370
+ lines.append(f" {step.get('id', '')} {step.get('action', '')} [{_(PROMISE_LABEL.get(step.get('promise'), str(step.get('promise'))))}]")
371
+ if plan.get("blocked"):
372
+ lines += [S.red(_("blocked(不可执行):"))] + _line_items(plan["blocked"])
373
+ if plan.get("warnings"):
374
+ lines += [S.yellow(_("提示:"))] + _line_items(plan["warnings"])
375
+ if plan.get("confirmations"):
376
+ lines += [S.yellow(_("需要确认:"))] + [" - " + _("{0}({1})").format(item.get("text"), item.get("flag")) if isinstance(item, dict) else f" - {item}"
377
+ for item in plan["confirmations"]]
378
+ for item in plan.get("manual") or []:
379
+ lines.append(" $ " + str(item.get("command") if isinstance(item, dict) else item))
380
+ if plan.get("diff"):
381
+ lines += [_("Profile 将发生的改动:"), *plan["diff"].rstrip("\n").splitlines()]
382
+ if plan.get("snippet"):
383
+ lines += [_("可粘贴的片段(合并进 Profile):"), *json.dumps(plan["snippet"], ensure_ascii=False, indent=2).splitlines()]
384
+ nxt = plan.get("next")
385
+ if isinstance(nxt, dict):
386
+ for key, value in nxt.items():
387
+ if key == "apply":
388
+ continue
389
+ lines.append(S.dim(_("下一步:{0}").format(value)))
390
+ if plan.get("plan_digest"):
391
+ lines.append(_("plan_digest:{0}").format(plan["plan_digest"]))
392
+ return lines
393
+
394
+
395
+ def render_action(result: dict) -> list[str]:
396
+ if result.get("unsupported"):
397
+ return [S.yellow(result["message"])]
398
+ lines = render_plan(result["plan"])
399
+ applied = result.get("applied")
400
+ if result["mode"] == "preview":
401
+ lines.append(S.dim(_("以上为预览,没有写入。确认后加 --apply --expect-plan <plan_digest>。")))
402
+ return lines
403
+ status = (applied or {}).get("status", "failed")
404
+ lines.append(S.bold(_("结果:{0}").format(_(APPLIED_LABEL.get(status, status)))))
405
+ if result.get("refused"):
406
+ lines.append(S.yellow(_(REFUSED_REASON.get(result["refused"], result["refused"]))))
407
+ for key in ("recovery_dir", "restore"):
408
+ if (applied or {}).get(key):
409
+ value = applied[key]
410
+ lines.append(f" {key}: " + ("; ".join(map(str, value)) if isinstance(value, list) else str(value)))
411
+ readback = result.get("readback")
412
+ if readback:
413
+ lines.append(_("读回:{0}").format(_("一致") if readback["ok"] else S.red(_("读回失败"))))
414
+ lines += [f" {'✓' if item['ok'] else '✗'} {item['message']}" for item in readback.get("checks", [])]
415
+ return lines