@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,582 @@
1
+ """opinion_manager.py migrate:把用户现有的 Profile(2.0 / 2.1)迁移到带标签声明的 2.2,契约见 docs/design/opinion-progressive-loading.md 第 7 节。
2
+
3
+ 默认只读预览(零写入,失败路径也一样);``--apply --confirm <指纹>`` 才写入:先备份到 ``.opinion/backups/<时间戳>-migrate/``,
4
+ 再复用 ``profile`` → ``compose`` → ``verify`` 的原子写与读回,任一步失败按备份逐字节还原;``--rollback <备份目录>`` 只在当前状态
5
+ 等于迁移后状态时还原。用户的 ``custom`` 段与手工追加的内容一律保留:没有标签标记的行永远常驻,迁移不替用户猜标签。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import difflib
12
+ import hashlib
13
+ import json
14
+ import shlex
15
+ import shutil
16
+ import tempfile
17
+ from argparse import Namespace
18
+ from datetime import UTC, datetime
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ import inbox
23
+ import rule_lines
24
+ import tags
25
+ import versioned
26
+ from constants import KNOWN_PLACEHOLDERS
27
+ from i18n_opinion import _, N_ # noqa: E402
28
+
29
+
30
+ EXIT_OK, EXIT_ERROR, EXIT_CANNOT, EXIT_REFUSED, EXIT_FAILED = 0, 2, 3, 4, 5
31
+ BACKUPS = Path(".opinion") / "backups"
32
+ MANIFEST = "manifest.json"
33
+ RUNTIME = Path(__file__).resolve().with_name("opinion_manager.py")
34
+ EXCERPT = 80
35
+ # 状态:preview / migrated / unchanged / nothing-to-migrate / rolled-back 退出 0;cannot-migrate 为 3;refused 为 4;failed 为 5。
36
+ STATUS_EXIT = {"cannot-migrate": EXIT_CANNOT, "refused": EXIT_REFUSED, "failed": EXIT_FAILED}
37
+
38
+
39
+ class Stop(Exception):
40
+ """迁移在某一步停下:状态码、原因代码、说明与下一步命令;除 failed 外不改动任何文件。"""
41
+
42
+ def __init__(self, status: str, reason: str, message: str, steps: list[str] | None = None, **extra: Any) -> None:
43
+ super().__init__(message)
44
+ self.status, self.reason, self.message, self.steps, self.extra = status, reason, message, steps or [], extra
45
+
46
+
47
+ def sha(content: bytes) -> str:
48
+ return hashlib.sha256(content).hexdigest()
49
+
50
+
51
+ def command(root: Path, *words: str) -> str:
52
+ return " ".join(["python3", shlex.quote(str(RUNTIME)), "migrate", "--project", shlex.quote(str(root)), *words])
53
+
54
+
55
+ def guarded(action: Any, reason: str, hint: str) -> Any:
56
+ """读取阶段的 I/O 与格式错误统一为 cannot-migrate,附原因。"""
57
+ try:
58
+ return action()
59
+ except (versioned.OpinionVersionError, OSError, UnicodeDecodeError, ValueError, KeyError, TypeError) as exc:
60
+ raise Stop("cannot-migrate", reason, _("{0}:{1}").format(hint, exc)) from exc
61
+
62
+
63
+ # ---------------------------------------------------------------- 读取(只读)
64
+
65
+ def read_state(root: Path) -> dict[str, Any]:
66
+ """读取锁与正文;没有锁且正文空白(或初始化占位)返回 blank,其余无法迁移的形态抛 Stop。"""
67
+ if not root.is_dir():
68
+ raise Stop("cannot-migrate", "no-project", _("项目目录不存在:{0}").format(root))
69
+ lock_path, opinion_path = root / "opinion.lock.json", root / "OPINION.md"
70
+ has_lock = lock_path.exists() or lock_path.is_symlink()
71
+ current = guarded(lambda: versioned.file_state(opinion_path), "opinion-unreadable", _("OPINION.md 不可读")) # 含符号链接与非普通文件的拒绝
72
+ raw = opinion_path.read_bytes() if current is not None else b""
73
+ if not has_lock:
74
+ if current is None or not current.strip() or current in KNOWN_PLACEHOLDERS:
75
+ return {"blank": True, "current": current}
76
+ raise Stop("cannot-migrate", "no-lock", _("项目没有 opinion.lock.json,OPINION.md 又含有内容,无法确定它来自哪个 Profile;迁移不会猜测"),
77
+ [_("用 profile 预览、确认后写入一个 Profile,再用 compose --profile 生成带锁的 OPINION.md(选择模板或把现有内容放进 --custom-file);完成后重新运行 migrate")])
78
+ guarded(lambda: versioned.safe_path(lock_path), "lock-unreadable", _("锁文件不可读"))
79
+ lock = guarded(lambda: versioned.validate_lock(versioned.read_object(lock_path)), "lock-invalid", _("锁文件或 Profile 无效"))
80
+ if current is None:
81
+ raise Stop("cannot-migrate", "opinion-missing", _("OPINION.md 不存在,但项目有锁文件;先用锁里的 Profile 重建正文"),
82
+ [_("python3 {0} compose --project {1} --profile <锁里 Profile 的文件> --apply --confirm <预览指纹>").format(shlex.quote(str(RUNTIME)), shlex.quote(str(root)))])
83
+ return {"blank": False, "lock": lock, "current": current, "raw": raw, "lock_language": lock.get("language", "zh"),
84
+ "lock_bytes": lock_path.read_bytes()}
85
+
86
+
87
+ def summary(profile: dict[str, Any] | None) -> dict[str, Any] | None:
88
+ """loading 的前后对照用摘要;完整声明见 changes.loading。"""
89
+ loading = (profile or {}).get("loading")
90
+ if loading is None:
91
+ return None
92
+ if tags.is_tag_profile(profile or {}):
93
+ return {"kind": "tags", "always": len(loading["always"]), "tags": [item["id"] for item in loading["tags"]], "on_demand_rules": len(loading["members"])}
94
+ return {"kind": "bundles", "core": list(loading["core"]), "bundles": [item["family"] for item in loading["bundles"]]}
95
+
96
+
97
+ # ---------------------------------------------------------------- 手工修改:只接受能放进 custom 的改动
98
+
99
+ def manual_edits(expected: str, current: str, profile: dict[str, Any], language: str) -> dict[str, Any]:
100
+ """比较「按锁渲染的正文」与当前正文。自定义规则小节内的任何改动、其余位置的纯追加都并入新的 custom(保持原样,常驻);
101
+ 改写或删除了生成内容(规则正文、元数据)无法放进 custom,抛 Stop。"""
102
+ before, after = expected.splitlines(), current.splitlines()
103
+ heading = versioned.FRAME[language]["custom"]
104
+ start = None
105
+ if profile["custom"]:
106
+ candidate = len(before) - len(profile["custom"].split("\n"))
107
+ if candidate >= 2 and before[candidate - 2] == heading and before[candidate - 1] == "":
108
+ start = candidate
109
+ inside: list[str] = []
110
+ extra: list[list[str]] = []
111
+ rejected: list[tuple[int, str]] = []
112
+ edited = 0
113
+ for op, i1, i2, j1, j2 in difflib.SequenceMatcher(None, before, after, autojunk=False).get_opcodes():
114
+ if op == "equal":
115
+ if start is not None and i2 > start:
116
+ inside.extend(before[max(i1, start):i2])
117
+ continue
118
+ in_custom = start is not None and i1 >= start
119
+ if op == "insert" and not in_custom:
120
+ extra.append(after[j1:j2])
121
+ elif in_custom:
122
+ inside.extend(after[j1:j2])
123
+ edited += sum(1 for line in after[j1:j2] if line.strip())
124
+ else:
125
+ rejected.append((i1 + 1, before[i1] if i1 < len(before) else ""))
126
+ if rejected:
127
+ shown = _(";").join(_("第 {0} 行:{1}").format(number, text[:EXCERPT]) for number, text in rejected[:3])
128
+ raise Stop("cannot-migrate", "manual-edit-conflict",
129
+ _("OPINION.md 与锁不一致,且改动落在生成内容里(改写或删除了规则正文或元数据),无法并入自定义规则:{0}").format(shown),
130
+ [_("把改动写成自定义规则(放在“用户自定义规则”小节,或用 inbox add / adopt),或还原被改动的生成内容,再重新运行 migrate;规则本身的修订用 profile --overrides-file")],
131
+ conflicts=[{"line": number, "text": text} for number, text in rejected])
132
+ appended = [_trim(hunk) for hunk in extra if any(line.strip() for line in hunk)]
133
+ parts = [_trim(inside)] if any(line.strip() for line in inside) else []
134
+ custom = "\n\n".join(["\n".join(part) for part in parts + appended]).strip() or None
135
+ lines = [line for hunk in appended for line in hunk if line.strip()]
136
+ return {"custom": custom, "appended_lines": len(lines), "edited_in_custom": edited, "appended": lines}
137
+
138
+
139
+ def _trim(lines: list[str]) -> list[str]:
140
+ start, end = 0, len(lines)
141
+ while start < end and not lines[start].strip():
142
+ start += 1
143
+ while end > start and not lines[end - 1].strip():
144
+ end -= 1
145
+ return lines[start:end]
146
+
147
+
148
+ # ---------------------------------------------------------------- 分类
149
+
150
+ def classify_custom(profile: dict[str, Any], content: str, language: str) -> dict[str, Any]:
151
+ """custom 段逐行归类:tagged(已带有效标签)/ suggest(有条件的结构化行,可手工加标签)/ resident(常驻,不改)。"""
152
+ if not profile["custom"]:
153
+ return {"lines": [], "tagged": 0, "suggested": 0, "resident": 0, "available_tags": []}
154
+ vocabulary = [item["id"] for item in profile["loading"]["tags"]] if tags.is_tag_profile(profile) else []
155
+ owners = {}
156
+ if vocabulary:
157
+ for index, (_line, tag_set) in enumerate(tags.split_custom(profile)[0]):
158
+ owners[index] = tag_set
159
+ rendered = content.splitlines()
160
+ first = None
161
+ heading = versioned.FRAME[language]["custom"]
162
+ for number, line in enumerate(rendered):
163
+ if line == heading:
164
+ first = number + 2
165
+ entries: list[dict[str, Any]] = []
166
+ for index, line in enumerate(profile["custom"].split("\n")):
167
+ if not line.strip():
168
+ continue
169
+ parsed = rule_lines.parse_line(line)
170
+ owned = owners.get(index, ())
171
+ if owned:
172
+ category = "tagged"
173
+ elif vocabulary and parsed and parsed.get("trigger") and not parsed.get("tags") and not parsed.get("tags_error"):
174
+ category = "suggest"
175
+ else:
176
+ category = "resident"
177
+ entry = {"line": (first + index + 1) if first is not None else None, "category": category, "text": line[:EXCERPT]}
178
+ if owned:
179
+ entry["tags"] = list(owned)
180
+ if category == "resident" and parsed and (parsed.get("tags") or parsed.get("tags_error")):
181
+ entry["note"] = "invalid-tags"
182
+ entries.append(entry)
183
+ count = lambda name: sum(1 for item in entries if item["category"] == name) # noqa: E731
184
+ return {"lines": entries, "tagged": count("tagged"), "suggested": count("suggest"), "resident": count("resident"), "available_tags": vocabulary}
185
+
186
+
187
+ def inbox_report(root: Path) -> dict[str, Any]:
188
+ """收件箱只读:列出缺 trigger / purpose 的旧候选(不改写、不阻断),并给出文件指纹供确认指纹使用。"""
189
+ path = root / inbox.STORE
190
+ try:
191
+ raw = path.read_bytes() if path.exists() and not path.is_symlink() else None
192
+ data = inbox.load(root)
193
+ except (inbox.InboxError, OSError, ValueError, UnicodeDecodeError) as exc:
194
+ return {"readable": False, "error": str(exc), "incomplete": [], "sha256": None}
195
+ incomplete = [{"id": identity, "title": item.get("title", ""), "status": item.get("status"), "missing": inbox.missing_fields(item)}
196
+ for identity, item in sorted(data["candidates"].items()) if item.get("status") != "formal" and inbox.missing_fields(item)]
197
+ return {"readable": True, "incomplete": incomplete, "sha256": sha(raw) if raw is not None else None}
198
+
199
+
200
+ # ---------------------------------------------------------------- 计划(只读)
201
+
202
+ def plan_for(root: Path, args: argparse.Namespace, workdir: Path) -> dict[str, Any]:
203
+ state = read_state(root)
204
+ if state["blank"]:
205
+ return {"result": {"status": "nothing-to-migrate", "reason": "blank", "message": _("没有可迁移的内容:OPINION.md 不存在或只是初始化出来的空白文件")}, "actionable": False}
206
+ lock, current = state["lock"], state["current"]
207
+ old, language = lock["profile"], versioned.project_language(root)
208
+ base: dict[str, Any] = {
209
+ "profile": {"id": old["id"], "version": old["version"], "schema_version": old["schema_version"], "templates": old["templates"], "rules": old["rules"]},
210
+ "inbox": inbox_report(root),
211
+ "loading": {"before": summary(old), "after": summary(old)},
212
+ "opinion_md": {"modified": versioned.text_digest(current) != lock["opinion_sha256"], "sha256": versioned.text_digest(current), "lock_sha256": lock["opinion_sha256"],
213
+ "crlf": b"\r\n" in state["raw"]},
214
+ "notes": [],
215
+ }
216
+ if state["raw"] and b"\r\n" in state["raw"]:
217
+ base["notes"].append(_("OPINION.md 使用 CRLF 行尾;迁移后的正文统一为 LF,回滚会逐字节还原原文件"))
218
+ old_file = workdir / "old-profile.json"
219
+ old_file.write_text(versioned.pretty(old), encoding="utf-8")
220
+ refs = updates_for(old_file, old, args)
221
+ base["updates"] = refs["entries"]
222
+ base["custom"] = classify_custom(old, versioned.render(old, state["lock_language"]), state["lock_language"])
223
+ schema = old["schema_version"]
224
+ if schema == "2.2":
225
+ return {"result": {**base, "status": "unchanged", "reason": "already-tagged", "message": _("已经是带标签声明的 Profile(schema 2.2),无需迁移")}, "actionable": False}
226
+ if schema == "2.1" and not args.tags:
227
+ return {"result": {**base, "status": "unchanged", "reason": "bundles-kept",
228
+ "message": _("Profile 使用规则束声明(schema 2.1),按约定保持不动,context bundle 继续可用"),
229
+ "next": [_("如要改用标签,先预览:{0}").format(command(root, "--tags"))]}, "actionable": False}
230
+ if schema == "2.1":
231
+ base["notes"].append(_("改用标签会把规则束声明(core / signals / bundles)整体替换为标签声明;新旧声明互斥,改写后不再有 bundles,context bundle 不再可用"))
232
+ elif schema == "2.0":
233
+ base["notes"].append(_("若此前用 --no-tags 有意保持完整读取,迁移会重新生成标签声明;不迁移则保持原样,迁移后可用 --rollback 或 profile --remove-loading 恢复完整读取"))
234
+ return draft(root, args, workdir, state, base, refs, old_file)
235
+
236
+
237
+ def updates_for(old_file: Path, old: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
238
+ """沿用 updates 的预览:可升级的模板与规则;--skip 的项保持当前版本。"""
239
+ found = guarded(lambda: versioned.updates_command(Namespace(profile=old_file, catalog=versioned.PUBLIC_CATALOG))["updates"], "catalog-conflict", _("公开 catalog 与 Profile 记录的来源不一致"))
240
+ entries, templates, rules = [], [], []
241
+ known = {versioned.parse_ref(item["current"], item["kind"])[0] for item in found}
242
+ unknown = sorted(set(args.skip) - known)
243
+ if unknown:
244
+ versioned.fail(_("--skip 引用了没有可升级版本的项:{0};可用的项:{1}").format(", ".join(unknown), ", ".join(sorted(known)) or "-"))
245
+ for item in found:
246
+ identity = versioned.parse_ref(item["current"], item["kind"])[0]
247
+ target = item["available"][-1]
248
+ skipped = identity in args.skip
249
+ entries.append({"kind": item["kind"], "id": identity, "current": item["current"], "target": target, "action": "skip" if skipped else "upgrade"})
250
+ if not skipped:
251
+ (templates if item["kind"] == "templates" else rules).append(target)
252
+ return {"entries": entries, "templates": templates, "rules": rules}
253
+
254
+
255
+ def draft(root: Path, args: argparse.Namespace, workdir: Path, state: dict[str, Any], base: dict[str, Any], refs: dict[str, Any], old_file: Path) -> dict[str, Any]:
256
+ lock, current = state["lock"], state["current"]
257
+ old, language = lock["profile"], versioned.project_language(root)
258
+ custom_file = None
259
+ manual = None
260
+ if base["opinion_md"]["modified"]:
261
+ manual = manual_edits(versioned.render(old, state["lock_language"]), current, old, state["lock_language"])
262
+ if manual["custom"] is None and old["custom"]:
263
+ raise Stop("cannot-migrate", "manual-edit-conflict", _("OPINION.md 删除了全部自定义规则,迁移无法表示这种改动;迁移不会让已删除的行复活"),
264
+ [_("先用 profile 派生一个不含这些自定义规则的新版本,或还原被删除的行,再重新运行 migrate")])
265
+ base["opinion_md"]["manual"] = {"appended_lines": manual["appended_lines"], "edited_in_custom": manual["edited_in_custom"], "appended": manual["appended"]}
266
+ if manual["custom"] and manual["custom"] != (old["custom"] or ""):
267
+ custom_file = workdir / "custom.md"
268
+ custom_file.write_text(manual["custom"] + "\n", encoding="utf-8")
269
+ major, minor, patch = versioned.version(old["version"])
270
+ while True:
271
+ patch += 1
272
+ number = f"{major}.{minor}.{patch}"
273
+ target = root / ".opinion" / "profiles" / old["id"] / "versions" / f"{number}.json"
274
+ if not target.exists():
275
+ break
276
+
277
+ def namespace(**override: Any) -> Namespace:
278
+ values = dict(project=root, id=old["id"], version=number, template=refs["templates"], rule=refs["rules"], remove_template=[], remove_rule=[], custom_file=custom_file,
279
+ from_profile=old_file, overrides_file=None, resolutions_file=args.resolutions_file, loading_file=None, remove_loading=False, no_tags=False,
280
+ catalog=versioned.PUBLIC_CATALOG, apply=False, confirm=None)
281
+ values.update(override)
282
+ return Namespace(**values)
283
+
284
+ # 先只取升级后的来源(不带声明),再由所选模板合并出标签声明,作为 --loading-file 显式写入,不依赖 profile 对“模板选择是否变化”的判断。
285
+ first = guarded(lambda: versioned.profile_command(namespace(remove_loading=True)), "draft-failed", _("无法生成新的 Profile 预览"))
286
+ proposed = guarded(lambda: versioned.template_loading(first["profile"]["sources"]), "tag-conflict", _("所选模板的标签声明无法合并"))
287
+ if proposed is None:
288
+ return {"result": {**base, "status": "nothing-to-migrate", "reason": "no-tag-declaration",
289
+ "message": _("所选的公开模板没有可物化的标签声明(没有选用公开模板,或模板版本不带标签),保持完整读取,没有可迁移的内容"),
290
+ "updates": [{**item, "action": "available"} for item in base["updates"]]}, "actionable": False}
291
+ loading_file = workdir / "loading.json"
292
+ loading_file.write_text(versioned.pretty(proposed), encoding="utf-8")
293
+ drafted = guarded(lambda: versioned.profile_command(namespace(loading_file=loading_file)), "draft-failed", _("无法生成新的 Profile 预览"))
294
+ profile = drafted["profile"]
295
+ preview_file = workdir / "profile.json"
296
+ preview_file.write_text(versioned.pretty(profile), encoding="utf-8")
297
+ accept = versioned.text_digest(current) if base["opinion_md"]["modified"] else None
298
+ compose_args = Namespace(project=root, profile=preview_file, template=[], rule=[], custom_file=None, replace=False, accept_current=accept, apply=False, confirm=None)
299
+ composed = guarded(lambda: versioned.compose_command(compose_args), "compose-failed", _("无法生成新的 OPINION.md 预览"))
300
+ changes = drafted["changes"]
301
+ base["loading"] = {"before": summary(old), "after": summary(profile), "source": "template"}
302
+ base["custom"] = classify_custom(profile, composed["content"], language)
303
+ base["changes"] = {key: changes[key] for key in ("added", "removed", "changed", "custom_changed", "templates", "direct_rules", "loading_changed", "loading")} | {"conflicts": [item["id"] for item in changes["conflicts"]]}
304
+ unified = list(difflib.unified_diff(current.splitlines(), composed["content"].splitlines(), "OPINION.md", "OPINION.md (migrated)", lineterm="", n=0))
305
+ base["diff"] = {"added_lines": sum(1 for line in unified if line.startswith("+") and not line.startswith("+++")),
306
+ "removed_lines": sum(1 for line in unified if line.startswith("-") and not line.startswith("---"))}
307
+ base["target"] = {"profile": f"{old['id']}@{number}", "schema_version": profile["schema_version"], "path": str(target)}
308
+ unresolved = list(drafted["unresolved"])
309
+ classification = {key: base[key] for key in ("profile", "target", "updates", "loading", "opinion_md", "custom", "inbox", "changes")}
310
+ fingerprint = versioned.digest({"profile": drafted["confirmation_sha256"], "compose": composed["confirmation_sha256"], "classification": classification})
311
+ steps = []
312
+ if unresolved:
313
+ steps.append(_("先处理升级冲突:为 {0} 写 resolutions 文件(每项 keep-local 或 use-upstream),再加 --resolutions-file 重新预览").format(", ".join(unresolved)))
314
+ elif composed["blocked"]:
315
+ steps.append(composed["blocked"])
316
+ else:
317
+ steps.append(_("审阅后确认:{0}").format(command(root, *(["--tags"] if args.tags else []), *[item for skip in args.skip for item in ("--skip", shlex.quote(skip))],
318
+ *(["--resolutions-file", shlex.quote(str(args.resolutions_file))] if args.resolutions_file else []), "--apply", "--confirm", fingerprint)))
319
+ result = {**base, "status": "preview", "unresolved": unresolved, "blocked": composed["blocked"], "confirmation_sha256": fingerprint, "content": composed["content"], "next": steps,
320
+ **{key: composed[key] for key in ("untranslated", "warnings") if key in composed}}
321
+ return {"result": result, "actionable": True, "fingerprint": fingerprint, "unresolved": unresolved, "blocked": composed["blocked"], "target": target, "number": number,
322
+ "drafted": drafted, "composed": composed, "namespace": namespace(loading_file=loading_file), "compose_args": compose_args, "content": composed["content"],
323
+ "old": old, "old_file": old_file, "preview_file": preview_file, "accept": accept}
324
+
325
+
326
+ # ---------------------------------------------------------------- 备份、写入、读回、还原
327
+
328
+ def backup_files(root: Path, old: dict[str, Any]) -> list[tuple[str, Path, bool]]:
329
+ """备份的相对路径、源文件、回滚时是否还原。收件箱仅作留底,迁移不改写它,回滚也不还原它。"""
330
+ profile = Path(".opinion") / "profiles" / old["id"] / "versions" / f"{old['version']}.json"
331
+ items = [("OPINION.md", root / "OPINION.md", True), ("opinion.lock.json", root / "opinion.lock.json", True), (profile.as_posix(), root / profile, True), (inbox.STORE.as_posix(), root / inbox.STORE, False)]
332
+ return [item for item in items if item[1].exists()]
333
+
334
+
335
+ def write_backup(root: Path, plan: dict[str, Any], directory: Path) -> list[dict[str, Any]]:
336
+ entries = []
337
+ for relative, source, restore in backup_files(root, plan["old"]):
338
+ raw = source.read_bytes()
339
+ destination = directory / "files" / relative
340
+ destination.parent.mkdir(parents=True, exist_ok=True)
341
+ destination.write_bytes(raw)
342
+ entries.append({"path": relative, "sha256": sha(raw), "restore": restore})
343
+ manifest = {"schema": 1, "kind": "opinion-migrate", "created_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), "confirmation_sha256": plan["fingerprint"],
344
+ "before": f"{plan['old']['id']}@{plan['old']['version']}", "before_consistent": not plan["result"]["opinion_md"]["modified"],
345
+ "files": entries, "after": None}
346
+ (directory / MANIFEST).write_text(versioned.pretty(manifest), encoding="utf-8")
347
+ return entries
348
+
349
+
350
+ def write_new(root: Path, plan: dict[str, Any]) -> None:
351
+ versioned.profile_command(Namespace(**{**vars(plan["namespace"]), "apply": True, "confirm": plan["drafted"]["confirmation_sha256"]}))
352
+ versioned.compose_command(Namespace(**{**vars(plan["compose_args"]), "profile": plan["target"], "apply": True, "confirm": plan["composed"]["confirmation_sha256"]}))
353
+
354
+
355
+ def read_back(root: Path, plan: dict[str, Any]) -> dict[str, Any]:
356
+ verified = versioned.verify_project(root)
357
+ if (root / "OPINION.md").read_text(encoding="utf-8") != plan["content"]:
358
+ versioned.fail(_("写入后读回的 OPINION.md 与预览不一致"))
359
+ if versioned.read_object(plan["target"]) != plan["drafted"]["profile"]:
360
+ versioned.fail(_("写入后读回的 Profile 与预览不一致"))
361
+ return verified
362
+
363
+
364
+ def restore_all(root: Path, directory: Path, manifest: dict[str, Any], target: Path | None) -> None:
365
+ for item in manifest["files"]:
366
+ if item["restore"]:
367
+ inbox.restore(root / item["path"], (directory / "files" / item["path"]).read_bytes())
368
+ if target is not None:
369
+ target.unlink(missing_ok=True)
370
+
371
+
372
+ def unique_directory(root: Path) -> Path:
373
+ moment = datetime.now(UTC)
374
+ while True:
375
+ candidate = root / BACKUPS / f"{moment.strftime('%Y%m%dT%H%M%SZ')}-migrate"
376
+ if not candidate.exists():
377
+ return candidate
378
+ moment = datetime.fromtimestamp(moment.timestamp() + 1, UTC)
379
+
380
+
381
+ def created_directories(root: Path, target: Path) -> list[Path]:
382
+ chain = [root / ".opinion", root / BACKUPS, target.parent.parent.parent, target.parent.parent, target.parent]
383
+ return [path for path in chain if not path.exists()]
384
+
385
+
386
+ def remove_created(paths: list[Path]) -> None:
387
+ for path in sorted(paths, key=lambda item: len(item.parts), reverse=True):
388
+ try:
389
+ path.rmdir()
390
+ except OSError:
391
+ pass
392
+
393
+
394
+ def apply(root: Path, plan: dict[str, Any], args: argparse.Namespace) -> dict[str, Any]:
395
+ result = plan["result"]
396
+ if plan["unresolved"]:
397
+ raise Stop("refused", "unresolved-conflicts", _("升级存在未确认的冲突:{0}").format(", ".join(plan["unresolved"])), result["next"])
398
+ if plan["blocked"]:
399
+ raise Stop("refused", "blocked", plan["blocked"])
400
+ if not args.confirm:
401
+ raise Stop("refused", "confirm-required", _("写入需要 --apply --confirm <预览指纹>;先审阅预览"), result["next"])
402
+ if args.confirm != plan["fingerprint"]:
403
+ raise Stop("refused", "stale-confirmation", _("确认指纹与当前预览不一致:预览之后 Profile、OPINION.md、收件箱或 catalog 有变化;请重新预览并审阅"),
404
+ [command(root, *(["--tags"] if args.tags else []))])
405
+ directory = unique_directory(root)
406
+ created = created_directories(root, plan["target"])
407
+ manifest: dict[str, Any] = {}
408
+ phase = "backup"
409
+ try:
410
+ manifest = {"files": write_backup(root, plan, directory)}
411
+ phase = "write"
412
+ write_new(root, plan)
413
+ phase = "read-back"
414
+ verified = read_back(root, plan)
415
+ phase = "manifest"
416
+ finalize_manifest(root, directory, plan)
417
+ except BaseException as exc:
418
+ restored, detail = True, ""
419
+ try:
420
+ if manifest:
421
+ restore_all(root, directory, manifest, plan["target"])
422
+ else:
423
+ plan["target"].unlink(missing_ok=True)
424
+ shutil.rmtree(directory, ignore_errors=True)
425
+ remove_created(created)
426
+ except BaseException as inner: # 还原本身失败:保留备份目录,给出手工还原方法
427
+ restored, detail = False, str(inner)
428
+ if not isinstance(exc, Exception):
429
+ raise
430
+ message = _("迁移在“{0}”阶段失败:{1}").format(phase, exc)
431
+ if restored:
432
+ raise Stop("failed", "apply-failed", message + _(";已按备份逐字节还原,项目与迁移前相同"), phase=phase, restored=True) from exc
433
+ raise Stop("failed", "restore-failed", message + _(";自动还原也失败了({0}),备份目录已保留:{1}").format(detail, directory),
434
+ [command(root, "--rollback", shlex.quote(str(directory)))], phase=phase, restored=False, backup=str(directory)) from exc
435
+ return {**result, "status": "migrated", "applied": True, "backup": str(directory), "verified": verified,
436
+ "message": _("已迁移到 {0}(schema {1}),备份在 {2}").format(plan["result"]["target"]["profile"], plan["result"]["target"]["schema_version"], directory),
437
+ "next": [_("不满意时回滚:{0}").format(command(root, "--rollback", shlex.quote(str(directory))))]}
438
+
439
+
440
+ def finalize_manifest(root: Path, directory: Path, plan: dict[str, Any]) -> None:
441
+ manifest = json.loads((directory / MANIFEST).read_text(encoding="utf-8"))
442
+ manifest["after"] = {"profile": plan["result"]["target"]["profile"], "profile_path": plan["target"].relative_to(root).as_posix(), "profile_sha256": sha(plan["target"].read_bytes()),
443
+ "opinion_sha256": sha((root / "OPINION.md").read_bytes()), "lock_sha256": sha((root / "opinion.lock.json").read_bytes())}
444
+ (directory / MANIFEST).write_text(versioned.pretty(manifest), encoding="utf-8")
445
+
446
+
447
+ # ---------------------------------------------------------------- 回滚
448
+
449
+ def rollback(root: Path, argument: Path) -> dict[str, Any]:
450
+ directory = Path(argument if argument.is_absolute() else Path.cwd() / argument)
451
+ directory = Path(versioned.safe_path(directory))
452
+ parent = Path(versioned.safe_path(root / BACKUPS))
453
+ if directory.parent != parent or not directory.name.endswith("-migrate") or not directory.is_dir():
454
+ raise Stop("refused", "not-a-backup", _("回滚目录必须是本项目 .opinion/backups/ 下的 *-migrate 目录:{0}").format(directory))
455
+ manifest = guarded(lambda: json.loads((directory / MANIFEST).read_text(encoding="utf-8")), "manifest-invalid", _("备份 manifest 不可读"))
456
+ if not isinstance(manifest, dict) or manifest.get("kind") != "opinion-migrate" or not isinstance(manifest.get("files"), list):
457
+ raise Stop("refused", "manifest-invalid", _("备份 manifest 格式无效"))
458
+ if not manifest.get("after"):
459
+ raise Stop("refused", "incomplete-backup", _("备份没有迁移后的状态记录(迁移未完成),无法确认是否可以安全回滚;该目录只是失败现场的备份"))
460
+ for item in manifest["files"]:
461
+ stored = directory / "files" / item["path"]
462
+ if not stored.is_file() or sha(stored.read_bytes()) != item["sha256"]:
463
+ raise Stop("refused", "backup-damaged", _("备份文件缺失或指纹不符:{0}").format(item["path"]))
464
+ after = manifest["after"]
465
+ target = root / after["profile_path"]
466
+
467
+ def current(path: Path) -> str | None:
468
+ return sha(path.read_bytes()) if path.is_file() else None
469
+
470
+ restorable = [item for item in manifest["files"] if item["restore"]]
471
+ before_state = all(current(root / item["path"]) == item["sha256"] for item in restorable) and not target.exists()
472
+ after_state = (current(root / "OPINION.md") == after["opinion_sha256"] and current(root / "opinion.lock.json") == after["lock_sha256"] and current(target) == after["profile_sha256"])
473
+ if before_state:
474
+ return {"ok": True, "status": "unchanged", "reason": "already-restored", "message": _("当前状态已经等于迁移前,无需回滚"), "backup": str(directory)}
475
+ if not after_state:
476
+ changed = [name for name, value in (("OPINION.md", current(root / "OPINION.md") == after["opinion_sha256"]), ("opinion.lock.json", current(root / "opinion.lock.json") == after["lock_sha256"]),
477
+ (after["profile_path"], current(target) == after["profile_sha256"])) if not value]
478
+ raise Stop("refused", "state-changed", _("当前状态不等于迁移后的状态(迁移之后这些文件又被修改:{0}),回滚会丢失后续修改,已拒绝;需要时手工从备份目录取回文件").format(", ".join(changed)),
479
+ changed=changed, backup=str(directory))
480
+ snapshot = {path: path.read_bytes() if path.exists() else None for path in (root / "OPINION.md", root / "opinion.lock.json", target)}
481
+ try:
482
+ restore_all(root, directory, manifest, target)
483
+ # 迁移前正文被手工修改过时,还原后 verify 按设计不通过,只做逐字节核对
484
+ verified = versioned.verify_project(root) if manifest.get("before_consistent", True) else None
485
+ for item in restorable:
486
+ if current(root / item["path"]) != item["sha256"]:
487
+ versioned.fail(_("还原后核对失败:{0}").format(item["path"]))
488
+ except BaseException as exc:
489
+ for path, content in snapshot.items():
490
+ inbox.restore(path, content)
491
+ if not isinstance(exc, Exception):
492
+ raise
493
+ raise Stop("failed", "rollback-failed", _("回滚失败:{0};已恢复到回滚前的状态").format(exc), restored=True) from exc
494
+ return {"ok": True, "status": "rolled-back", "backup": str(directory), "verified": verified, "message": _("已按备份还原 Profile、OPINION.md 与锁,并删除迁移写入的 Profile {0}").format(after["profile"])}
495
+
496
+
497
+ # ---------------------------------------------------------------- 输出与入口
498
+
499
+ def text_of(result: dict[str, Any]) -> str:
500
+ """可读文字:框架文字随界面语言;用户自己的内容原样引用。"""
501
+ names = {"preview": N_("预览(未写入任何文件)"), "migrated": N_("已迁移"), "unchanged": N_("无需改动"), "nothing-to-migrate": N_("没有可迁移的内容"), "rolled-back": N_("已回滚"),
502
+ "cannot-migrate": N_("无法迁移(未写入任何文件)"), "refused": N_("已拒绝(未写入任何文件)"), "failed": N_("失败")}
503
+ lines = [_("# Opinion 迁移"), "", _("- 状态:{0}").format(_(names[result["status"]]))]
504
+ if result.get("message"):
505
+ lines.append(_("- 说明:{0}").format(result["message"]))
506
+ if result.get("reason"):
507
+ lines.append(_("- 原因代码:{0}").format(result["reason"]))
508
+ profile = result.get("profile")
509
+ if profile:
510
+ lines.append(_("- 当前 Profile:`{0}@{1}`(schema {2})").format(profile["id"], profile["version"], profile["schema_version"]))
511
+ if result.get("target"):
512
+ lines.append(_("- 迁移后 Profile:`{0}`(schema {1})").format(result["target"]["profile"], result["target"]["schema_version"]))
513
+ if result.get("updates"):
514
+ lines.extend(("", _("## 模板与规则升级")))
515
+ for item in result["updates"]:
516
+ lines.append(_("- `{0}` → `{1}`({2})").format(item["current"], item["target"], _({"upgrade": N_("升级"), "skip": N_("按 --skip 保持当前版本"), "available": N_("可升级,本次未采用")}[item["action"]])))
517
+ if result.get("loading") and (result["loading"]["before"] or result["loading"]["after"]):
518
+ lines.extend(("", _("## 加载声明"), _("- 迁移前:{0}").format(json.dumps(result["loading"]["before"], ensure_ascii=False)), _("- 迁移后:{0}").format(json.dumps(result["loading"]["after"], ensure_ascii=False))))
519
+ if result.get("opinion_md"):
520
+ info = result["opinion_md"]
521
+ lines.extend(("", _("## OPINION.md"), _("- 是否被手工修改:{0}").format(_("是") if info["modified"] else _("否"))))
522
+ if info.get("manual"):
523
+ lines.append(_("- 手工内容并入自定义规则(原样保留、常驻):追加 {0} 行,自定义小节内改动 {1} 行").format(info["manual"]["appended_lines"], info["manual"]["edited_in_custom"]))
524
+ if result.get("diff"):
525
+ lines.append(_("- 新旧正文差异:+{0} / -{1} 行(完整新正文见 --output json 的 content)").format(result["diff"]["added_lines"], result["diff"]["removed_lines"]))
526
+ custom = result.get("custom")
527
+ if custom and custom["lines"]:
528
+ lines.extend(("", _("## 自定义规则"), _("- 已带标签:{0};常驻:{1};可手工加标签的建议:{2}").format(custom["tagged"], custom["resident"], custom["suggested"])))
529
+ for item in custom["lines"]:
530
+ if item["category"] == "suggest":
531
+ lines.append(_(" - 第 {0} 行可在行尾追加 `[tags 标签]`(可用标签:{1}):{2}").format(item["line"], ", ".join(custom["available_tags"]), item["text"]))
532
+ if result.get("inbox", {}).get("incomplete"):
533
+ lines.extend(("", _("## 收件箱中缺字段的旧候选(只列出,不改写,不影响迁移)")))
534
+ for item in result["inbox"]["incomplete"]:
535
+ lines.append(_("- `{0}` {1}:缺 {2}").format(item["id"], item["title"], ", ".join(item["missing"])))
536
+ for note in result.get("notes", []):
537
+ lines.append(_("- 注意:{0}").format(note))
538
+ for warning in result.get("warnings", []):
539
+ lines.append(_("- 警告:{0}").format(warning))
540
+ if result.get("confirmation_sha256"):
541
+ lines.extend(("", _("确认指纹:`{0}`").format(result["confirmation_sha256"])))
542
+ if result.get("next"):
543
+ lines.extend(("", _("## 下一步"), *[f"- {step}" for step in result["next"]]))
544
+ return "\n".join(lines) + "\n"
545
+
546
+
547
+ def emit(result: dict[str, Any], output: str) -> tuple[int, str]:
548
+ code = STATUS_EXIT.get(result["status"], EXIT_OK)
549
+ result = {"ok": code == EXIT_OK, **{key: value for key, value in result.items() if key != "ok"}}
550
+ return code, (versioned.pretty(result) if output == "json" else text_of(result))
551
+
552
+
553
+ def execute(args: argparse.Namespace) -> tuple[int, str]:
554
+ root = versioned.safe_path(args.project)
555
+ try:
556
+ if args.rollback is not None:
557
+ if args.apply or args.confirm or args.tags or args.skip or args.resolutions_file:
558
+ versioned.fail(_("--rollback 不能与 --apply、--confirm、--tags、--skip、--resolutions-file 同用"))
559
+ return emit({"project": str(root), **rollback(root, args.rollback)}, args.output)
560
+ if args.confirm and not args.apply:
561
+ versioned.fail(_("--confirm 需要和 --apply 一起使用"))
562
+ with tempfile.TemporaryDirectory(prefix="opinion-migrate-") as workdir:
563
+ plan = plan_for(root, args, Path(workdir).resolve())
564
+ result = plan["result"]
565
+ if args.apply and plan["actionable"]:
566
+ result = apply(root, plan, args)
567
+ except Stop as stop:
568
+ payload = {"status": stop.status, "reason": stop.reason, "message": stop.message, "project": str(root), "next": stop.steps, **stop.extra, "applied": False}
569
+ return emit(payload, args.output)
570
+ return emit({"project": str(root), "applied": bool(args.apply and result["status"] == "migrated"), **result}, args.output)
571
+
572
+
573
+ def add_command(subparsers: Any) -> None:
574
+ parser = subparsers.add_parser("migrate", help=_("把现有 Opinion 迁移到标签选择加载:默认预览,--apply --confirm 才写入,可回滚"))
575
+ parser.add_argument("--project", type=Path, required=True)
576
+ parser.add_argument("--apply", action="store_true", help=_("写入迁移(需要 --confirm)"))
577
+ parser.add_argument("--confirm", help=_("预览返回的确认指纹"))
578
+ parser.add_argument("--rollback", type=Path, help=_("还原到迁移前:.opinion/backups/ 下的备份目录"))
579
+ parser.add_argument("--tags", action="store_true", help=_("2.1(规则束声明)的项目改用标签声明;默认保持 2.1 不动"))
580
+ parser.add_argument("--skip", action="append", default=[], help=_("不升级这个模板(family/variant)或规则编号,可重复"))
581
+ parser.add_argument("--resolutions-file", type=Path, help=_("升级冲突的处理:编号到 keep-local 或 use-upstream 的 JSON"))
582
+ parser.add_argument("--output", choices=("json", "markdown"), default="markdown")
@@ -15,9 +15,10 @@ from typing import Any
15
15
  import context
16
16
  import inbox
17
17
  import lifecycle
18
+ import migrate
18
19
  import versioned
19
20
  from constants import KNOWN_PLACEHOLDERS
20
- from i18n_opinion import _ # noqa: E402
21
+ from i18n_opinion import _, resolve_language # noqa: E402
21
22
 
22
23
 
23
24
  PLUGIN_ROOT = Path(__file__).resolve().parents[1]
@@ -317,14 +318,15 @@ def catalog_markdown(catalog: OrderedDict[str, dict[str, Any]]) -> str:
317
318
  if not catalog:
318
319
  lines.append(_("当前没有已批准的公开模板。"))
319
320
  return "\n".join(lines).rstrip() + "\n"
321
+ language = resolve_language()
320
322
  for template in catalog.values():
321
323
  identity = f"{template['family']}/{template['variant']}" if "family" in template else template["id"]
322
324
  lines.extend((
323
- f"## {template['name']} `{identity}@{template['version']}`",
325
+ f"## {versioned.pick(template['name'], language)[0]} `{identity}@{template['version']}`",
324
326
  "",
325
- template["description"],
327
+ versioned.pick(template["description"], language)[0],
326
328
  "",
327
- _("规则数量:{0};适用场景:{1}。").format(len(template['rules']), _('、').join(template['scopes'])),
329
+ _("规则数量:{0};适用场景:{1}。").format(len(template['rules']), _('、').join(versioned.pick(template['scopes'], language)[0])),
328
330
  "",
329
331
  ))
330
332
  return "\n".join(lines).rstrip() + "\n"
@@ -356,6 +358,7 @@ def build_parser() -> argparse.ArgumentParser:
356
358
  context.add_command(subparsers)
357
359
  lifecycle.add_command(subparsers)
358
360
  inbox.add_command(subparsers)
361
+ migrate.add_command(subparsers)
359
362
  return parser
360
363
 
361
364
 
@@ -366,6 +369,8 @@ def execute(args: argparse.Namespace) -> tuple[int, str]:
366
369
  return lifecycle.execute(args)
367
370
  if args.command == "inbox":
368
371
  return inbox.execute(args)
372
+ if args.command == "migrate":
373
+ return migrate.execute(args)
369
374
  if versioned.handles(args):
370
375
  return versioned.execute(args)
371
376
  catalog = load_catalog()