@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,447 @@
1
+ #!/usr/bin/env python3
2
+ """MCP entry moves and retirements for Claude (``agenthelm relocate`` mcp refs, later ``dedupe``).
3
+
4
+ The one place that edits MCP entries in ``~/.claude.json`` (user level and the ``local`` section under the project's
5
+ path) and the project's ``.mcp.json``. It reuses the readers and helpers of ``agent_pack_claude`` (the same ones the
6
+ Claude sync uses), writes atomically, restores every touched file byte for byte on a failure, and never prints a value:
7
+ plans, outputs and the metadata this module writes carry names, scopes, paths and digests only. The only files that hold
8
+ the user's own values are the recovery fragments (``mcp/<name>@<scope>.json``) and the byte-exact backups
9
+ (``claude.json.before`` / ``project-mcp.json.before``), all mode 0600.
10
+
11
+ Only entries the project's agent-pack state owns are ever removed by the tool; any other entry gets the official manual
12
+ command and a backup reminder (``MANUAL_REMOVE`` / ``MANUAL_BACKUP``), flagged as not archivable by the tool.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import copy
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import shlex
22
+ import stat
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ RUNTIME_DIR = Path(__file__).resolve().parent
28
+ if str(RUNTIME_DIR) not in sys.path:
29
+ sys.path.insert(0, str(RUNTIME_DIR))
30
+ import agent_pack_config as core # noqa: E402
31
+ import agent_pack_ext_common as ext # noqa: E402
32
+ import agent_pack_inventory as inv # noqa: E402
33
+ from i18n_agent_pack import _, N_ # noqa: E402
34
+
35
+ # Writers as data: the clients whose MCP stores this module knows how to edit (the Claude layout). Whether a client
36
+ # supports project-level writes is decided only by ``agent_pack_config.project_write_supported``.
37
+ MCP_WRITERS = {"claude": ("user", "local", "project")}
38
+ RANK = {"local": 0, "project": 0, "user": 1} # breadth: a higher rank widens; local <-> project is lateral
39
+ STORE_PATH = {"user": "~/.claude.json", "local": "~/.claude.json#projects[" + inv.PROJECT + "]",
40
+ "project": inv.PROJECT + "/.mcp.json"}
41
+ PLACE = {"local": "project:local", "project": "project:file"}
42
+ MANUAL_REMOVE = {"claude": "claude mcp remove --scope {scope} {name}"}
43
+ MANUAL_BACKUP = {"claude": "cp ~/.claude.json ~/.claude.json.bak"}
44
+ WIDEN_WARNING = N_("放宽:这个 MCP 之后在所有项目里可见")
45
+
46
+ ACTION_TEXT = {
47
+ "write-mcp-entry": N_("写入 {to}:条目 {name}(原样复制,不显示任何值)"),
48
+ "verify-mcp-readback": N_("读回校验 {to}:条目 {name} 与源逐字段一致"),
49
+ "retire-mcp-entry": N_("校验通过后从 {from} 移除源条目 {name};原片段存入恢复目录 mcp/(0600),配置文件先整份逐字节备份"),
50
+ "update-state": N_("更新 agent-pack 的归属记录:{name} → {place}"),
51
+ "manual-remove-mcp": N_("{ref}:不可由工具归档,见下面的手工命令"),
52
+ }
53
+
54
+
55
+ def entry_hash(entry: Any) -> str:
56
+ """The hash the Claude sync records for an entry (``state`` ownership), so both agree."""
57
+ return hashlib.sha256(json.dumps(entry, sort_keys=True).encode("utf-8")).hexdigest()
58
+
59
+
60
+ def _short(entry: Any) -> str:
61
+ return entry_hash(entry)[:16]
62
+
63
+
64
+ def _claude():
65
+ import agent_pack_claude # noqa: PLC0415 - shipped next to this file
66
+ return agent_pack_claude
67
+
68
+
69
+ # ------------------------------------------------------------------ reading
70
+
71
+ def _root_and_package(project: Path) -> tuple[Path, str | None, Any]:
72
+ """(project root, package name or ``None``, layout or ``None``). A project without a usable profile is fine."""
73
+ try:
74
+ layout = core.load_project_layout(project)
75
+ return layout.root, core._package_name(layout.root), layout
76
+ except core.AgentPackError:
77
+ return project, None, None
78
+
79
+
80
+ def read_entry(home: Path, root: Path, scope: str, name: str) -> tuple[Any, str | None]:
81
+ """(raw entry or ``None``, problem). ``problem`` is a short code when the store cannot be read as expected."""
82
+ claude = _claude()
83
+ try:
84
+ if scope == "project":
85
+ servers, problem = claude._read_project_file(claude._project_file(root))
86
+ return servers.get(name), problem
87
+ config = claude._read_config(home)
88
+ if scope == "user":
89
+ return (config.get("mcpServers") or {}).get(name), None
90
+ _key, servers, problem = claude.local_section(config, root)
91
+ return servers.get(name), problem
92
+ except core.AgentPackError:
93
+ return None, "config-unreadable"
94
+
95
+
96
+ def ownership(home: Path, package: str | None, scope: str, name: str) -> dict:
97
+ """Whether the project's agent-pack state owns the entry at that scope, and the hash it recorded.
98
+
99
+ Only the state of this project's package counts; an entry owned by another package's state (or by none) is unmanaged.
100
+ """
101
+ claude = _claude()
102
+ state = claude._read_state(home, package) if package else {}
103
+ if scope == "user":
104
+ mcps = state.get("mcps") if isinstance(state.get("mcps"), dict) else {}
105
+ recorded = mcps.get(name)
106
+ places = claude._state_scopes(state, "mcps")
107
+ owned = name in mcps and places.get(name, "user") == "user"
108
+ return {"managed": owned, "recorded_hash": recorded if owned else None, "package": package}
109
+ owned = claude._state_scopes(state, "mcps").get(name) == PLACE[scope]
110
+ hashes = claude._project_hashes(state)
111
+ return {"managed": owned, "recorded_hash": hashes.get(name) if owned else None, "package": package}
112
+
113
+
114
+ # ------------------------------------------------------------------ plan
115
+
116
+ def manual_entry(item_ref: str, client: str, scope: str, store: str, name: str) -> dict:
117
+ entry: dict[str, Any] = {"ref": item_ref, "client": client, "scope": scope, "store": store, "name": name,
118
+ "not_archivable_by_tool": True, "promise": "cannot-promise"}
119
+ if client in MANUAL_REMOVE:
120
+ entry["command"] = MANUAL_REMOVE[client].format(scope=scope, name=shlex.quote(name))
121
+ entry["backup"] = MANUAL_BACKUP[client]
122
+ else:
123
+ entry["instruction"] = _("手工删除 {0} 里名为 {1} 的 MCP 条目(先自己备份该文件)").format(store, name)
124
+ return entry
125
+
126
+
127
+ def _finish(plan: dict, status: str | None = None) -> dict:
128
+ if status:
129
+ plan["status"] = status
130
+ plan["plan_digest"] = ext.plan_digest(plan)
131
+ return plan
132
+
133
+
134
+ def parse_target(text: str) -> tuple[str, str] | None:
135
+ client, colon, scope = text.partition(":")
136
+ return (client, scope) if colon and scope in ("user", "local", "project") else None
137
+
138
+
139
+ def build_plan(home: Path, project: Path, ref: str, to: str, allow_widen: bool = False, keep_source: bool = False,
140
+ recovery_override: Path | None = None, mode: str = "copy") -> tuple[dict, dict]:
141
+ """The plan of moving one MCP entry between Claude scopes (JSON-safe, never a value) and the private apply context."""
142
+ home = home.expanduser().resolve()
143
+ project = project.expanduser().resolve()
144
+ root, package, layout = _root_and_package(project)
145
+ plan: dict[str, Any] = {
146
+ "ref": ref, "kind": "mcp", "source": None, "target": None, "mode": "copy", "retire_source": False,
147
+ "direction": None, "status": "blocked", "steps": [], "blocked": [], "warnings": [], "confirmations": [],
148
+ "manual": [], "recovery_base": ext.display(ext.recovery_base(home, recovery_override), home, root),
149
+ }
150
+ ctx: dict[str, Any] = {}
151
+ blocks = plan["blocked"]
152
+ from agent_pack_relocate import parse_ref # noqa: PLC0415 - one ref grammar for both kinds
153
+ parsed = parse_ref(ref)
154
+ target = parse_target(to)
155
+ if parsed is None or parsed[0] != "mcp":
156
+ blocks.append(ext.blocked("invalid-ref", _("引用格式应为 mcp:<名>@<客户端>:<作用域>")))
157
+ if target is None:
158
+ blocks.append(ext.blocked("invalid-target", _("MCP 的目标格式应为 <客户端>:<作用域>,作用域为 user|local|project")))
159
+ if blocks:
160
+ return _finish(plan), ctx
161
+ assert parsed is not None and target is not None
162
+ _kind, name, src_client, src_scope = parsed
163
+ target_client, target_scope = target
164
+
165
+ report = inv.observe(home, root, None, "mcp", "all")
166
+ item = next((entry for entry in report["mcps"] if entry["ref"] == ref), None)
167
+ if item is None:
168
+ near = sorted(entry["ref"] for entry in report["mcps"] if entry["name"] == name)
169
+ blocks.append(ext.blocked("source-not-found", _("没有找到这个 MCP 引用"), candidates=near))
170
+ return _finish(plan), ctx
171
+ store = STORE_PATH.get(item["scope"], item["store"])
172
+ plan["source"] = {"ref": ref, "name": name, "client": item["client"], "scope": item["scope"], "store": store,
173
+ "path": store, "managed": False}
174
+ plan["target"] = {"client": target_client, "scope": target_scope, "store": STORE_PATH[target_scope],
175
+ "path": STORE_PATH[target_scope]}
176
+ direction = "same" if RANK[item["scope"]] == RANK[target_scope] and item["scope"] != target_scope else (
177
+ "widen" if RANK[target_scope] > RANK[item["scope"]] else "narrow")
178
+ plan["direction"] = direction
179
+
180
+ if src_client != target_client:
181
+ blocks.append(ext.blocked("cross-client-unsupported", _("本版本只在同一客户端的作用域之间迁移 MCP;跨客户端用 transfer 或 sync")))
182
+ for client in dict.fromkeys((src_client, target_client)):
183
+ if client not in MCP_WRITERS:
184
+ blocks.append(ext.blocked("mcp-client-unsupported", _("{0} 的 MCP 配置本工具不写入").format(client), client=client))
185
+ elif (item["scope"] != "user" or target_scope != "user") and not core.project_write_supported(client):
186
+ blocks.append(ext.blocked("project-write-unsupported", _("{0} 不支持项目级写入").format(client), client=client))
187
+ if mode != "copy":
188
+ blocks.append(ext.blocked("link-unsupported", _("MCP 条目只能复制,不支持 --mode link")))
189
+ if item["scope"] == target_scope:
190
+ blocks.append(ext.blocked("target-is-source", _("目标作用域就是源本身")))
191
+ if not root.is_dir():
192
+ blocks.append(ext.blocked("project-not-found", _("需要项目目录,请用 --project 指定")))
193
+ if item["evidence"] != "file":
194
+ blocks.append(ext.blocked("source-not-file-evidence", _("源条目没有文件级证据,只读,不能迁移")))
195
+ if direction == "widen" and not allow_widen:
196
+ blocks.append(ext.blocked("widen-needs-flag", _("项目级 → 用户级会放宽作用域(所有项目都会看到),需要 --allow-widen")))
197
+ if direction == "widen":
198
+ plan["warnings"].append(ext.warning("widen", WIDEN_WARNING))
199
+ if blocks:
200
+ return _finish(plan), ctx
201
+
202
+ raw, problem = read_entry(home, root, item["scope"], name)
203
+ if raw is None or problem or not isinstance(raw, dict):
204
+ blocks.append(ext.blocked("source-unreadable", _("读不到源条目(配置文件结构不被识别或已变化),不迁移")))
205
+ return _finish(plan), ctx
206
+ owner = ownership(home, package, item["scope"], name)
207
+ current_hash = entry_hash(raw)
208
+ plan["source"].update(managed=owner["managed"], entry_digest=current_hash[:16])
209
+ if owner["managed"] and owner["recorded_hash"] and owner["recorded_hash"] != current_hash:
210
+ plan["warnings"].append(ext.warning("modified-since-sync", _("源条目自上次同步后被改过:仍按受管处理,原片段会完整存入恢复目录")))
211
+
212
+ # target side
213
+ existing, target_problem = read_entry(home, root, target_scope, name)
214
+ claude = _claude()
215
+ if target_problem:
216
+ blocks.append(ext.blocked("target-unreadable", _("目标存储的结构不被识别,不写入"), problem=target_problem))
217
+ elif existing is not None:
218
+ relation = "identical" if entry_hash(existing) == current_hash else "different"
219
+ blocks.append(ext.blocked("target-exists-" + relation, _("目标已存在同名条目(内容{0}),不覆盖、不改名、不合并").format(
220
+ _("相同") if relation == "identical" else _("不同")), target=plan["target"]["path"]))
221
+ elif not claude._writable(core._claude_user_config(home) if target_scope != "project" else claude._project_file(root)):
222
+ blocks.append(ext.blocked("target-not-writable", _("目标文件不可写")))
223
+ if target_scope == "project":
224
+ if item.get("has_inline_secret"):
225
+ blocks.append(ext.blocked("inline-secret-in-project-file", _("条目含内联密钥值,不能写入项目文件 .mcp.json;请先改成 ${VAR} 引用(工具不改写条目)")))
226
+ fields = claude.machine_specific(raw, home, root)
227
+ if fields:
228
+ blocks.append(ext.blocked("machine-specific-in-project-file", _("条目含本机路径({0}),不能写入项目文件 .mcp.json").format(", ".join(fields)), fields=fields))
229
+ plan["confirmations"].append({
230
+ "id": "project-content", "flag": "--confirm-project-content",
231
+ "text": _("将进入项目文件 .mcp.json(可能被提交到版本库);请自行确认其内容适合共享")})
232
+ if layout is not None and package:
233
+ declared = core.declared_scope(layout, "mcp", name)
234
+ landing = "user" if target_scope == "user" else "project"
235
+ explicit = name in layout.mcp_scope or layout.default_scope != "user" # only a declaration the project made
236
+ if explicit and declared != landing:
237
+ plan["warnings"].append(ext.warning("declaration-differs", _("项目 Profile 把 {0} 声明为 {1} 级:下次 sync 会按声明处理它,请同步更新声明").format(name, declared)))
238
+
239
+ plan["retire_source"] = owner["managed"] and not keep_source
240
+ if not blocks:
241
+ steps = plan["steps"]
242
+ steps.append(ext.step("s1", "create-recovery-dir", "certain", to=plan["recovery_base"]))
243
+ steps.append(ext.step("s2", "write-mcp-entry", "certain", to=plan["target"]["path"], name=name))
244
+ steps.append(ext.step("s3", "verify-mcp-readback", "certain", to=plan["target"]["path"], name=name))
245
+ if plan["retire_source"]:
246
+ steps.append(ext.step("s4", "retire-mcp-entry", "certain", name=name, **{"from": plan["source"]["path"]}))
247
+ steps.append(ext.step("s5", "update-state", "certain", name=name,
248
+ place="user" if target_scope == "user" else PLACE[target_scope]))
249
+ elif not owner["managed"]:
250
+ plan["manual"].append(manual_entry(ref, item["client"], item["scope"], store, name))
251
+ steps.append(ext.step("s4", "manual-remove-mcp", "cannot-promise", ref=ref))
252
+ plan["warnings"].append(ext.warning("mcp-not-archivable", _("未受管条目不可由工具归档:只复制到新位置,原位置不动;要移除请按下面的手工命令(先自己备份)")))
253
+ else:
254
+ steps.append(ext.step("s4", "keep-source", "certain", **{"from": plan["source"]["path"]}))
255
+ steps.append(ext.step(f"s{len(steps) + 1}", "confirm-in-client", "best-effort", client=target_client))
256
+ plan["status"] = "blocked" if blocks else "ready"
257
+ ctx.update(home=home, project=root, recovery_override=recovery_override, entry=raw, package=package,
258
+ source_scope=item["scope"], target_scope=target_scope, name=name)
259
+ return _finish(plan), ctx
260
+
261
+
262
+ # ------------------------------------------------------------------ writing
263
+
264
+ def _write_state(path: Path, data: dict) -> None:
265
+ core._write_json_atomic(path, data, mode=0o600)
266
+
267
+
268
+ def state_after(state: dict, name: str, from_scope: str, to_scope: str | None, new_hash: str | None) -> dict:
269
+ """The agent-pack state with ``name`` moved from ``from_scope`` to ``to_scope`` (or dropped when ``None``).
270
+
271
+ The pre-existing ``mcps`` key stays user-level ownership only (an older runtime reads it that way); where each
272
+ entry sits is recorded only under ``scopes``, completed from that key when it was absent.
273
+ """
274
+ new = copy.deepcopy(state)
275
+ mcps = new.get("mcps") if isinstance(new.get("mcps"), dict) else {}
276
+ scopes = new.get("scopes") if isinstance(new.get("scopes"), dict) else {}
277
+ places = scopes.get("mcps") if isinstance(scopes.get("mcps"), dict) else {}
278
+ hashes = scopes.get("project_hashes") if isinstance(scopes.get("project_hashes"), dict) else {}
279
+ for known in mcps:
280
+ places.setdefault(known, "user")
281
+ mcps.pop(name, None)
282
+ places.pop(name, None)
283
+ hashes.pop(name, None)
284
+ if to_scope == "user":
285
+ mcps[name] = new_hash
286
+ places[name] = "user"
287
+ elif to_scope is not None:
288
+ places[name] = PLACE[to_scope]
289
+ hashes[name] = new_hash
290
+ scopes.setdefault("skills", {})
291
+ scopes.update(mcps=places, project_hashes=hashes)
292
+ new.update(mcps=mcps, scopes=scopes)
293
+ return new
294
+
295
+
296
+ def _fragment_name(name: str, scope: str) -> str:
297
+ return f"{name}@{scope}.json"
298
+
299
+
300
+ def apply_edits(home: Path, root: Path, recovery: Path, edits: list[dict], state_package: str | None = None,
301
+ state_change: dict | list[dict] | None = None) -> dict:
302
+ """Apply ``edits`` (``{"op": "set"|"drop", "scope", "name", "entry"?}``) and the optional state change in one
303
+ transaction. Config and project-file writes are atomic; any failure puts every touched file back byte for byte and
304
+ re-raises. Returns the recovery fragment paths of the dropped entries."""
305
+ claude = _claude()
306
+ config_path = core._claude_user_config(home)
307
+ project_file = claude._project_file(root)
308
+ state_path = claude.state_path(home, state_package) if state_package else None
309
+ snapshots: dict[Path, tuple[bytes | None, int]] = {}
310
+ for path in (config_path, project_file, state_path):
311
+ if path is not None:
312
+ snapshots[path] = (path.read_bytes() if path.is_file() else None,
313
+ stat.S_IMODE(path.stat().st_mode) if path.is_file() else 0o600)
314
+ config = claude._read_config(home)
315
+ config_before = json.loads(json.dumps(config))
316
+ fragments: list[Path] = []
317
+ file_data: dict[str, Any] | None = None
318
+ touched: list[Path] = []
319
+ try:
320
+ for edit in edits:
321
+ if edit["op"] == "drop":
322
+ path = recovery / "mcp" / _fragment_name(edit["name"], edit["scope"])
323
+ ext.write_private_json(path, {"schema_version": ext.SCHEMA_VERSION, "name": edit["name"],
324
+ "scope": edit["scope"], "store": STORE_PATH[edit["scope"]],
325
+ "entry": edit["entry"]})
326
+ os.chmod(path, 0o600)
327
+ os.chmod(path.parent, 0o700)
328
+ fragments.append(path)
329
+ if any(e["scope"] != "project" for e in edits):
330
+ _backup(recovery, "claude.json.before", snapshots[config_path][0])
331
+ if any(e["scope"] == "project" for e in edits):
332
+ _backup(recovery, "project-mcp.json.before", snapshots[project_file][0])
333
+ file_data = core._read_json(project_file) if snapshots[project_file][0] is not None else {}
334
+ for edit in edits:
335
+ servers = _servers_for(claude, config, file_data, edit["scope"], root, create=edit["op"] == "set")
336
+ if edit["op"] == "set":
337
+ servers[edit["name"]] = edit["entry"]
338
+ elif servers is not None:
339
+ servers.pop(edit["name"], None)
340
+ if config != config_before:
341
+ touched.append(config_path)
342
+ core._write_json_atomic(config_path, config, mode=snapshots[config_path][1] if snapshots[config_path][0] else 0o600)
343
+ if file_data is not None:
344
+ touched.append(project_file)
345
+ core._write_json_atomic(project_file, file_data, mode=snapshots[project_file][1] if snapshots[project_file][0] else 0o644)
346
+ if state_package and state_change is not None and state_path is not None:
347
+ after = claude._read_state(home, state_package)
348
+ for change in ([state_change] if isinstance(state_change, dict) else state_change):
349
+ after = state_after(after, **change)
350
+ touched.append(state_path)
351
+ _write_state(state_path, after | {"updated_at": ext_stamp()})
352
+ _verify(home, root, edits)
353
+ except Exception:
354
+ for path in reversed(touched):
355
+ data, mode = snapshots[path]
356
+ claude._restore_bytes(path, data, mode)
357
+ raise
358
+ return {"fragments": fragments}
359
+
360
+
361
+ def ext_stamp() -> str:
362
+ from datetime import UTC, datetime # noqa: PLC0415
363
+ return datetime.now(UTC).strftime("%Y%m%dT%H%M%S.%fZ")
364
+
365
+
366
+ def _backup(recovery: Path, name: str, data: bytes | None) -> None:
367
+ if data is None:
368
+ return
369
+ path = recovery / name
370
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
371
+ with os.fdopen(descriptor, "wb") as handle:
372
+ handle.write(data)
373
+
374
+
375
+ def _servers_for(claude, config: dict, file_data: dict | None, scope: str, root: Path, create: bool) -> dict | None:
376
+ if scope == "user":
377
+ return config.setdefault("mcpServers", {}) if create else config.get("mcpServers", {})
378
+ if scope == "project":
379
+ assert file_data is not None
380
+ return file_data.setdefault("mcpServers", {})
381
+ key = claude.local_section(config, root)[0]
382
+ if key is None:
383
+ raise core.AgentPackError("claude local MCP store changed shape since the preview")
384
+ if not create and key not in (config.get("projects") or {}):
385
+ return {}
386
+ return config.setdefault("projects", {}).setdefault(key, {}).setdefault("mcpServers", {})
387
+
388
+
389
+ def _verify(home: Path, root: Path, edits: list[dict]) -> None:
390
+ for edit in edits:
391
+ found, problem = read_entry(home, root, edit["scope"], edit["name"])
392
+ if problem:
393
+ raise ext.ExtError("read-back failed: " + problem)
394
+ if edit["op"] == "set" and found != edit["entry"]:
395
+ raise ext.ExtError("read-back mismatch")
396
+ if edit["op"] == "drop" and found is not None:
397
+ raise ext.ExtError("entry still present after removal")
398
+
399
+
400
+ def restore_lines(recovery: Path, home: Path, fragments: list[Path], edits: list[dict]) -> list[str]:
401
+ lines = []
402
+ for edit, fragment in zip((e for e in edits if e["op"] == "drop"), fragments):
403
+ lines.append(_("把 {0} 里的 entry 手工放回 {1} 的 mcpServers.{2};或整份还原 {3}(逐字节备份,会丢掉之后的其他改动)").format(
404
+ ext.display(fragment, home, None), STORE_PATH[edit["scope"]], edit["name"],
405
+ ext.display(recovery / ("project-mcp.json.before" if edit["scope"] == "project" else "claude.json.before"), home, None)))
406
+ return lines
407
+
408
+
409
+ def retire_group(home: Path, root: Path, recovery: Path, package: str | None, items: list[dict]) -> dict:
410
+ """Remove managed entries (``{"scope", "name", "entry"}``) in one transaction (``dedupe --retire-others``): fragments
411
+ and byte-exact backups first, atomic edits, state records dropped, byte-exact rollback on failure."""
412
+ edits = [{"op": "drop", **item} for item in items]
413
+ changes = [{"name": item["name"], "from_scope": item["scope"], "to_scope": None, "new_hash": None} for item in items]
414
+ result = apply_edits(home, root, recovery, edits, package, changes)
415
+ return {"fragments": result["fragments"], "edits": edits}
416
+
417
+
418
+ def apply_plan(plan: dict, ctx: dict, confirm_project: bool) -> dict:
419
+ """Execute a ready MCP move plan; failures roll back and are reported, never raised."""
420
+ home, root = ctx["home"], ctx["project"]
421
+ if plan["confirmations"] and not confirm_project:
422
+ return {"status": "refused", "reason": "project-content-unconfirmed", "written": False,
423
+ "message": _("需要确认:{0}(加 --confirm-project-content)").format(plan["confirmations"][0]["text"])}
424
+ recovery: Path | None = None
425
+ name, source_scope, target_scope = ctx["name"], ctx["source_scope"], ctx["target_scope"]
426
+ edits = [{"op": "set", "scope": target_scope, "name": name, "entry": ctx["entry"]}]
427
+ state_change = None
428
+ if plan["retire_source"]:
429
+ edits.append({"op": "drop", "scope": source_scope, "name": name, "entry": ctx["entry"]})
430
+ state_change = {"name": name, "from_scope": source_scope, "to_scope": target_scope, "new_hash": entry_hash(ctx["entry"])}
431
+ try:
432
+ recovery = ext.new_recovery_dir(ext.recovery_base(home, ctx["recovery_override"]), f"relocate-mcp-{name}")
433
+ ext.write_private_json(recovery / "relocate.json", {
434
+ "schema_version": ext.SCHEMA_VERSION, "ref": plan["ref"], "source": plan["source"]["path"],
435
+ "target": plan["target"]["path"], "retire_source": plan["retire_source"], "plan_digest": plan["plan_digest"]})
436
+ result = apply_edits(home, root, recovery, edits, ctx["package"] if plan["retire_source"] else None, state_change)
437
+ except Exception as exc: # noqa: BLE001 - every failure rolls back the same way
438
+ return {"status": "rolled-back", "written": False, "reason": type(exc).__name__,
439
+ "message": _("失败,已回滚:{0}").format(str(exc)),
440
+ "recovery_dir": ext.display(recovery, home, root) if recovery else None}
441
+ applied: dict[str, Any] = {
442
+ "status": "applied", "written": True, "mode": "copy", "target": plan["target"]["path"],
443
+ "readback": {"ok": True}, "recovery_dir": ext.display(recovery, home, root),
444
+ "retired": plan["retire_source"], "restore": [], "manual": plan["manual"]}
445
+ if plan["retire_source"]:
446
+ applied["restore"] = restore_lines(recovery, home, result["fragments"], edits)
447
+ return applied
@@ -24,13 +24,15 @@ import time
24
24
  from pathlib import Path
25
25
  from typing import Any
26
26
 
27
+ import agent_pack_clients as client_registry
27
28
  from nudge_text import LANGUAGES, resolve_language, session_flag, text as say
28
29
 
29
30
  ENV_DISABLE = "AGENTHELM_NO_NUDGE"
30
31
  ENV_DEBUG = "AGENTHELM_NUDGE_DEBUG"
31
- CLIENTS = ("claude", "codex", "cursor")
32
+ CLIENTS = client_registry.default_ids()
32
33
  EVENTS = ("session-start", "prompt-submit", "stop")
33
34
  STOP_MODES = ("off", "on-completion", "always")
35
+ CONFIRM_MODES = ("ask", "digest", "quiet")
34
36
  OURS = re.compile(r"agenthelm\.py['\"]?\s+nudge\s+hook")
35
37
  SUBPROCESS_TIMEOUT = 5
36
38
  MAX_PROMPT_CHARS = 1500
@@ -52,6 +54,8 @@ DEFAULTS: dict[str, Any] = {
52
54
  "pending_threshold": 5,
53
55
  "stale_days": 7,
54
56
  "max_prompts_per_session": 1,
57
+ "confirm": "ask",
58
+ "prompt_cooldown_hours": 24,
55
59
  "capture_hints_per_session": 3,
56
60
  "trial_expire_days": 30,
57
61
  "reminder_repeat_hours": 24,
@@ -103,6 +107,16 @@ def merge_config(*layers: Any) -> tuple[dict[str, Any], list[str]]:
103
107
  config[key] = {**config[key], **modes}
104
108
  else:
105
109
  problems.append(("warn_stop", {"label": label, "modes": "/".join(STOP_MODES)}))
110
+ elif key == "confirm":
111
+ if value in CONFIRM_MODES:
112
+ config[key] = value
113
+ else:
114
+ problems.append(("warn_confirm", {"label": label, "modes": "/".join(CONFIRM_MODES)}))
115
+ elif key == "prompt_cooldown_hours":
116
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
117
+ config[key] = value
118
+ else:
119
+ problems.append(("warn_cooldown", {"label": label}))
106
120
  elif key in ("keywords", "completion_keywords"):
107
121
  parsed = _words(value, [])
108
122
  if parsed:
@@ -313,7 +327,9 @@ def session_start(host: Any, env: Any, payload: dict, client: str, root: Path, c
313
327
  source = str(payload.get("source") or "startup")
314
328
  if (root / ".opinion" / "inbox.json").is_file():
315
329
  run_manager(manager, "inbox", "expire", "--project", str(root), "--days", str(config["trial_expire_days"]), lang=config["lang"])
316
- brief = run_manager(manager, "inbox", "brief", "--project", str(root), *(["--session", session] if session else []), lang=config["lang"])
330
+ brief = run_manager(manager, "inbox", "brief", "--project", str(root), *(["--session", session] if session else []),
331
+ "--mode", config["confirm"], "--cooldown-hours", str(config["prompt_cooldown_hours"]),
332
+ "--max-per-session", str(config["max_prompts_per_session"]), lang=config["lang"])
317
333
  context = brief["text"] if brief else None
318
334
  if source == "compact":
319
335
  return render(client, "session-start", context=context)
@@ -373,7 +389,7 @@ def prompt_submit(host: Any, env: Any, payload: dict, client: str, root: Path, c
373
389
 
374
390
  def stop(host: Any, env: Any, payload: dict, client: str, root: Path, config: dict) -> dict | None:
375
391
  mode = config["stop_prompt"].get(client, "off")
376
- if mode == "off" or payload.get("stop_hook_active") or payload.get("loop_count"):
392
+ if mode == "off" or config["confirm"] != "ask" or payload.get("stop_hook_active") or payload.get("loop_count"):
377
393
  return None
378
394
  if client == "cursor" and payload.get("status") not in (None, "completed"):
379
395
  return None
@@ -395,10 +411,18 @@ def stop(host: Any, env: Any, payload: dict, client: str, root: Path, config: di
395
411
  identifiers = summary["session_unpresented"]
396
412
  if not identifiers:
397
413
  return None
414
+ gate = ["inbox", "gate", "--project", str(root), "--session", session, "--cooldown-hours", str(config["prompt_cooldown_hours"]),
415
+ "--max-per-session", str(config["max_prompts_per_session"])]
416
+ peek = run_manager(manager, *gate, "--peek", lang=config["lang"])
417
+ if not peek or peek.get("allowed") is not True:
418
+ return None # 冷却中;gate 状态损坏时 run_manager 返回 None,同样保持静默
398
419
  listing = run_manager(manager, "inbox", "list", "--project", str(root), "--session", session, "--unpresented",
399
420
  "--status", "pending", "--output", "markdown", lang=config["lang"])
400
421
  if not listing:
401
422
  return None
423
+ recorded = run_manager(manager, *gate, lang=config["lang"]) # 真要发请求才记账
424
+ if not recorded or recorded.get("allowed") is not True:
425
+ return None
402
426
  run_manager(manager, "inbox", "present", *identifiers, "--project", str(root), lang=config["lang"])
403
427
  record["stop_prompts"] += 1
404
428
  save_state(host, env, state)
@@ -645,7 +669,8 @@ def main(argv: list[str], host: Any) -> int:
645
669
  say("status_switch", lang, state=state),
646
670
  say("status_thresholds", lang, pending=config["pending_threshold"], stale=config["stale_days"],
647
671
  prompts=config["max_prompts_per_session"], expire=config["trial_expire_days"],
648
- stop=config["stop_prompt"], language=f"{config['language']} ({lang})")]
672
+ stop=config["stop_prompt"], language=f"{config['language']} ({lang})"),
673
+ say("status_confirm", lang, mode=config["confirm"], hours=config["prompt_cooldown_hours"])]
649
674
  if result.get("summary"):
650
675
  summary = result["summary"]
651
676
  lines.append(say("status_current", lang, pending=summary["pending"], trial=summary["trial"], days=int(summary["oldest_days"])))