@sakanano-moe/agenthelm 6.8.0 → 6.11.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 (90) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +2 -0
  3. package/package.json +1 -1
  4. package/runtime/index.json +6 -6
  5. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  6. package/runtime/plugins/agent-pack/hooks/hooks.json +32 -0
  7. package/runtime/plugins/agent-pack/plugin.json +1 -1
  8. package/runtime/plugins/agent-pack/references/local-only.md +126 -0
  9. package/runtime/plugins/agent-pack/references/nudge.en.md +58 -0
  10. package/runtime/plugins/agent-pack/references/nudge.md +58 -0
  11. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +613 -0
  12. package/runtime/plugins/agent-pack/runtime/agenthelm.py +1271 -221
  13. package/runtime/plugins/agent-pack/runtime/agenthelm_runtime.py +114 -65
  14. package/runtime/plugins/agent-pack/runtime/i18n_agent_pack.py +78 -0
  15. package/runtime/plugins/agent-pack/runtime/local_only.py +1132 -0
  16. package/runtime/plugins/agent-pack/runtime/locale/en.json +569 -0
  17. package/runtime/plugins/agent-pack/runtime/mcp_server.py +25 -0
  18. package/runtime/plugins/agent-pack/runtime/nudge_text.py +127 -0
  19. package/runtime/plugins/agent-pack/runtime/user_settings.py +275 -0
  20. package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +11 -1
  21. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  22. package/runtime/plugins/agents-init/content.json +4 -4
  23. package/runtime/plugins/agents-init/plugin.json +1 -1
  24. package/runtime/plugins/agents-init/skills/agents-init/AGENT.template.md +141 -5
  25. package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +41 -8
  26. package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +408 -80
  27. package/runtime/plugins/agents-init/skills/agents-init/scripts/adopt.py +615 -0
  28. package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +221 -0
  29. package/runtime/plugins/agents-init/skills/agents-init/scripts/i18n_init.py +78 -0
  30. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +748 -159
  31. package/runtime/plugins/agents-init/skills/agents-init/scripts/locale/en.json +289 -0
  32. package/runtime/plugins/agents-init/skills/agents-init/scripts/merge3.py +149 -0
  33. package/runtime/plugins/agents-init/skills/agents-init/scripts/regions.py +99 -0
  34. package/runtime/plugins/agents-init/skills/agents-init/scripts/scaffold.py +594 -90
  35. package/runtime/plugins/agents-init/skills/agents-init/skeleton.json +2 -0
  36. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  37. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  38. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  39. package/runtime/plugins/opinion-manager/references/inbox.en.md +48 -0
  40. package/runtime/plugins/opinion-manager/references/inbox.md +48 -0
  41. package/runtime/plugins/opinion-manager/runtime/context.py +31 -26
  42. package/runtime/plugins/opinion-manager/runtime/i18n_opinion.py +78 -0
  43. package/runtime/plugins/opinion-manager/runtime/inbox.py +398 -0
  44. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +114 -0
  45. package/runtime/plugins/opinion-manager/runtime/lifecycle.py +45 -44
  46. package/runtime/plugins/opinion-manager/runtime/locale/en.json +193 -0
  47. package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +55 -50
  48. package/runtime/plugins/opinion-manager/runtime/versioned.py +90 -85
  49. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +15 -2
  50. package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
  51. package/runtime/plugins/project-orchestrator/content.json +30 -3
  52. package/runtime/plugins/project-orchestrator/plugin.json +1 -1
  53. package/runtime/plugins/project-orchestrator/references/case-workspaces.md +9 -1
  54. package/runtime/plugins/project-orchestrator/references/case.schema.json +1 -0
  55. package/runtime/plugins/project-orchestrator/references/sop-interview.md +83 -0
  56. package/runtime/plugins/project-orchestrator/references/sop.md +156 -0
  57. package/runtime/plugins/project-orchestrator/runtime/assets.py +52 -57
  58. package/runtime/plugins/project-orchestrator/runtime/case.py +139 -80
  59. package/runtime/plugins/project-orchestrator/runtime/case_structure.py +71 -0
  60. package/runtime/plugins/project-orchestrator/runtime/case_workspace.py +47 -46
  61. package/runtime/plugins/project-orchestrator/runtime/i18n_orchestrator.py +78 -0
  62. package/runtime/plugins/project-orchestrator/runtime/locale/en.json +1450 -0
  63. package/runtime/plugins/project-orchestrator/runtime/memory.py +45 -45
  64. package/runtime/plugins/project-orchestrator/runtime/private_paths.py +119 -0
  65. package/runtime/plugins/project-orchestrator/runtime/project_base.py +37 -19
  66. package/runtime/plugins/project-orchestrator/runtime/project_cli.py +307 -195
  67. package/runtime/plugins/project-orchestrator/runtime/project_demo.py +130 -48
  68. package/runtime/plugins/project-orchestrator/runtime/project_maintain.py +328 -221
  69. package/runtime/plugins/project-orchestrator/runtime/project_menu.py +167 -89
  70. package/runtime/plugins/project-orchestrator/runtime/project_real.py +187 -105
  71. package/runtime/plugins/project-orchestrator/runtime/project_write.py +58 -55
  72. package/runtime/plugins/project-orchestrator/runtime/sop.py +1670 -0
  73. package/runtime/plugins/project-orchestrator/runtime/sop_structure.py +226 -0
  74. package/runtime/plugins/project-orchestrator/runtime/wf.py +74 -70
  75. package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +22 -0
  76. package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.en.md +57 -0
  77. package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.md +57 -0
  78. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.en.md +77 -0
  79. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.md +77 -0
  80. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.en.md +11 -0
  81. package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.md +11 -0
  82. package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.en.md +87 -0
  83. package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.md +87 -0
  84. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.en.md +75 -0
  85. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.md +75 -0
  86. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.en.md +11 -0
  87. package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.md +12 -0
  88. package/runtime/plugins/project-orchestrator/templates/CASE.en.md +39 -0
  89. package/runtime/plugins/agents-init/skills/agents-init/scripts/test_init_project.py +0 -678
  90. package/runtime/plugins/agents-init/skills/agents-init/scripts/test_scaffold.py +0 -551
@@ -4,6 +4,7 @@
4
4
  from __future__ import annotations
5
5
 
6
6
  import argparse
7
+ import dataclasses
7
8
  import difflib
8
9
  import hashlib
9
10
  import json
@@ -11,12 +12,17 @@ import os
11
12
  import re
12
13
  import stat
13
14
  import sys
15
+ import tempfile
14
16
  from dataclasses import dataclass
17
+ from datetime import datetime, timezone
15
18
  from pathlib import Path
16
19
  from typing import Iterable
20
+ if str(Path(__file__).resolve().parent) not in sys.path: # also loaded by path from other plugins
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+ from i18n_init import _, resolve_language # noqa: E402
17
23
 
18
24
 
19
- INITIALIZER_VERSION = "6.6.0"
25
+ INITIALIZER_VERSION = "6.8.1"
20
26
  PLUGIN_ROOT = Path(__file__).resolve().parents[3]
21
27
  PROFILE_SCHEMA = "https://skill.sakanano.moe/skills/agents-init/project.schema.json"
22
28
  PROFILE_PATH = Path(".agents/moe.sakanano.agent-pack/project.json")
@@ -53,7 +59,9 @@ DEFAULT_ENTRY = "menu"
53
59
  ENTRY_API = 1
54
60
  ENTRY_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
55
61
  RESERVED_ENTRY_NAMES = {"AGENTS.md", "AGENT.md", "CLAUDE.md", "AGENT.RULES.md", "OPINION.md", "README.md",
56
- "cases", "docs", "memory", ".agents", ".git"}
62
+ "cases", "docs", "memory", "sops", "private", ".agents", ".git"}
63
+ # 私有目录:内容默认不进入 git(与 project-orchestrator 的 private_paths.IGNORE_TEXT 相同,测试核对一致)。
64
+ PRIVATE_IGNORE = "# agenthelm: 本目录内容默认不进入 git;读取前须经用户确认。\n*\n!.gitignore\n"
57
65
  README_START = "<!-- agenthelm:entry -->"
58
66
  README_END = "<!-- /agenthelm:entry -->"
59
67
  # 内容锁里没有记录模板版本时(早于内容锁的项目),补登的条目使用这个版本,检查会提示刷新。
@@ -69,6 +77,17 @@ REQUIRED_TEMPLATES = {
69
77
  "AGENT.RULES.md",
70
78
  "OPINION.md",
71
79
  "ROUTE.md",
80
+ "CLAUDE.md",
81
+ "region/claude-import",
82
+ "region/agents-contract",
83
+ "region/privacy-contract",
84
+ "region/privacy-contract.en",
85
+ "privacy/declared",
86
+ "privacy/undeclared",
87
+ "privacy/declared.en",
88
+ "privacy/undeclared.en",
89
+ "privacy/rules-line",
90
+ "privacy/rules-line.en",
72
91
  ".agent-doc/plan.md",
73
92
  ".agent-doc/progress.md",
74
93
  ".agent-doc/chat-summary.md",
@@ -76,6 +95,10 @@ REQUIRED_TEMPLATES = {
76
95
  }
77
96
 
78
97
 
98
+ # 隐私约定相关的区块是 rc.2 才加入的;rc.1 及更早的历史版本包没有它们,渲染旧基线时按空文本处理。
99
+ PRIVACY_TEMPLATES = {name for name in REQUIRED_TEMPLATES if name.startswith(("privacy/", "region/privacy-contract"))}
100
+
101
+
79
102
  class InitError(Exception):
80
103
  """Expected initialization failure."""
81
104
 
@@ -84,6 +107,60 @@ class InitError(Exception):
84
107
  self.code = code
85
108
 
86
109
 
110
+ # ---------------------------------------------------------------- recovery (backup of replaced files)
111
+
112
+ def default_recovery_dir(label: str) -> Path:
113
+ """``~/.agent-pack/recovery/<UTC time>-agenthelm-<label>``: the place ``agenthelm update`` and ``migrate`` use."""
114
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
115
+ return Path.home() / ".agent-pack" / "recovery" / f"{stamp}-agenthelm-{label}"
116
+
117
+
118
+ def prepare_recovery_dir(root: Path, recovery_dir: Path | None, label: str) -> tuple[Path, bool]:
119
+ """The folder replaced files are copied to, ready for writing: ``(path, was_defaulted)``.
120
+
121
+ An explicit ``--recovery-dir`` wins; otherwise the default location is used, so nobody has to invent a backup
122
+ folder first. Either way it must be outside the project and writable. Callers resolve it *before* touching any
123
+ project file, so a backup folder that cannot be used leaves the project unchanged instead of skipping the backup.
124
+ """
125
+ defaulted = recovery_dir is None
126
+ target = (default_recovery_dir(label) if defaulted else recovery_dir.expanduser()).resolve()
127
+ if target == root or root in target.parents:
128
+ if defaulted:
129
+ raise InitError(_("默认恢复目录 {0} 在项目目录内,请用 --recovery-dir 指定项目外的目录").format(target))
130
+ raise InitError("--recovery-dir must be outside the project root")
131
+ try:
132
+ target.mkdir(parents=True, exist_ok=True, mode=0o700)
133
+ if not target.is_dir():
134
+ raise OSError(_("不是目录"))
135
+ with tempfile.TemporaryFile(dir=target):
136
+ pass
137
+ except OSError as exc:
138
+ raise InitError(_("恢复目录 {0} 无法创建或写入:{1}。项目文件没有改动;请检查权限,或用 --recovery-dir 指定其他项目外目录").format(target, exc),
139
+ code="recovery-unavailable") from exc
140
+ return target, defaulted
141
+
142
+
143
+ def backup_into(root: Path, recovery: Path, relative: Path) -> None:
144
+ """Copy ``root/relative`` to the same relative path under ``recovery`` (never overwriting an earlier copy)."""
145
+ archived = recovery / relative
146
+ if archived.exists():
147
+ raise InitError(f"recovery collision: {relative}")
148
+ archived.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
149
+ archived.write_bytes((root / relative).read_bytes())
150
+
151
+
152
+ def recovery_lines(result: dict) -> list[str]:
153
+ """Text lines telling the user where the originals went and how to get them back."""
154
+ recovery = result.get("recovery")
155
+ if not recovery or not result.get("applied"):
156
+ return []
157
+ files = [str(path) for path in result.get("recovery_files") or []]
158
+ lines = [_("被替换文件的原件已备份到:{0}").format(recovery)]
159
+ lines += [f" {path}" for path in files]
160
+ lines.append(_("还原:把备份目录里的文件按相同的相对路径复制回项目目录(cp -p <备份目录>/<文件> <项目目录>/<文件>)。"))
161
+ return lines
162
+
163
+
87
164
  @dataclass(frozen=True)
88
165
  class Inputs:
89
166
  project: Path
@@ -96,6 +173,8 @@ class Inputs:
96
173
  agent_cli: tuple[str, ...]
97
174
  work_mode: str = "case-workspace"
98
175
  entry_launcher: str | None = None
176
+ language: str = "zh"
177
+ privacy_declared: bool = True # Profile 的 privacy.forbidden_default_reads 非空;决定 AGENTS.md 的隐私约定写哪一版
99
178
 
100
179
 
101
180
  def split_csv(value: str) -> tuple[str, ...]:
@@ -120,14 +199,53 @@ def load_templates(path: Path = TEMPLATE_PATH) -> dict[str, str]:
120
199
  try:
121
200
  source = path.read_text(encoding="utf-8")
122
201
  except (OSError, UnicodeDecodeError) as exc:
123
- raise InitError(f"无法读取中文模板:{path}", code="template-invalid") from exc
202
+ raise InitError(_("无法读取中文模板:{0}").format(path), code="template-invalid") from exc
203
+ return parse_templates(source)
204
+
205
+
206
+ def parse_templates(source: str, *, historical: bool = False) -> dict[str, str]:
207
+ """Parse a template file. ``historical`` is for an earlier release's template (baseline rendering): the blocks added
208
+ after it shipped (the privacy convention) may be missing and render as empty."""
124
209
  templates = {match.group("name"): match.group("body") for match in TEMPLATE_PATTERN.finditer(source)}
125
- missing = sorted(REQUIRED_TEMPLATES - set(templates))
210
+ missing = sorted(REQUIRED_TEMPLATES - set(templates) - (PRIVACY_TEMPLATES if historical else set()))
126
211
  if missing:
127
- raise InitError("中文模板缺少生成区块:" + ", ".join(missing), code="template-invalid")
212
+ raise InitError(_("中文模板缺少生成区块:") + ", ".join(missing), code="template-invalid")
213
+ if historical:
214
+ for name in PRIVACY_TEMPLATES - set(templates):
215
+ templates[name] = ""
128
216
  return templates
129
217
 
130
218
 
219
+ def privacy_declared_in(profile: dict) -> bool:
220
+ """The Profile declares private paths: ``privacy.forbidden_default_reads`` holds at least one non-empty string."""
221
+ privacy = profile.get("privacy") if isinstance(profile.get("privacy"), dict) else {}
222
+ reads = privacy.get("forbidden_default_reads")
223
+ return isinstance(reads, list) and any(isinstance(item, str) and item.strip() for item in reads)
224
+
225
+
226
+ def localized(templates: dict[str, str], name: str, language: str) -> str:
227
+ """Template ``name`` in the project's file language; ``<name>.en`` for English, the Chinese one when there is none."""
228
+ return templates.get(f"{name}.en", templates[name]) if language == "en" else templates[name]
229
+
230
+
231
+ def privacy_section(templates: dict[str, str], language: str, declared: bool) -> str:
232
+ """AGENTS.md's privacy convention: it names the Profile field instead of copying the paths."""
233
+ return localized(templates, "privacy/declared" if declared else "privacy/undeclared", language).rstrip("\n")
234
+
235
+
236
+ def privacy_convention_state(text: str, templates: dict[str, str]) -> str:
237
+ """How an AGENTS.md carries the privacy convention.
238
+
239
+ ``declared`` / ``undeclared``: one of the template versions is in the text (either language, also inside the
240
+ managed region); ``custom``: the user wrote their own rule naming the field; ``absent``: nothing about it.
241
+ """
242
+ for state, name in (("declared", "privacy/declared"), ("undeclared", "privacy/undeclared")):
243
+ for language in ("zh", "en"):
244
+ if privacy_section(templates, language, state == "declared").strip() in text:
245
+ return state
246
+ return "custom" if "privacy.forbidden_default_reads" in text else "absent"
247
+
248
+
131
249
  def render_template(template: str, replacements: dict[str, str]) -> str:
132
250
  rendered = template
133
251
  for token, value in replacements.items():
@@ -147,9 +265,9 @@ def _read_manifest(path: Path) -> dict:
147
265
  try:
148
266
  manifest = json.loads(path.read_text(encoding="utf-8"))
149
267
  except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
150
- raise InitError(f"Plugin manifest 无法解析:{path}", code="runtime-required") from exc
268
+ raise InitError(_("Plugin manifest 无法解析:{0}").format(path), code="runtime-required") from exc
151
269
  if not isinstance(manifest, dict):
152
- raise InitError(f"Plugin manifest 根节点必须是对象:{path}", code="runtime-required")
270
+ raise InitError(_("Plugin manifest 根节点必须是对象:{0}").format(path), code="runtime-required")
153
271
  return manifest
154
272
 
155
273
 
@@ -205,9 +323,9 @@ def _agents_init_root(plugin_root: Path) -> Path:
205
323
  def validate_runtime(plugin_root: Path) -> dict[str, str | bool]:
206
324
  root = _agents_init_root(plugin_root)
207
325
  if not _is_regular_file(root / "plugin.json"):
208
- raise InitError(f"缺少 agents-init Plugin manifest:{root / 'plugin.json'}", code="runtime-required")
326
+ raise InitError(_("缺少 agents-init Plugin manifest:{0}").format(root / 'plugin.json'), code="runtime-required")
209
327
  if _read_manifest(root / "plugin.json").get("name") != "agents-init":
210
- raise InitError("Plugin manifest 必须声明 name=agents-init", code="runtime-required")
328
+ raise InitError(_("Plugin manifest 必须声明 name=agents-init"), code="runtime-required")
211
329
  missing: list[str] = []
212
330
  versions: dict[str, str] = {}
213
331
  for name, files in BUNDLED_PLUGINS.items():
@@ -218,11 +336,11 @@ def validate_runtime(plugin_root: Path) -> dict[str, str | bool]:
218
336
  missing.extend(f"{name}/{relative}" for relative in files if not _is_regular_file(companion / relative))
219
337
  manifest = _read_manifest(companion / "plugin.json")
220
338
  if manifest.get("name") != name:
221
- raise InitError(f"同包 Plugin manifest 必须声明 name={name}", code="runtime-required")
339
+ raise InitError(_("同包 Plugin manifest 必须声明 name={0}").format(name), code="runtime-required")
222
340
  versions[name] = str(manifest.get("version", ""))
223
341
  if missing:
224
342
  raise InitError(
225
- "缺少必需的 project-orchestrator / agent-pack / opinion-manager 文件:"
343
+ _("缺少必需的 project-orchestrator / agent-pack / opinion-manager 文件:")
226
344
  + ", ".join(missing),
227
345
  code="runtime-required",
228
346
  )
@@ -253,9 +371,9 @@ def read_legacy_profile(root: Path) -> dict | None:
253
371
  try:
254
372
  profile = json.loads(current.read_text(encoding="utf-8"))
255
373
  except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
256
- raise InitError(f"legacy profile 无法解析:{LEGACY_PROFILE_PATH}", code="profile-invalid") from exc
374
+ raise InitError(_("legacy profile 无法解析:{0}").format(LEGACY_PROFILE_PATH), code="profile-invalid") from exc
257
375
  if not isinstance(profile, dict) or profile.get("schema_version") != "1.0":
258
- raise InitError("legacy profile 必须是 schema_version=1.0 的对象", code="profile-invalid")
376
+ raise InitError(_("legacy profile 必须是 schema_version=1.0 的对象"), code="profile-invalid")
259
377
  return profile
260
378
 
261
379
 
@@ -275,12 +393,12 @@ def upgrade_legacy_profile(legacy: dict) -> dict:
275
393
 
276
394
  def configure_work_mode(profile: dict, mode: str | None) -> dict:
277
395
  if profile.get('work') is not None and not isinstance(profile['work'], dict):
278
- raise InitError('work 配置必须是对象', code='profile-invalid')
396
+ raise InitError(_('work 配置必须是对象'), code='profile-invalid')
279
397
  if mode is None:
280
398
  return profile
281
399
  work = dict(profile.get('work') or {})
282
400
  if any(work.get(key) is not None and not isinstance(work[key], dict) for key in ('task', 'case')):
283
- raise InitError('task/case 配置必须是对象或 null', code='profile-invalid')
401
+ raise InitError(_('task/case 配置必须是对象或 null'), code='profile-invalid')
284
402
  if mode == 'case-workspace':
285
403
  if work.get('task'):
286
404
  work['legacy_task'] = {**work['task'], 'mode': 'migrate-only'}
@@ -295,15 +413,15 @@ def configure_work_mode(profile: dict, mode: str | None) -> dict:
295
413
 
296
414
  def validate_inline(label: str, value: str) -> str:
297
415
  if not value.strip():
298
- raise InitError(f"{label} 不能为空")
416
+ raise InitError(_("{0} 不能为空").format(label))
299
417
  if len(value) > 512 or any(ord(character) < 32 for character in value):
300
- raise InitError(f"{label} 只能包含单行可打印文本")
418
+ raise InitError(_("{0} 只能包含单行可打印文本").format(label))
301
419
  return value.strip()
302
420
 
303
421
 
304
422
  def validate_entry_name(name: str) -> str:
305
423
  if not ENTRY_NAME_RE.fullmatch(name) or name in RESERVED_ENTRY_NAMES:
306
- raise InitError(f"启动器名称不合法:{name}(只能用字母、数字、. _ -,且不能与骨架文件同名)")
424
+ raise InitError(_("启动器名称不合法:{0}(只能用字母、数字、. _ -,且不能与骨架文件同名)").format(name))
307
425
  return name
308
426
 
309
427
 
@@ -311,33 +429,53 @@ def launcher_text() -> str:
311
429
  try:
312
430
  return LAUNCHER_TEMPLATE.read_text(encoding="utf-8")
313
431
  except (OSError, UnicodeDecodeError) as exc:
314
- raise InitError(f"无法读取启动器模板:{LAUNCHER_TEMPLATE}", code="template-invalid") from exc
432
+ raise InitError(_("无法读取启动器模板:{0}").format(LAUNCHER_TEMPLATE), code="template-invalid") from exc
315
433
 
316
434
 
317
435
  def entry_command(launcher: str | None) -> str:
318
436
  return f"./{launcher}" if launcher else "agenthelm project"
319
437
 
320
438
 
321
- def readme_block(launcher: str | None) -> str:
439
+ def readme_block(launcher: str | None, language: str = "zh") -> str:
440
+ """The README section that points at the project entry, written in the project's file language."""
322
441
  command = entry_command(launcher)
442
+ if language == "en":
443
+ return (f"{README_START}\n## How to use\n\nRun `{command}` in the project root to open the project menu: find files, see progress, "
444
+ f"read the project guide, check and maintain. No AI client is needed, only Python 3.11+; if the first run says the runtime is "
445
+ f"missing, install it once as prompted.\n\n"
446
+ f"You can also skip the menu: `{command} find <words>`, `{command} progress`, `{command} --help`.\n{README_END}\n")
323
447
  return (f"{README_START}\n## 怎样使用\n\n在项目根目录运行 `{command}` 打开项目菜单:找资料、看进展、项目指南、检查与维护。"
324
448
  f"不需要 AI 客户端,只需要 Python 3.11+;第一次运行如果提示缺少运行时,按提示安装一次即可。\n\n"
325
449
  f"不进菜单也可以:`{command} find 关键词`、`{command} progress`、`{command} --help`。\n{README_END}\n")
326
450
 
327
451
 
452
+ def file_language(args: argparse.Namespace) -> str:
453
+ """The language a new project's files are written in: --language, else the UI language at init time (migrate keeps zh)."""
454
+ if getattr(args, "language", "auto") in ("zh", "en"):
455
+ return args.language
456
+ return "zh" if args.mode == "migrate" else resolve_language()
457
+
458
+
459
+ def project_language(profile: dict) -> str:
460
+ """The language of a project's generated files: the Profile's ``language``, ``zh`` for projects that predate it."""
461
+ return profile.get("language") if profile.get("language") in ("zh", "en") else "zh"
462
+
463
+
328
464
  def tracked_paths(pack: dict | None, launcher: str | None) -> list[Path]:
329
465
  """Files the content lock follows: the pack's fixed list plus this project's launcher."""
330
466
  tracked = [Path(path) for path in (pack or {}).get("materializes", [])]
331
467
  return tracked + ([Path(launcher)] if launcher else [])
332
468
 
333
469
 
334
- def files_for(inputs: Inputs, templates: dict[str, str] | None = None) -> dict[Path, str]:
470
+ def files_for(inputs: Inputs, templates: dict[str, str] | None = None, launcher: str | None = None) -> dict[Path, str]:
471
+ """``launcher`` is the launcher script text; omitted, the one shipped with this plugin."""
335
472
  templates = templates or load_templates()
336
473
  profile = {
337
474
  "$schema": PROFILE_SCHEMA,
338
475
  "schema_version": "1.0",
339
476
  "initializer_version": INITIALIZER_VERSION,
340
477
  "name": inputs.name,
478
+ "language": inputs.language,
341
479
  "profile": {
342
480
  "project_type": list(inputs.project_type),
343
481
  "vcs": inputs.vcs,
@@ -359,6 +497,7 @@ def files_for(inputs: Inputs, templates: dict[str, str] | None = None) -> dict[P
359
497
  "check_command": None,
360
498
  "policy": None,
361
499
  },
500
+ "sop": {"root": "sops"},
362
501
  "capabilities": {
363
502
  "plugin_roots": [".agents"],
364
503
  "plugin_dirs": [],
@@ -376,7 +515,7 @@ def files_for(inputs: Inputs, templates: dict[str, str] | None = None) -> dict[P
376
515
  "case": {"root": "cases", "artifact_mode": "case-local"}
377
516
  if inputs.work_mode == "case-workspace" else None,
378
517
  },
379
- "privacy": {"forbidden_default_reads": [], "generated_outputs": []},
518
+ "privacy": {"forbidden_default_reads": ["private/"], "generated_outputs": []},
380
519
  }
381
520
  if inputs.entry_launcher:
382
521
  profile["entry"] = {"api": ENTRY_API, "launcher": inputs.entry_launcher}
@@ -390,13 +529,15 @@ def files_for(inputs: Inputs, templates: dict[str, str] | None = None) -> dict[P
390
529
  "RUNTIME": inputs.runtime,
391
530
  "AGENT_CLI": ", ".join(inputs.agent_cli),
392
531
  }
532
+ replacements["PRIVACY_SECTION"] = privacy_section(templates, inputs.language, inputs.privacy_declared)
533
+ replacements["PRIVACY_RULES_LINE"] = localized(templates, "privacy/rules-line", inputs.language).rstrip("\n")
393
534
  agents = render_template(templates["AGENTS.md"], replacements)
394
535
  route = render_template(templates["ROUTE.md"], replacements)
395
536
  files = {
396
537
  Path("AGENTS.md"): agents,
397
538
  Path("AGENT.RULES.md"): render_template(templates["AGENT.RULES.md"], replacements),
398
539
  Path("OPINION.md"): render_template(templates["OPINION.md"], replacements),
399
- Path("CLAUDE.md"): route,
540
+ Path("CLAUDE.md"): render_template(templates["CLAUDE.md"], replacements),
400
541
  Path("AGENT.md"): route,
401
542
  Path(".agents/plugin.json"): json_text({
402
543
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
@@ -414,13 +555,15 @@ def files_for(inputs: Inputs, templates: dict[str, str] | None = None) -> dict[P
414
555
  Path(".agent-doc/progress.md"): render_template(templates[".agent-doc/progress.md"], replacements),
415
556
  Path(".agent-doc/chat-summary.md"): render_template(templates[".agent-doc/chat-summary.md"], replacements),
416
557
  Path("memory/.gitkeep"): "",
558
+ Path("sops/.gitkeep"): "",
559
+ Path("private/.gitignore"): PRIVATE_IGNORE,
417
560
  Path("docs/refs/README.md"): render_template(templates["docs/refs/README.md"], replacements),
418
561
  Path("docs/drafts/.gitkeep"): "",
419
562
  }
420
563
  if inputs.work_mode == "case-workspace":
421
564
  files[Path("cases/.gitkeep")] = ""
422
565
  if inputs.entry_launcher:
423
- files[Path(inputs.entry_launcher)] = launcher_text()
566
+ files[Path(inputs.entry_launcher)] = launcher if launcher is not None else launcher_text()
424
567
  return files
425
568
 
426
569
 
@@ -571,19 +714,14 @@ def apply_migration(
571
714
  replace: Iterable[Path],
572
715
  recovery_dir: Path | None,
573
716
  retire: Iterable[Path] = (),
574
- ) -> None:
717
+ ) -> Path | None:
718
+ """Write the migration; replaced and retired files are moved to the recovery folder first. Returns that folder."""
575
719
  create_paths = list(create)
576
720
  replace_paths = list(replace)
577
721
  retire_paths = list(retire)
578
- if (replace_paths or retire_paths) and recovery_dir is None:
579
- raise InitError("--recovery-dir is required when --replace is used or a legacy profile is retired")
580
- recovery = recovery_dir.expanduser().resolve() if recovery_dir is not None else None
581
- if recovery is not None:
582
- if recovery == root or root in recovery.parents:
583
- raise InitError("--recovery-dir must be outside the project root")
584
- recovery.mkdir(parents=True, exist_ok=True, mode=0o700)
585
- if recovery.is_symlink() or not recovery.is_dir():
586
- raise InitError("--recovery-dir must be a real directory")
722
+ recovery: Path | None = None
723
+ if replace_paths or retire_paths or recovery_dir is not None:
724
+ recovery, _defaulted = prepare_recovery_dir(root, recovery_dir, "migrate")
587
725
  conflicts = [path for path in [*replace_paths, *retire_paths] if (recovery / path).exists()]
588
726
  if conflicts:
589
727
  raise InitError("recovery collision: " + ", ".join(str(path) for path in conflicts))
@@ -625,6 +763,7 @@ def apply_migration(
625
763
  raise InitError(f"migration rolled back after write failure: {exc}") from exc
626
764
  finally:
627
765
  os.close(root_fd)
766
+ return recovery
628
767
 
629
768
 
630
769
  def contract_pack(plugin_root: Path = PLUGIN_ROOT) -> dict | None:
@@ -651,8 +790,21 @@ def content_baseline(pack: dict | None, files: dict[Path, str], written: Iterabl
651
790
  }
652
791
 
653
792
 
654
- def write_content_lock(root: Path, pack: dict, baseline: dict[str, str]) -> None:
655
- """Merge this run's baseline into the project's content lock, atomically."""
793
+ def render_inputs(inputs: Inputs) -> dict:
794
+ """The inputs a project's template files were rendered with; with the pack version they rebuild the baseline."""
795
+ return {"name": inputs.name, "slug": inputs.slug, "project_type": list(inputs.project_type), "vcs": inputs.vcs,
796
+ "stack": list(inputs.stack), "runtime": inputs.runtime, "agent_cli": list(inputs.agent_cli),
797
+ "work_mode": inputs.work_mode, "entry_launcher": inputs.entry_launcher, "language": inputs.language,
798
+ "privacy_declared": inputs.privacy_declared}
799
+
800
+
801
+ def write_content_lock(root: Path, pack: dict, baseline: dict[str, str], *, inputs: Inputs | None = None,
802
+ regions: dict[str, dict[str, str]] | None = None) -> None:
803
+ """Merge this run's baseline into the project's content lock, atomically.
804
+
805
+ ``regions`` maps a file to ``{region id: body digest}`` for blocks this tool manages inside a file the user
806
+ owns; ``render_inputs`` records what the templates were rendered with. Keys the lock already has stay.
807
+ """
656
808
  path = root / CONTENT_LOCK_PATH
657
809
  for parent in [*reversed(CONTENT_LOCK_PATH.parents[:-1])]:
658
810
  if (root / parent).is_symlink():
@@ -664,14 +816,20 @@ def write_content_lock(root: Path, pack: dict, baseline: dict[str, str]) -> None
664
816
  try:
665
817
  lock = json.loads(path.read_text(encoding="utf-8"))
666
818
  except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
667
- raise InitError(f"content lock 无法解析:{CONTENT_LOCK_PATH}", code="profile-invalid") from exc
819
+ raise InitError(_("content lock 无法解析:{0}").format(CONTENT_LOCK_PATH), code="profile-invalid") from exc
668
820
  entry = lock.setdefault("packs", {}).get(pack["id"], {})
669
821
  files = {**entry.get("files", {}), **baseline}
670
- lock["packs"][pack["id"]] = {"plugin": "agents-init", "version": pack["version"], "files": dict(sorted(files.items()))}
822
+ updated = {**entry, "plugin": "agents-init", "version": pack["version"], "files": dict(sorted(files.items()))}
823
+ if inputs is not None:
824
+ updated["render_inputs"] = render_inputs(inputs)
825
+ if regions:
826
+ merged = {path_: dict(ids) for path_, ids in (entry.get("regions") or {}).items()}
827
+ for path_, ids in regions.items():
828
+ merged[path_] = {**merged.get(path_, {}), **ids}
829
+ updated["regions"] = dict(sorted(merged.items()))
830
+ lock["packs"][pack["id"]] = updated
671
831
  path.parent.mkdir(parents=True, exist_ok=True)
672
- temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
673
- temporary.write_text(json_text(lock), encoding="utf-8")
674
- os.replace(temporary, path)
832
+ _atomic_write(path, json_text(lock))
675
833
 
676
834
 
677
835
  def _read_project_json(root: Path, relative: Path, label: str) -> dict:
@@ -681,11 +839,11 @@ def _read_project_json(root: Path, relative: Path, label: str) -> dict:
681
839
  try:
682
840
  data = json.loads(path.read_text(encoding="utf-8"))
683
841
  except FileNotFoundError as exc:
684
- raise InitError(f"缺少 {relative}", code="refresh-unavailable") from exc
842
+ raise InitError(_("缺少 {0}").format(relative), code="refresh-unavailable") from exc
685
843
  except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
686
- raise InitError(f"{label} 无法解析:{relative}", code="profile-invalid") from exc
844
+ raise InitError(_("{0} 无法解析:{1}").format(label, relative), code="profile-invalid") from exc
687
845
  if not isinstance(data, dict):
688
- raise InitError(f"{label} 根节点必须是对象", code="profile-invalid")
846
+ raise InitError(_("{0} 根节点必须是对象").format(label), code="profile-invalid")
689
847
  return data
690
848
 
691
849
 
@@ -706,6 +864,8 @@ def inputs_from_profile(root: Path) -> Inputs:
706
864
  tuple(details.get("agent_cli") or ()),
707
865
  str((profile.get("work") or {}).get("mode") or "legacy"),
708
866
  _profile_launcher(profile),
867
+ project_language(profile),
868
+ privacy_declared_in(profile),
709
869
  )
710
870
 
711
871
 
@@ -726,26 +886,197 @@ def _scaffold():
726
886
  return scaffold
727
887
 
728
888
 
729
- def _unified_diff(relative: str, current: str, new: str, limit: int = 200) -> str:
889
+ def _unified_diff(relative: str, current: str, new: str, limit: int | None = 200) -> str:
730
890
  lines = list(difflib.unified_diff(
731
891
  current.splitlines(keepends=True), new.splitlines(keepends=True),
732
892
  fromfile=f"a/{relative}", tofile=f"b/{relative}",
733
893
  ))
734
- if len(lines) > limit:
894
+ if limit is not None and len(lines) > limit:
735
895
  lines = lines[:limit] + [f"... ({len(lines) - limit} more diff lines)\n"]
736
896
  return "".join(lines)
737
897
 
738
898
 
899
+ # 保留本地内容、只追加带标记区块的文件 → 区块 ID(模板里的 region/<ID>)。
900
+ # AGENTS.md 的 agents-contract 区块已随 rc.1 发布,正文语义不变;隐私约定是独立的 privacy-contract 区块。
901
+ APPEND_REGIONS = {Path("AGENTS.md"): ("agents-contract", "privacy-contract"), Path("CLAUDE.md"): ("claude-import",)}
902
+ CLAUDE_IMPORT_RE = re.compile(r"^\s*@(?:\./)?AGENTS\.md\s*$", re.MULTILINE)
903
+
904
+
905
+ def line_delta(current: str, new: str) -> tuple[int, int]:
906
+ """(lines the new text adds, lines of the current text it would drop)."""
907
+ added = lost = 0
908
+ matcher = difflib.SequenceMatcher(None, current.splitlines(), new.splitlines(), autojunk=False)
909
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
910
+ if tag != "equal":
911
+ lost += i2 - i1
912
+ added += j2 - j1
913
+ return added, lost
914
+
915
+
916
+ def _regions():
917
+ here = str(Path(__file__).resolve().parent)
918
+ if here not in sys.path:
919
+ sys.path.insert(0, here)
920
+ import regions # noqa: PLC0415
921
+
922
+ return regions
923
+
924
+
925
+ def _baseline():
926
+ here = str(Path(__file__).resolve().parent)
927
+ if here not in sys.path:
928
+ sys.path.insert(0, here)
929
+ import baseline # noqa: PLC0415
930
+
931
+ return baseline
932
+
933
+
934
+ def _merge3():
935
+ here = str(Path(__file__).resolve().parent)
936
+ if here not in sys.path:
937
+ sys.path.insert(0, here)
938
+ import merge3 # noqa: PLC0415
939
+
940
+ return merge3
941
+
942
+
943
+ def baseline_providers() -> list:
944
+ """Where historical content packs come from (runtime cache, local git tags, GitHub Release); tests replace this."""
945
+ return _baseline().default_providers()
946
+
947
+
948
+ def _inputs_from_lock(root: Path, recorded: object, fallback: Inputs) -> Inputs:
949
+ """The inputs recorded in the content lock; the Profile's when the lock has none or they do not fit."""
950
+ if not isinstance(recorded, dict):
951
+ return fallback
952
+ try:
953
+ return Inputs(root, str(recorded["name"]), str(recorded["slug"]), tuple(recorded["project_type"]), str(recorded["vcs"]),
954
+ tuple(recorded["stack"]), str(recorded["runtime"]), tuple(recorded["agent_cli"]),
955
+ str(recorded.get("work_mode") or "legacy"), recorded.get("entry_launcher") or None,
956
+ str(recorded.get("language") or "zh"),
957
+ recorded["privacy_declared"] if isinstance(recorded.get("privacy_declared"), bool) else fallback.privacy_declared)
958
+ except (KeyError, TypeError):
959
+ return fallback
960
+
961
+
962
+ def find_baseline(root: Path, relative: Path, digest: str, versions: list[str], recorded: object, current: Inputs,
963
+ providers: list, pack_id: str) -> dict | None:
964
+ """Re-render ``relative`` as an earlier content pack did and return it only if it hashes to ``digest``.
965
+
966
+ ``digest`` is what the content lock recorded when the file was written, so a match proves the text is exactly the
967
+ baseline; a wrong guess (another pack version, other inputs) never matches and is skipped.
968
+ """
969
+ start = _inputs_from_lock(root, recorded, current)
970
+ variants = [start, dataclasses.replace(start, privacy_declared=not start.privacy_declared)]
971
+ seen: set[tuple[str, str]] = set()
972
+ for provider in providers:
973
+ try:
974
+ for source in provider(pack_id, versions):
975
+ if (source.kind, source.label) in seen:
976
+ continue
977
+ seen.add((source.kind, source.label))
978
+ try:
979
+ templates = parse_templates(source.template, historical=True)
980
+ for variant in variants:
981
+ text = files_for(variant, templates, source.launcher).get(relative)
982
+ if text is not None and hashlib.sha256(text.encode("utf-8")).hexdigest() == digest:
983
+ return {"text": text, "source": source.label, "kind": source.kind, "version": source.version}
984
+ except (InitError, KeyError, ValueError):
985
+ continue
986
+ except (OSError, ValueError):
987
+ continue
988
+ return None
989
+
990
+
991
+ def _refresh_notes(item: dict) -> list[str]:
992
+ """Human lines for a file refresh cannot silently decide: why, what each choice costs, what to type."""
993
+ path, reason = item["path"], item.get("reason")
994
+ notes: list[str] = []
995
+ if reason == "baseline-unavailable":
996
+ notes.append(_("找不到这个文件升级前的基线(旧版本包不在本机运行时缓存和本地 git tag 里,也没能从 GitHub Release 取得),无法三方合并;"
997
+ "没有改动任何文件,请改用 --keep / --append / --accept 选择"))
998
+ elif reason == "merge-conflict":
999
+ numbers = ", ".join(str(number) for number in item["merge"]["unresolved"])
1000
+ notes.append(_("有 {0} 处冲突需要你选择(第 {1} 块):--pick {2}#<序号>=mine|theirs|both"
1001
+ "(mine 保留你的、theirs 取新模板、both 两边都留)").format(len(item["merge"]["unresolved"]), numbers, path))
1002
+ elif reason == "no-baseline" and item.get("merge_requested"):
1003
+ notes.append(_("内容锁里没有它的基线,无法三方合并;请改用 --keep / --append / --accept 选择"))
1004
+ if item["action"] == "merge":
1005
+ merge = item["merge"]
1006
+ notes.append(_("三方合并:新模板的变化已并入你的版本(自动合并 {0} 处,冲突 {1} 处均已选择;基线取自 {2});写入前先备份").format(
1007
+ merge["auto_hunks"], len(merge["conflicts"]), merge["source"]))
1008
+ if reason == "symlink":
1009
+ notes.append(_("{0} 是指向 {1} 的符号链接,refresh 不跟随链接改写,保留原样").format(path, item.get("link")))
1010
+ if item["action"] == "blocked":
1011
+ notes.append(_("确认后用 --keep {0} 记为保留(之后不再追问);要让模板接管请先把它换成普通文件").format(path))
1012
+ elif reason == "no-baseline":
1013
+ notes.append(_("内容锁里没有它的基线(早期版本初始化的项目),无法判断是你改过还是模板变了;建议先保留你的版本:--keep {0}").format(path))
1014
+ elif reason == "edited":
1015
+ notes.append(_("你改过这个文件,新模板也变了"))
1016
+ if item["action"] == "blocked" and not item.get("merge_requested"):
1017
+ notes.append(_("也可以三方合并(用旧版本包还原出升级前的基线,保留你的改动并带入新模板的变化):--merge {0}").format(path))
1018
+ elif reason == "discard-unconfirmed":
1019
+ notes.append(_("--accept 会丢弃 {0} 行本地内容;确认后追加 --confirm-discard {1}").format(item["lines_lost"], path))
1020
+ if "local_lines" in item and item["action"] in {"blocked", "replace"}:
1021
+ notes.append(_("本地 {0} 行,新模板 {1} 行;采用新模板会新增 {2} 行、丢弃 {3} 行本地内容").format(
1022
+ item["local_lines"], item["template_lines"], item["lines_added"], item["lines_lost"]))
1023
+ if item["action"] == "blocked" and Path(path) in APPEND_REGIONS:
1024
+ notes.append(_("也可以保留你的内容并追加带标记的区块(原文不动):--append {0}").format(path))
1025
+ if item["action"] == "blocked":
1026
+ notes.append(_("先看差异:--diff {0}").format(path))
1027
+ if item["action"] == "append":
1028
+ notes.append(_("保留你的内容,末尾追加带标记的区块({0} 行,原文不动,先备份)").format(item["append_lines"]))
1029
+ if reason == "already-present":
1030
+ notes.append(_("已经导入或带有这个区块,无需追加"))
1031
+ return notes
1032
+
1033
+
1034
+ def _symlink_item(path: Path, relative: Path, new: str, new_digest: str, keep: set[Path], kept_before: dict) -> dict:
1035
+ """A tracked file that is a symbolic link: never written through. Same text as the new render → unchanged;
1036
+ kept explicitly or by an earlier decision → keep; otherwise blocked until the user says --keep."""
1037
+ link = os.readlink(path)
1038
+ try:
1039
+ resolved = path.read_text(encoding="utf-8") if path.is_file() else None
1040
+ except (OSError, UnicodeDecodeError):
1041
+ resolved = None
1042
+ if resolved is not None and hashlib.sha256(resolved.encode("utf-8")).hexdigest() == new_digest:
1043
+ state, action, reason = "unchanged", "keep", None
1044
+ elif relative in keep or kept_before.get(relative.as_posix()) == new_digest:
1045
+ state, action, reason = "symlink", "keep", "symlink"
1046
+ else:
1047
+ state, action, reason = "symlink", "blocked", "symlink"
1048
+ item = {"path": relative.as_posix(), "state": state, "action": action, "new_sha256": new_digest, "link": link}
1049
+ if reason:
1050
+ item["reason"] = reason
1051
+ return item
1052
+
1053
+
1054
+ def _parse_picks(values: list[str], merge: set[Path]) -> dict[Path, dict[int, str]]:
1055
+ """``--pick 文件#序号=mine|theirs|both`` → {文件: {序号: 选择}}。"""
1056
+ picks: dict[Path, dict[int, str]] = {}
1057
+ for value in values:
1058
+ target, _sep, choice = value.rpartition("=")
1059
+ name, _hash, number = target.rpartition("#")
1060
+ if not _sep or not _hash or not number.isdigit() or choice not in ("mine", "theirs", "both"):
1061
+ raise InitError(_("--pick 的写法是 <文件>#<冲突块序号>=mine|theirs|both:{0}").format(value))
1062
+ relative = Path(name)
1063
+ if relative not in merge:
1064
+ raise InitError(_("--pick 只能用于同时带 --merge 的文件:{0}").format(name))
1065
+ picks.setdefault(relative, {})[int(number)] = choice
1066
+ return picks
1067
+
1068
+
739
1069
  def refresh_project(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
740
1070
  """Re-render the tracked template files after a content pack update.
741
1071
 
742
- Files still identical to their install-time baseline are replaced; files the
743
- user edited are only replaced with --accept or kept with --keep. Every
744
- replaced file is copied to --recovery-dir first.
1072
+ Files still identical to their install-time baseline are replaced; files the user edited are only replaced
1073
+ with --accept (and, when that drops local lines, --confirm-discard), kept with --keep, or kept with a marked
1074
+ region appended to them with --append (AGENTS.md and CLAUDE.md). Every file the command changes is copied to
1075
+ the recovery folder first.
745
1076
  """
746
1077
  pack = contract_pack()
747
1078
  if pack is None:
748
- raise InitError("当前 agents-init 未声明可刷新的内容包", code="refresh-unavailable")
1079
+ raise InitError(_("当前 agents-init 未声明可刷新的内容包"), code="refresh-unavailable")
749
1080
  try:
750
1081
  lock = _read_project_json(root, CONTENT_LOCK_PATH, "content lock")
751
1082
  except InitError as exc:
@@ -756,26 +1087,55 @@ def refresh_project(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
756
1087
  # every file that differs from the new render counts as locally modified.
757
1088
  entry = (lock.get("packs") or {}).get(pack["id"]) or {}
758
1089
  baseline: dict[str, str] = dict(entry.get("files") or {})
1090
+ file_versions: dict[str, str] = dict(entry.get("file_versions") or {}) # 文件基线是哪个内容包版本渲染的(未更新的文件仍是旧版本)
759
1091
  inputs = inputs_from_profile(root)
760
1092
  rendered = files_for(inputs)
761
1093
  accept = {Path(value) for value in args.accept}
762
1094
  keep = {Path(value) for value in args.keep}
1095
+ append = {Path(value) for value in getattr(args, "append", [])}
1096
+ confirm = {Path(value) for value in getattr(args, "confirm_discard", [])}
1097
+ show_diff = {Path(value) for value in getattr(args, "diff", [])}
1098
+ merge = {Path(value) for value in getattr(args, "merge", [])}
1099
+ picks = _parse_picks(getattr(args, "pick", []), merge)
763
1100
  tracked = tracked_paths(pack, inputs.entry_launcher)
764
- unknown = (accept | keep) - set(tracked)
1101
+ unknown = (accept | keep | append | confirm | show_diff | merge) - set(tracked)
765
1102
  if unknown:
766
- raise InitError("不是内容包跟踪的文件:" + ", ".join(sorted(map(str, unknown))))
767
- if accept & keep:
768
- raise InitError("同一文件不能同时 --accept 与 --keep:" + ", ".join(sorted(map(str, accept & keep))))
1103
+ raise InitError(_("不是内容包跟踪的文件:") + ", ".join(sorted(map(str, unknown))))
1104
+ chosen_twice = (accept & keep) | (accept & append) | (keep & append) | (merge & (accept | keep | append))
1105
+ if chosen_twice:
1106
+ raise InitError(_("同一文件只能选一种处理(--accept / --keep / --append / --merge):") + ", ".join(sorted(map(str, chosen_twice))))
1107
+ not_appendable = append - set(APPEND_REGIONS)
1108
+ if not_appendable:
1109
+ raise InitError(_("只有 AGENTS.md 和 CLAUDE.md 可以追加受管区块:") + ", ".join(sorted(map(str, not_appendable))))
1110
+ if show_diff and args.apply:
1111
+ raise InitError(_("--diff 只用于查看,不能与 --apply 同用"))
1112
+ templates = load_templates()
1113
+ regions = _regions()
1114
+ merge3 = _merge3() if merge else None
1115
+ providers = baseline_providers() if merge else []
769
1116
  plan: list[dict] = []
1117
+ merged_texts: dict[Path, str] = {}
770
1118
  kept_before = _scaffold().keep_fingerprints(root)
771
1119
  for relative in tracked:
772
1120
  new = rendered[relative]
773
1121
  new_digest = hashlib.sha256(new.encode("utf-8")).hexdigest()
774
1122
  path = root / relative
775
1123
  if path.is_symlink():
776
- raise InitError(f"refusing symlinked file: {relative}")
1124
+ # 契约文件是符号链接(常见:CLAUDE.md → AGENTS.md):refresh 不跟随链接改写,逐项处置,不拖垮其他文件。
1125
+ if relative in accept | append | merge:
1126
+ raise InitError(_("{0} 是指向 {1} 的符号链接,refresh 不跟随链接改写,不能用 --accept / --append / --merge;"
1127
+ "要保留请用 --keep {0},要让模板接管请先把它换成普通文件").format(relative, os.readlink(path)))
1128
+ item = _symlink_item(path, relative, new, new_digest, keep, kept_before)
1129
+ if relative in show_diff:
1130
+ item["diff"] = ""
1131
+ item["note"] = _refresh_notes(item)
1132
+ plan.append(item)
1133
+ continue
777
1134
  current = path.read_text(encoding="utf-8") if path.is_file() else None
778
1135
  current_digest = hashlib.sha256(current.encode("utf-8")).hexdigest() if current is not None else None
1136
+ added, lost = line_delta(current or "", new)
1137
+ reason = None
1138
+ merge_info = None
779
1139
  if current_digest == new_digest:
780
1140
  state, action = "unchanged", "keep"
781
1141
  elif current is None:
@@ -783,21 +1143,106 @@ def refresh_project(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
783
1143
  action = "create" if relative in accept else "skip"
784
1144
  elif new_digest == baseline.get(relative.as_posix()):
785
1145
  # The new template renders this file exactly as before; the user's edits stay untouched.
786
- state, action = "local-only", "keep"
1146
+ state, action = "local-only", "append" if relative in append else "keep"
787
1147
  elif current_digest == baseline.get(relative.as_posix()):
788
1148
  state, action = "clean", "keep" if relative in keep else "replace"
789
1149
  else:
790
1150
  state = "modified"
791
1151
  decided = kept_before.get(relative.as_posix()) == new_digest # 之前选过保留,且期望内容没变
792
- action = "replace" if relative in accept else "keep" if relative in keep or decided else "blocked"
793
- if decided and relative not in accept:
1152
+ reason = "edited" if relative.as_posix() in baseline else "no-baseline"
1153
+ if relative in merge:
1154
+ action = "blocked"
1155
+ merge_info = {}
1156
+ found = None
1157
+ if reason == "edited":
1158
+ wanted = [version for version in (file_versions.get(relative.as_posix()), entry.get("version"))
1159
+ if version and version != UNKNOWN_PACK_VERSION]
1160
+ found = find_baseline(root, relative, baseline[relative.as_posix()], list(dict.fromkeys(wanted)),
1161
+ entry.get("render_inputs"), inputs, providers, pack["id"])
1162
+ if found is None:
1163
+ reason = "baseline-unavailable"
1164
+ if found is not None:
1165
+ merged = merge3.merge_text(found["text"], current, new)
1166
+ chosen = picks.get(relative, {})
1167
+ open_blocks = [block.number for block in merged.unresolved(chosen)]
1168
+ merged_texts[relative] = merged.render(chosen, (_("你的版本"), _("基线"), _("新模板")))
1169
+ merge_info = {"source": found["source"], "baseline_version": found["version"], "auto_hunks": merged.auto_hunks,
1170
+ "conflicts": [{"id": block.number, "mine": "".join(block.mine), "theirs": "".join(block.theirs),
1171
+ "base": "".join(block.base), "pick": chosen.get(block.number)}
1172
+ for block in merged.conflicts],
1173
+ "unresolved": open_blocks}
1174
+ if open_blocks:
1175
+ reason = "merge-conflict"
1176
+ else:
1177
+ action, reason = "merge", None
1178
+ elif relative in accept:
1179
+ action = "replace"
1180
+ if lost and relative not in confirm:
1181
+ action, reason = "blocked", "discard-unconfirmed"
1182
+ elif relative in append:
1183
+ action = "append"
1184
+ elif relative in keep or decided:
1185
+ action = "keep"
1186
+ else:
1187
+ action = "blocked"
1188
+ if decided and relative not in accept and relative not in merge:
794
1189
  state = "kept-by-decision"
795
1190
  item = {"path": relative.as_posix(), "state": state, "action": action, "new_sha256": new_digest}
796
- if action in {"replace", "blocked", "create"} or (state == "clean" and action == "keep"):
797
- item["diff"] = _unified_diff(relative.as_posix(), current or "", new)
1191
+ if reason:
1192
+ item["reason"] = reason
1193
+ if relative in merge:
1194
+ item["merge_requested"] = True
1195
+ if merge_info:
1196
+ item["merge"] = merge_info
1197
+ if current is not None and current_digest != new_digest:
1198
+ item.update(local_lines=len(current.splitlines()), template_lines=len(new.splitlines()),
1199
+ lines_added=added, lines_lost=lost)
1200
+ appended_text = None
1201
+ if item["action"] == "append":
1202
+ wanted, appended = [], current or ""
1203
+ for region_id in APPEND_REGIONS[relative]:
1204
+ if region_id == "privacy-contract" and (
1205
+ not inputs.privacy_declared or privacy_convention_state(appended, templates) in ("declared", "custom")):
1206
+ continue # 没有声明私有路径,或文件里已有这条约定(模板原文或用户自己写的):不追加
1207
+ body = localized(templates, f"region/{region_id}", inputs.language)
1208
+ existing = regions.get(appended, region_id)
1209
+ if (existing is not None and existing.intact and existing.body == regions.normalize(body)) \
1210
+ or (region_id == "claude-import" and CLAUDE_IMPORT_RE.search(appended)):
1211
+ continue
1212
+ appended, region_state = regions.upsert(appended, region_id, body)
1213
+ if region_state == "modified":
1214
+ raise InitError(_("{0} 里的受管区块 {1} 被你改过:用 --mode region 处理").format(relative, region_id))
1215
+ wanted.append((region_id, body))
1216
+ if not wanted:
1217
+ item["action"], item["reason"] = "keep", "already-present"
1218
+ else:
1219
+ item.update(region=wanted[0][0], regions=[region_id for region_id, _body in wanted],
1220
+ append_lines=sum(len(regions.render(region_id, body).splitlines()) for region_id, body in wanted))
1221
+ appended_text = appended
1222
+ if item["action"] in {"replace", "blocked", "create", "append"} or (state == "clean" and item["action"] == "keep") \
1223
+ or relative in show_diff or merge_info:
1224
+ shown = appended_text if appended_text is not None else merged_texts.get(relative, new)
1225
+ item["diff"] = _unified_diff(relative.as_posix(), current or "", shown,
1226
+ None if relative in show_diff else 200)
1227
+ item["note"] = _refresh_notes(item)
798
1228
  plan.append(item)
1229
+ satisfied = {item["path"] for item in plan if item["action"] == "append" or item.get("reason") == "already-present"}
1230
+ unmet = sorted(path.as_posix() for path in append if path.as_posix() not in satisfied)
1231
+ if unmet:
1232
+ raise InitError(_("没有本地改动,不需要追加区块:") + ", ".join(unmet))
1233
+ not_modified = sorted(item["path"] for item in plan if Path(item["path"]) in merge and item["state"] != "modified")
1234
+ if not_modified:
1235
+ raise InitError(_("没有需要合并的本地改动(文件没改过,或已与新模板一致):") + ", ".join(not_modified))
799
1236
  blocked = [item["path"] for item in plan if item["action"] == "blocked"]
800
- replacing = [Path(item["path"]) for item in plan if item["action"] == "replace"]
1237
+ replacing = [Path(item["path"]) for item in plan if item["action"] in {"replace", "append", "merge"}]
1238
+ for relative, chosen in picks.items():
1239
+ item = next(item for item in plan if item["path"] == relative.as_posix())
1240
+ if "merge" not in item:
1241
+ continue # 取不到基线:整个文件退回 --keep / --append / --accept 的选择
1242
+ known = {block["id"] for block in item["merge"]["conflicts"]}
1243
+ if set(chosen) - known:
1244
+ raise InitError(_("--pick 指向的冲突块不存在:{0}#{1}(先用 --merge {0} 查看冲突块序号)").format(
1245
+ relative, ", ".join(str(number) for number in sorted(set(chosen) - known) or [0])))
801
1246
  result = {
802
1247
  "ok": not blocked,
803
1248
  "mode": "refresh",
@@ -807,75 +1252,118 @@ def refresh_project(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
807
1252
  "files": plan,
808
1253
  "blocked": blocked,
809
1254
  }
1255
+ if show_diff:
1256
+ result["diffs"] = {path.as_posix(): next(item["diff"] for item in plan if item["path"] == path.as_posix()) for path in sorted(show_diff)}
810
1257
  if blocked:
811
- result["hint"] = "本地已改动的文件需逐个选择:--accept <文件> 用新模板替换(先备份),或 --keep <文件> 保留本地"
812
- if not args.apply or blocked:
1258
+ hints = []
1259
+ if any(item.get("reason") in {"no-baseline", "edited", "baseline-unavailable", "symlink"} for item in plan if item["action"] == "blocked"):
1260
+ hints.append(_("本地已改动的文件需逐个选择:--keep <文件> 保留你的版本(建议);--append <文件> 保留并追加带标记的区块(仅 AGENTS.md / CLAUDE.md);"
1261
+ "--accept <文件> 用新模板替换(先备份,会丢弃本地内容,需再加 --confirm-discard <文件>);--diff <文件> 先看差异"))
1262
+ if any(item.get("reason") == "discard-unconfirmed" for item in plan):
1263
+ hints.append(_("--accept 会丢弃本地内容:确认后追加 --confirm-discard <文件>"))
1264
+ result["hint"] = "\n".join(hints)
1265
+ if not args.apply or blocked or show_diff:
813
1266
  return (0 if not blocked else 1), result
814
- if replacing and args.recovery_dir is None:
815
- raise InitError("--recovery-dir is required when refresh replaces files")
816
1267
  if replacing:
817
- recovery = args.recovery_dir.expanduser().resolve()
818
- if recovery == root or root in recovery.parents:
819
- raise InitError("--recovery-dir must be outside the project root")
1268
+ recovery, defaulted = prepare_recovery_dir(root, args.recovery_dir, "refresh")
820
1269
  for relative in replacing:
821
- archived = recovery / relative
822
- if archived.exists():
823
- raise InitError(f"recovery collision: {relative}")
824
- archived.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
825
- archived.write_bytes((root / relative).read_bytes())
826
- result["recovery"] = str(recovery)
1270
+ backup_into(root, recovery, relative)
1271
+ result.update(recovery=str(recovery), recovery_default=defaulted,
1272
+ recovery_files=[path.as_posix() for path in replacing])
1273
+ new_regions: dict[str, dict[str, str]] = {}
827
1274
  for item in plan:
828
1275
  relative = Path(item["path"])
829
1276
  if item["action"] in {"replace", "create"}:
830
1277
  target = root / relative
831
1278
  target.parent.mkdir(parents=True, exist_ok=True)
832
- temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
833
- temporary.write_text(rendered[relative], encoding="utf-8")
834
- if relative == Path(inputs.entry_launcher or "\0"):
835
- temporary.chmod(0o755)
836
- os.replace(temporary, target)
1279
+ _atomic_write(target, rendered[relative], 0o755 if relative == Path(inputs.entry_launcher or "\0") else None)
1280
+ elif item["action"] == "merge":
1281
+ target = root / relative
1282
+ _atomic_write(target, merged_texts[relative], os.stat(target).st_mode & 0o7777)
1283
+ elif item["action"] == "append":
1284
+ target = root / relative
1285
+ text = target.read_text(encoding="utf-8")
1286
+ for region_id in item["regions"]:
1287
+ body = localized(templates, f"region/{region_id}", inputs.language)
1288
+ text, _region_state = regions.upsert(text, region_id, body)
1289
+ new_regions.setdefault(item["path"], {})[region_id] = regions.digest(body)
1290
+ _atomic_write(target, text, os.stat(target).st_mode & 0o7777)
837
1291
  files = dict(baseline)
838
1292
  for item in plan:
839
- if item["action"] in {"replace", "create"} or item["state"] == "unchanged":
1293
+ if item["action"] in {"replace", "create", "merge"} or item["state"] == "unchanged":
840
1294
  files[item["path"]] = item["new_sha256"]
1295
+ file_versions[item["path"]] = pack["version"]
1296
+ elif item["state"] == "local-only":
1297
+ file_versions[item["path"]] = pack["version"] # 新模板渲染结果与基线相同
1298
+ elif item["path"] in baseline and item["path"] not in file_versions and entry.get("version") not in (None, UNKNOWN_PACK_VERSION):
1299
+ file_versions[item["path"]] = entry["version"] # 没写这个文件:基线仍是升级前的版本
841
1300
  # Files kept on purpose keep their old baseline: the tool did not write them.
842
- lock.setdefault("packs", {})[pack["id"]] = {"plugin": "agents-init", "version": pack["version"],
843
- "files": dict(sorted(files.items()))}
1301
+ new_entry = {**entry, "plugin": "agents-init", "version": pack["version"],
1302
+ "files": dict(sorted(files.items())), "render_inputs": render_inputs(inputs)}
1303
+ if file_versions:
1304
+ new_entry["file_versions"] = dict(sorted(file_versions.items()))
1305
+ if new_regions:
1306
+ merged = {path: dict(ids) for path, ids in (entry.get("regions") or {}).items()}
1307
+ for path, ids in new_regions.items():
1308
+ merged.setdefault(path, {}).update(ids)
1309
+ new_entry["regions"] = dict(sorted(merged.items()))
1310
+ lock.setdefault("packs", {})[pack["id"]] = new_entry
844
1311
  lock_path = root / CONTENT_LOCK_PATH
845
1312
  lock_path.parent.mkdir(parents=True, exist_ok=True)
846
- temporary = lock_path.with_name(f".{lock_path.name}.{os.getpid()}.tmp")
847
- temporary.write_text(json_text(lock), encoding="utf-8")
848
- os.replace(temporary, lock_path)
849
- # 显式 --keep 的选择记入决定文件:同样的模板内容以后不再追问,模板实质变化时才再问。
1313
+ _atomic_write(lock_path, json_text(lock))
1314
+ # 显式 --keep / --append 的选择记入决定文件:同样的模板内容以后不再追问,模板实质变化时才再问。
850
1315
  for item in plan:
851
- if Path(item["path"]) in keep and item["state"] in {"modified", "local-only", "kept-by-decision"}:
852
- _scaffold().decide(root, f"content:{item['path']}", "keep", reason="refresh --keep",
1316
+ chosen_keep = Path(item["path"]) in (keep | append) or item["action"] in {"append", "merge"}
1317
+ if chosen_keep and item["state"] in {"modified", "local-only", "kept-by-decision", "symlink"}:
1318
+ _scaffold().decide(root, f"content:{item['path']}", "keep",
1319
+ reason=("refresh --append: kept the local file and appended a managed region" if item["action"] == "append"
1320
+ else "refresh --merge: merged the local edits with the new template" if item["action"] == "merge"
1321
+ else "refresh --keep: kept the local file"),
853
1322
  fingerprint=item["new_sha256"], scope="project", apply=True)
854
1323
  result.setdefault("decisions", []).append(f"content:{item['path']}")
855
1324
  result["applied"] = True
856
1325
  return 0, result
857
1326
 
858
1327
 
1328
+ def _adopt():
1329
+ here = str(Path(__file__).resolve().parent)
1330
+ if here not in sys.path:
1331
+ sys.path.insert(0, here)
1332
+ import adopt # noqa: PLC0415
1333
+
1334
+ adopt.bind(sys.modules[__name__])
1335
+ return adopt
1336
+
1337
+
859
1338
  def _atomic_write(path: Path, text: str, mode: int | None = None) -> None:
1339
+ """Write ``text`` through a temporary file and ``os.replace``; a failure removes the temporary and raises InitError."""
860
1340
  temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
861
- temporary.write_text(text, encoding="utf-8")
862
- if mode is not None:
863
- temporary.chmod(mode)
864
- os.replace(temporary, path)
1341
+ try:
1342
+ temporary.write_text(text, encoding="utf-8")
1343
+ if mode is not None:
1344
+ temporary.chmod(mode)
1345
+ os.replace(temporary, path)
1346
+ except OSError as exc:
1347
+ try:
1348
+ temporary.unlink()
1349
+ except OSError:
1350
+ pass
1351
+ raise InitError(_("写入 {0} 失败,临时文件已清理:{1}。已写好的文件与备份保持一致,排除原因后重新运行同一条命令即可继续").format(
1352
+ path.name, exc), code="write-failed") from exc
865
1353
 
866
1354
 
867
- def readme_plan(root: Path, name: str, launcher: str | None) -> dict | None:
1355
+ def readme_plan(root: Path, name: str, launcher: str | None, language: str = "zh") -> dict | None:
868
1356
  """README.md: create it with the entry section, or append the section once (marked)."""
869
1357
  path = root / "README.md"
870
1358
  if path.is_symlink():
871
1359
  raise InitError("refusing symlinked README.md")
872
1360
  if not path.exists():
873
- return {"path": "README.md", "action": "create", "text": f"# {name}\n\n{readme_block(launcher)}"}
1361
+ return {"path": "README.md", "action": "create", "text": f"# {name}\n\n{readme_block(launcher, language)}"}
874
1362
  current = path.read_text(encoding="utf-8")
875
1363
  if README_START in current:
876
1364
  return None
877
1365
  return {"path": "README.md", "action": "append",
878
- "text": current.rstrip("\n") + "\n\n" + readme_block(launcher)}
1366
+ "text": current.rstrip("\n") + "\n\n" + readme_block(launcher, language)}
879
1367
 
880
1368
 
881
1369
  def add_entry(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
@@ -887,22 +1375,22 @@ def add_entry(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
887
1375
  replaced only by explicit --keep / --accept, replacements backed up first.
888
1376
  """
889
1377
  if not args.entry_name:
890
- raise InitError("--mode entry 需要 --entry-name")
1378
+ raise InitError(_("--mode entry 需要 --entry-name"))
891
1379
  name = validate_entry_name(args.entry_name)
892
1380
  profile = _read_project_json(root, PROFILE_PATH, "Project Profile")
893
1381
  entry = profile.get("entry") if isinstance(profile.get("entry"), dict) else {}
894
1382
  if entry.get("launcher") and entry["launcher"] != name:
895
- raise InitError(f"项目已声明入口 ./{entry['launcher']};改名请同时修改 Profile 的 entry.launcher 与文件名")
1383
+ raise InitError(_("项目已声明入口 ./{0};改名请同时修改 Profile 的 entry.launcher 与文件名").format(entry['launcher']))
896
1384
  template = launcher_text()
897
1385
  target = root / name
898
1386
  if target.is_symlink():
899
1387
  raise InitError(f"refusing symlinked launcher: {name}")
900
1388
  current = target.read_text(encoding="utf-8", errors="replace") if target.is_file() else None
901
1389
  if target.exists() and not target.is_file():
902
- raise InitError(f"{name} 已存在且不是文件")
1390
+ raise InitError(_("{0} 已存在且不是文件").format(name))
903
1391
  chosen = {Path(value) for value in args.accept} | {Path(value) for value in args.keep}
904
1392
  if chosen - {Path(name)}:
905
- raise InitError("--mode entry 只接受启动器文件的 --accept / --keep:" + name)
1393
+ raise InitError(_("--mode entry 只接受启动器文件的 --accept / --keep:") + name)
906
1394
  if current is None:
907
1395
  action = "create"
908
1396
  elif current == template:
@@ -915,18 +1403,18 @@ def add_entry(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
915
1403
  action = "blocked"
916
1404
  new_profile = {**profile, "entry": {**entry, "api": entry.get("api", ENTRY_API), "launcher": name}}
917
1405
  profile_changed = new_profile != profile
918
- readme = readme_plan(root, str(profile.get("name") or root.name), name) if args.readme_entry else None
1406
+ readme = readme_plan(root, str(profile.get("name") or root.name), name, project_language(profile)) if args.readme_entry else None
919
1407
  writes = ([name] if action in ("create", "replace") else []) + ([str(PROFILE_PATH)] if profile_changed else []) \
920
1408
  + ([readme["path"]] if readme else [])
921
1409
  if action in ("create", "replace", "unchanged"):
922
1410
  writes.append(str(CONTENT_LOCK_PATH))
923
- labels = {"create": "新建启动器", "replace": "用模板替换(先备份)", "unchanged": "已是模板内容",
924
- "keep": "保留你的文件(不跟踪更新)", "blocked": "已存在同名文件,需要选择"}
925
- changes = [f"{name}:{labels[action]}"]
1411
+ labels = {"create": _("新建启动器"), "replace": _("用模板替换(先备份)"), "unchanged": _("已是模板内容"),
1412
+ "keep": _("保留你的文件(不跟踪更新)"), "blocked": _("已存在同名文件,需要选择")}
1413
+ changes = [_("{0}:{1}").format(name, labels[action])]
926
1414
  if profile_changed:
927
- changes.append(f"Project Profile:加入 entry(api {new_profile['entry']['api']},launcher {name})")
1415
+ changes.append(_("Project Profile:加入 entry(api {0},launcher {1})").format(new_profile['entry']['api'], name))
928
1416
  if readme:
929
- changes.append("README.md:" + ("新建并写入「怎样使用」" if readme["action"] == "create" else "追加「怎样使用」一节"))
1417
+ changes.append(_("README.md:") + (_("新建并写入「怎样使用」") if readme["action"] == "create" else _("追加「怎样使用」一节")))
930
1418
  result = {
931
1419
  "ok": action != "blocked", "mode": "entry", "applied": False,
932
1420
  "entry": {"name": name, "action": action, "writes": writes, "changes": changes,
@@ -934,24 +1422,16 @@ def add_entry(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
934
1422
  "profile_diff": _unified_diff(str(PROFILE_PATH), json_text(profile), json_text(new_profile))
935
1423
  if profile_changed else ""},
936
1424
  "blocked": [name] if action == "blocked" else [],
937
- "readme_snippet": readme_block(name) if not readme else "",
1425
+ "readme_snippet": readme_block(name, project_language(profile)) if not readme else "",
938
1426
  }
939
1427
  if action == "blocked":
940
- result["hint"] = f"{name} 已存在:--accept {name} 用模板替换(先备份到 --recovery-dir),或 --keep {name} 保留你的文件"
1428
+ result["hint"] = _("{0} 已存在:--accept {1} 用模板替换(先备份到恢复目录),或 --keep {2} 保留你的文件").format(name, name, name)
941
1429
  if not args.apply or action == "blocked":
942
1430
  return (0 if action != "blocked" else 1), result
943
1431
  if action == "replace":
944
- if args.recovery_dir is None:
945
- raise InitError("--recovery-dir is required when replacing the launcher")
946
- recovery = args.recovery_dir.expanduser().resolve()
947
- if recovery == root or root in recovery.parents:
948
- raise InitError("--recovery-dir must be outside the project root")
949
- archived = recovery / name
950
- if archived.exists():
951
- raise InitError(f"recovery collision: {name}")
952
- archived.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
953
- archived.write_bytes(target.read_bytes())
954
- result["recovery"] = str(recovery)
1432
+ recovery, defaulted = prepare_recovery_dir(root, args.recovery_dir, "entry")
1433
+ backup_into(root, recovery, Path(name))
1434
+ result.update(recovery=str(recovery), recovery_default=defaulted, recovery_files=[name])
955
1435
  if action in ("create", "replace"):
956
1436
  _atomic_write(target, template, 0o755)
957
1437
  if readme:
@@ -977,8 +1457,39 @@ def add_entry(args: argparse.Namespace, root: Path) -> tuple[int, dict]:
977
1457
  return 0, result
978
1458
 
979
1459
 
1460
+ def _adopt_text(result: dict) -> str:
1461
+ lines = []
1462
+ if result["mode"] == "scan":
1463
+ lines.append(_("Scan(只读)"))
1464
+ else:
1465
+ lines.append(_("{0}:{1}").format(_("已应用") if result.get("applied") else _("仅预览"), result["mode"]))
1466
+ for blocker in result.get("blockers", []):
1467
+ lines.append(_(" 已阻塞 [{0}] {1}").format(blocker["code"], blocker["message"]))
1468
+ scan = result.get("scan", result)
1469
+ for item in scan.get("findings", []):
1470
+ lines.append(f" [{item['id']}] {item['summary']}")
1471
+ for option in item["options"]:
1472
+ mark = _("(推荐)") if option["id"] == item["recommended"] else ""
1473
+ lines.append(f" - {option['label']}{mark}" + (f" {option['flag']}" if option["flag"] else ""))
1474
+ for key, title in (("create", _("新建")), ("preserve", _("保留"))):
1475
+ for path in result.get(key, []):
1476
+ lines.append(f" {title} {path}")
1477
+ for item in result.get("modify", []):
1478
+ lines.append(f" {item['action']} {item['path']}" + (_("(区块 {0})").format(_("、").join(item.get("regions") or [item["region"]])) if item.get("region") else ""))
1479
+ for note in result.get("notes", []):
1480
+ lines.append(_(" 说明:{0}").format(note))
1481
+ if result.get("needs_recovery_dir") and not result.get("applied"):
1482
+ lines.append(" " + _("改动已有文件前会先备份到 ~/.agent-pack/recovery/(也可用 --recovery-dir 指定项目外的目录)"))
1483
+ if scan.get("recommended_flags"):
1484
+ lines.append(" " + _("推荐选项:") + " ".join(scan["recommended_flags"]))
1485
+ if result.get("check_after"):
1486
+ lines.append(" " + _("接管后检查:") + (_("一致") if result["check_after"]["ok"] else _("仍有 ") + ", ".join(result["check_after"]["findings"])))
1487
+ lines.extend(recovery_lines(result))
1488
+ return "\n".join(lines) + "\n"
1489
+
1490
+
980
1491
  def parser() -> argparse.ArgumentParser:
981
- result = argparse.ArgumentParser(description=__doc__)
1492
+ result = argparse.ArgumentParser(description=_("使用 agents-init v6 中文模板安全创建或迁移项目骨架。"))
982
1493
  result.add_argument("--project", type=Path, required=True)
983
1494
  result.add_argument("--name")
984
1495
  result.add_argument("--slug")
@@ -988,37 +1499,67 @@ def parser() -> argparse.ArgumentParser:
988
1499
  result.add_argument("--runtime")
989
1500
  result.add_argument("--agent-cli", type=split_csv)
990
1501
  result.add_argument("--mode", choices=("init", "migrate", "refresh", "entry", "check", "add-skeleton", "profile",
991
- "repair-lock", "decide", "case-naming"), default="init",
992
- help="refresh:内容包更新后按 Profile 重新渲染已跟踪的模板文件;"
1502
+ "repair-lock", "decide", "case-naming", "scan", "adopt", "region", "language", "accept-current"),
1503
+ default="init",
1504
+ help=_("refresh:内容包更新后按 Profile 重新渲染已跟踪的模板文件;"
993
1505
  "entry:为已初始化的项目补上根目录启动器与 Profile 的 entry 段;"
994
1506
  "check:只读,对比期望骨架清单;add-skeleton:按模板补上缺失的骨架文件;"
995
1507
  "profile:把缺失或不符的受检字段改为模板值;repair-lock:修复内容锁的 0.0.0 版本;"
996
- "decide:记录或撤销对某个发现的决定;case-naming:只输出 Case 目录改名计划与受影响的引用,不移动任何目录")
1508
+ "decide:记录或撤销对某个发现的决定;case-naming:只输出 Case 目录改名计划与受影响的引用,不移动任何目录;"
1509
+ "scan:只读,扫描已有内容与骨架的冲突并给出选项和推荐;"
1510
+ "adopt:接管非空目录(已有文件原样保留,只补骨架;改动已有文件须显式选择并备份);"
1511
+ "region:更新受管区块(--accept / --keep <文件>#<区块ID>);"
1512
+ "language:只把 Profile 的 language 设为 --language zh|en(项目文件语言;默认预览,先备份,不改写任何已有文件)"))
997
1513
  result.add_argument("--target", action="append", default=[],
998
- help="add-skeleton:骨架路径;profile:字段;decide:发现 ID(可重复;省略则处理全部可处理项)")
999
- result.add_argument("--decision", choices=("skip", "keep", "later", "unskip"), help="decide:决定;unskip 撤销")
1000
- result.add_argument("--reason", help="decide:理由(建议写,随项目同步)")
1001
- result.add_argument("--fingerprint", help="decide:期望指纹(缺省取该发现当前的指纹)")
1002
- result.add_argument("--reprompt", action="store_true", help="check:忽略已记录的决定,重新评估全部发现")
1003
- result.add_argument("--state-dir", type=Path, help="机器本地决定的状态目录(缺省 $XDG_STATE_HOME 或 ~/.local/state)")
1004
- result.add_argument("--entry-name", help=f"根目录启动器文件名(init 缺省 {DEFAULT_ENTRY};entry 模式必填)")
1005
- result.add_argument("--no-entry", action="store_true", help="init:不生成根目录启动器")
1514
+ help=_("add-skeleton:骨架路径;profile:字段;decide:发现 ID(可重复;省略则处理全部可处理项)"))
1515
+ result.add_argument("--decision", choices=("skip", "keep", "later", "unskip"), help=_("decide:决定;unskip 撤销"))
1516
+ result.add_argument("--reason", help=_("decide / accept-current:理由(建议写,随项目同步)"))
1517
+ result.add_argument("--fingerprint", help=_("decide:期望指纹(缺省取该发现当前的指纹)"))
1518
+ result.add_argument("--reprompt", action="store_true", help=_("check:忽略已记录的决定,重新评估全部发现"))
1519
+ result.add_argument("--required-only", action="store_true", dest="required_only",
1520
+ help=_("check:退出码只看「需要处理」的发现(与 agenthelm check 一致);缺省「可选」差异也使退出码为 1"))
1521
+ result.add_argument("--state-dir", type=Path, help=_("机器本地决定的状态目录(缺省 $XDG_STATE_HOME 或 ~/.local/state)"))
1522
+ result.add_argument("--entry-name", help=_("根目录启动器文件名(init 缺省 {0};entry 模式必填)").format(DEFAULT_ENTRY))
1523
+ result.add_argument("--no-entry", action="store_true", help=_("init:不生成根目录启动器"))
1524
+ result.add_argument("--language", choices=("auto", "zh", "en"), default="auto",
1525
+ help=_("init / migrate:项目文件语言(新建 Case 的小节名、README 追加的使用说明);auto 在 init 时取当前界面语言,migrate 时保持中文"))
1006
1526
  result.add_argument("--readme-entry", action="store_true",
1007
- help="在已有 README.md 末尾追加「怎样使用」一节(带标记,只追加一次);init 时 README 不存在会直接新建")
1008
- result.add_argument("--accept", action="append", default=[], help="refresh:用新模板替换这个本地已改动的文件")
1009
- result.add_argument("--keep", action="append", default=[], help="refresh:保留这个文件的本地内容")
1527
+ help=_("在已有 README.md 末尾追加「怎样使用」一节(带标记,只追加一次);init 时 README 不存在会直接新建"))
1528
+ result.add_argument("--accept", action="append", default=[], help=_("refresh:用新模板替换这个本地已改动的文件"))
1529
+ result.add_argument("--keep", action="append", default=[], help=_("refresh:保留这个文件的本地内容"))
1530
+ result.add_argument("--append", action="append", default=[],
1531
+ help=_("refresh:保留 AGENTS.md / CLAUDE.md 的本地内容,只在末尾追加带标记的区块(先备份)"))
1532
+ result.add_argument("--confirm-discard", action="append", default=[], dest="confirm_discard",
1533
+ help=_("refresh:确认 --accept 会丢弃这个文件里的本地内容"))
1534
+ result.add_argument("--diff", action="append", default=[],
1535
+ help=_("refresh:只查看这个文件与新模板的完整差异,不写入"))
1536
+ result.add_argument("--merge", action="append", default=[],
1537
+ help=_("refresh:三方合并这个本地已改动的文件(用旧版本包还原基线,保留你的改动并带入新模板的变化;默认只预览,先备份)"))
1538
+ result.add_argument("--pick", action="append", default=[],
1539
+ help=_("refresh --merge:逐块选择冲突,写法 <文件>#<冲突块序号>=mine|theirs|both(可重复)"))
1010
1540
  result.add_argument("--work-mode", choices=("case-workspace", "legacy"), default=None,
1011
- help="新项目默认 case-workspace;既有项目只在显式选择后更改模式")
1541
+ help=_("新项目默认 case-workspace;既有项目只在显式选择后更改模式"))
1012
1542
  result.add_argument("--replace", action="append", default=[], help="known skeleton path to replace in migrate mode")
1013
1543
  result.add_argument("--skip", action="append", default=[], help="known skeleton path the project does not want (migrate mode)")
1014
- result.add_argument("--recovery-dir", type=Path, help="outside-project backup directory required for replacements")
1544
+ result.add_argument("--recovery-dir", type=Path,
1545
+ help=_("被替换文件的备份目录(必须在项目外);缺省 ~/.agent-pack/recovery/<UTC 时间>-agenthelm-<模式>/"))
1546
+ result.add_argument("--agents-policy", choices=("keep", "append", "split", "side-by-side"), default=None,
1547
+ help=_("adopt:已有 AGENTS.md 怎么处理(缺省 keep,不改动)"))
1548
+ result.add_argument("--claude-policy", choices=("keep", "add-import"), default=None,
1549
+ help=_("adopt:已有 CLAUDE.md 没导入 AGENTS.md 时是否追加导入区块(缺省 keep)"))
1550
+ result.add_argument("--route", action="append", default=[],
1551
+ help=_("adopt split:<章节序号>=<agents|rules|user|opinion|sop>,未指定的章节留在 AGENTS.md"))
1552
+ result.add_argument("--register-root", action="append", default=[],
1553
+ help=_("adopt:把已有的工作容器目录登记到 work.assets.roots(只读登记,不动内容)"))
1554
+ result.add_argument("--case-root", help=_("adopt:新 Case 放的目录(缺省 cases)"))
1555
+ result.add_argument("--memory-root", help=_("adopt:记忆条目放的目录(缺省 memory)"))
1015
1556
  result.add_argument(
1016
1557
  "--runtime-plugin-root",
1017
1558
  type=Path,
1018
1559
  default=PLUGIN_ROOT,
1019
1560
  help=(
1020
- "agents-init Plugin 根目录(同级查找 project-orchestrator、agent-pack、"
1021
- "opinion-manager),或含 plugins/ 的仓库根目录"
1561
+ _("agents-init Plugin 根目录(同级查找 project-orchestrator、agent-pack、"
1562
+ "opinion-manager),或含 plugins/ 的仓库根目录")
1022
1563
  ),
1023
1564
  )
1024
1565
  result.add_argument("--apply", action="store_true", help="create the complete skeleton only when no collision exists")
@@ -1030,7 +1571,26 @@ def main(argv: list[str] | None = None) -> int:
1030
1571
  args = parser().parse_args(argv)
1031
1572
  try:
1032
1573
  root = validate_root(args.project)
1033
- if args.mode in ("check", "add-skeleton", "profile", "repair-lock", "decide", "case-naming"):
1574
+ if args.required_only and args.mode != "check":
1575
+ raise InitError(_("--required-only 只用于 --mode check"))
1576
+ if args.mode == "scan":
1577
+ placeholder = Inputs(root, args.name or root.name, "project", tuple(args.project_type or ("code",)),
1578
+ args.vcs or "git", tuple(args.stack or ("unknown",)), args.runtime or "local",
1579
+ tuple(args.agent_cli or ("codex",)), args.work_mode or "case-workspace",
1580
+ None if args.no_entry else validate_entry_name(args.entry_name or DEFAULT_ENTRY),
1581
+ file_language(args))
1582
+ adopt = _adopt()
1583
+ report = adopt.scan(root, placeholder, case_root=args.case_root or "cases",
1584
+ memory_root=args.memory_root or "memory")
1585
+ result = {"ok": not report["blockers"], "mode": "scan", "applied": False, **report}
1586
+ print(json_text(result), end="") if args.output == "json" else print(_adopt_text(result), end="")
1587
+ return 0 if result["ok"] else 1
1588
+ if args.mode == "region":
1589
+ code, result = _scaffold().update_regions(root, accept=args.accept, keep=args.keep, apply=args.apply,
1590
+ recovery_dir=args.recovery_dir, state_dir=args.state_dir)
1591
+ print(json_text(result), end="") if args.output == "json" else print(_scaffold().render_text(result), end="")
1592
+ return code
1593
+ if args.mode in ("check", "add-skeleton", "profile", "repair-lock", "decide", "case-naming", "language", "accept-current"):
1034
1594
  scaffold = _scaffold()
1035
1595
  code, result = scaffold.run_mode(args, root)
1036
1596
  print(json_text(result), end="") if args.output == "json" else print(scaffold.render_text(result), end="")
@@ -1040,33 +1600,47 @@ def main(argv: list[str] | None = None) -> int:
1040
1600
  if args.output == "json":
1041
1601
  print(json_text(result), end="")
1042
1602
  else:
1043
- print(("Applied" if result["applied"] else "Blocked" if result["blocked"] else "Dry-run")
1044
- + f": entry ./{result['entry']['name']}")
1603
+ print(_("{0}:入口 ./{1}").format(_("已应用") if result["applied"] else _("已阻塞") if result["blocked"] else _("仅预览"),
1604
+ result["entry"]["name"]))
1045
1605
  for change in result["entry"]["changes"]:
1046
1606
  print(f" {change}")
1047
1607
  if result.get("hint"):
1048
1608
  print(result["hint"])
1049
1609
  if result.get("readme_snippet"):
1050
- print("README 里可以加上:\n" + result["readme_snippet"])
1610
+ print(_("README 里可以加上:\n") + result["readme_snippet"])
1611
+ for line in recovery_lines(result):
1612
+ print(line)
1051
1613
  return code
1052
1614
  if args.mode == "refresh":
1053
1615
  code, result = refresh_project(args, root)
1054
1616
  if args.output == "json":
1055
1617
  print(json_text(result), end="")
1056
1618
  else:
1057
- label = "Applied" if result["applied"] else ("Blocked" if result["blocked"] else "Dry-run")
1058
- print(f"{label}: {result['pack']} (from {result['from_version']})")
1619
+ label = _("已应用") if result["applied"] else (_("已阻塞") if result["blocked"] else _("仅预览"))
1620
+ print(_("{0}:{1}(来自 {2})").format(label, result["pack"], result["from_version"]))
1059
1621
  for item in result["files"]:
1060
1622
  print(f" {item['action']:8} {item['path']} [{item['state']}]")
1623
+ for note in item.get("note", []):
1624
+ print(f" {note}")
1625
+ for block in (item.get("merge") or {}).get("conflicts", []):
1626
+ if block["pick"] is None:
1627
+ print(_(" 冲突块 {0}:").format(block["id"]))
1628
+ for label, key in ((_("你的版本"), "mine"), (_("基线"), "base"), (_("新模板"), "theirs")):
1629
+ print(f" [{label}]")
1630
+ print("".join(f" {line}\n" for line in block[key].splitlines()) or " \n", end="")
1631
+ for path, text in result.get("diffs", {}).items():
1632
+ print(text.rstrip("\n") if text else _("({0} 与新模板没有差异)").format(path))
1061
1633
  if result.get("hint"):
1062
1634
  print(result["hint"])
1635
+ for line in recovery_lines(result):
1636
+ print(line)
1063
1637
  return code
1064
1638
  missing = [flag for flag, value in (("--name", args.name), ("--project-type", args.project_type),
1065
1639
  ("--vcs", args.vcs), ("--stack", args.stack),
1066
1640
  ("--runtime", args.runtime), ("--agent-cli", args.agent_cli))
1067
1641
  if not value]
1068
1642
  if missing:
1069
- raise InitError("init/migrate 需要:" + ", ".join(missing))
1643
+ raise InitError(_("init/migrate 需要:") + ", ".join(missing))
1070
1644
  runtime_status = validate_runtime(args.runtime_plugin_root)
1071
1645
  slug = args.slug or slugify(args.name)
1072
1646
  if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", slug):
@@ -1082,8 +1656,13 @@ def main(argv: list[str] | None = None) -> int:
1082
1656
  tuple(validate_inline("--agent-cli", value) for value in args.agent_cli),
1083
1657
  args.work_mode or ('legacy' if args.mode == 'migrate' else 'case-workspace'),
1084
1658
  None if args.no_entry else validate_entry_name(args.entry_name) if args.entry_name
1085
- else DEFAULT_ENTRY if args.mode == "init" else None,
1659
+ else DEFAULT_ENTRY if args.mode in ("init", "adopt") else None,
1660
+ file_language(args),
1086
1661
  )
1662
+ if args.mode == "adopt":
1663
+ code, result = _adopt().run(args, root, inputs)
1664
+ print(json_text(result), end="") if args.output == "json" else print(_adopt_text(result), end="")
1665
+ return code
1087
1666
  files = files_for(inputs)
1088
1667
  if args.mode == "migrate" and (root / PROFILE_PATH).exists():
1089
1668
  profile_file = root / PROFILE_PATH
@@ -1092,10 +1671,12 @@ def main(argv: list[str] | None = None) -> int:
1092
1671
  try:
1093
1672
  current_profile = json.loads(profile_file.read_text(encoding="utf-8"))
1094
1673
  except (OSError, UnicodeError, ValueError) as exc:
1095
- raise InitError('Project Profile 无法解析', code='profile-invalid') from exc
1674
+ raise InitError(_('Project Profile 无法解析'), code='profile-invalid') from exc
1096
1675
  if not isinstance(current_profile, dict) or current_profile.get("schema_version") != "1.0":
1097
1676
  raise InitError("unsupported Project Profile", code="profile-invalid")
1098
1677
  upgraded = configure_work_mode(upgrade_legacy_profile(current_profile), args.work_mode)
1678
+ if args.language in ("zh", "en"):
1679
+ upgraded["language"] = args.language
1099
1680
  files[PROFILE_PATH] = json_text(upgraded)
1100
1681
  if upgraded.get("work", {}).get("mode") != "case-workspace":
1101
1682
  files.pop(Path("cases/.gitkeep"), None)
@@ -1104,11 +1685,13 @@ def main(argv: list[str] | None = None) -> int:
1104
1685
  if legacy_profile is not None:
1105
1686
  if args.mode == "init":
1106
1687
  raise InitError(
1107
- f"检测到 v5 Project Profile({LEGACY_PROFILE_PATH}),请改用 --mode migrate",
1688
+ _("检测到 v5 Project Profile({0}),请改用 --mode migrate").format(LEGACY_PROFILE_PATH),
1108
1689
  code="migrate-required",
1109
1690
  )
1110
1691
  if not (root / PROFILE_PATH).exists():
1111
1692
  upgraded = configure_work_mode(upgrade_legacy_profile(legacy_profile), args.work_mode)
1693
+ if args.language in ("zh", "en"):
1694
+ upgraded["language"] = args.language
1112
1695
  files[PROFILE_PATH] = json_text(upgraded)
1113
1696
  if upgraded.get('work', {}).get('mode') != 'case-workspace':
1114
1697
  files.pop(Path('cases/.gitkeep'), None)
@@ -1118,7 +1701,7 @@ def main(argv: list[str] | None = None) -> int:
1118
1701
  if output_profile.get('work', {}).get('mode') == 'case-workspace':
1119
1702
  case_root = (output_profile['work'].get('case') or {}).get('root', 'cases')
1120
1703
  if not isinstance(case_root, str) or not case_root or Path(case_root).is_absolute() or '..' in Path(case_root).parts or '\\' in case_root or re.match(r'^[A-Za-z]:', case_root) or case_root == '.' or set(Path(case_root).parts) & {'.git', '.agents', '.codex', '.cursor', '.claude', 'local-ai', 'confidential'}:
1121
- raise InitError('Case root 必须是项目内明确相对目录', code='profile-invalid')
1704
+ raise InitError(_('Case root 必须是项目内明确相对目录'), code='profile-invalid')
1122
1705
  files[Path(case_root) / '.gitkeep'] = ''
1123
1706
  requested_skip = {Path(value) for value in args.skip}
1124
1707
  if requested_skip:
@@ -1133,9 +1716,9 @@ def main(argv: list[str] | None = None) -> int:
1133
1716
  del files[path]
1134
1717
  readme = None
1135
1718
  if args.mode == "init" and not (root / "README.md").exists():
1136
- files[Path("README.md")] = f"# {inputs.name}\n\n{readme_block(inputs.entry_launcher)}"
1719
+ files[Path("README.md")] = f"# {inputs.name}\n\n{readme_block(inputs.entry_launcher, inputs.language)}"
1137
1720
  elif args.readme_entry:
1138
- readme = readme_plan(root, inputs.name, inputs.entry_launcher)
1721
+ readme = readme_plan(root, inputs.name, inputs.entry_launcher, inputs.language)
1139
1722
  create, collisions, symlinked = plan_writes(
1140
1723
  root, files, skip_symlinked_parents=args.mode == "migrate"
1141
1724
  )
@@ -1160,6 +1743,7 @@ def main(argv: list[str] | None = None) -> int:
1160
1743
  preserved = [path for path in collisions if path not in requested_replace]
1161
1744
  pack = contract_pack()
1162
1745
  baseline = content_baseline(pack, files, [*create, *replace], inputs.entry_launcher)
1746
+ recovery_used: Path | None = None
1163
1747
  if args.mode == "init":
1164
1748
  applied = bool(args.apply and not collisions)
1165
1749
  if applied:
@@ -1168,7 +1752,7 @@ def main(argv: list[str] | None = None) -> int:
1168
1752
  else:
1169
1753
  applied = bool(args.apply)
1170
1754
  if applied:
1171
- apply_migration(root, files, create, replace, args.recovery_dir, retire)
1755
+ recovery_used = apply_migration(root, files, create, replace, args.recovery_dir, retire)
1172
1756
  if retire:
1173
1757
  try:
1174
1758
  (root / LEGACY_PROFILE_PATH.parent).rmdir()
@@ -1180,7 +1764,7 @@ def main(argv: list[str] | None = None) -> int:
1180
1764
  if applied and readme:
1181
1765
  _atomic_write(root / readme["path"], readme["text"])
1182
1766
  if applied and pack is not None and baseline:
1183
- write_content_lock(root, pack, baseline)
1767
+ write_content_lock(root, pack, baseline, inputs=inputs)
1184
1768
  result = {
1185
1769
  "ok": ok,
1186
1770
  "mode": args.mode,
@@ -1191,6 +1775,9 @@ def main(argv: list[str] | None = None) -> int:
1191
1775
  "skipped_symlinked_parents": [str(path) for path in symlinked],
1192
1776
  "skipped_by_request": sorted(str(path) for path in requested_skip),
1193
1777
  "retire": [str(path) for path in retire],
1778
+ "recovery": str(recovery_used) if recovery_used is not None and (replace or retire) else None,
1779
+ "recovery_default": args.recovery_dir is None if recovery_used is not None else None,
1780
+ "recovery_files": [str(path) for path in [*replace, *retire]] if recovery_used is not None else [],
1194
1781
  "profile_upgraded_from": str(LEGACY_PROFILE_PATH) if retire else None,
1195
1782
  "runtime": runtime_status,
1196
1783
  "entry": {"launcher": inputs.entry_launcher, "command": entry_command(inputs.entry_launcher)},
@@ -1204,18 +1791,20 @@ def main(argv: list[str] | None = None) -> int:
1204
1791
  if args.output == "json":
1205
1792
  print(json_text(result), end="")
1206
1793
  else:
1207
- label = "Applied" if applied else ("Blocked" if args.mode == "init" and args.apply and collisions else "Dry-run")
1208
- print(label + f": {len(create)} create, {len(replace)} replace, {len(preserved)} preserved collision(s)")
1794
+ label = _("已应用") if applied else (_("已阻塞") if args.mode == "init" and args.apply and collisions else _("仅预览"))
1795
+ print(_("{0}:新建 {1},替换 {2},保留冲突 {3}").format(label, len(create), len(replace), len(preserved)))
1209
1796
  for path in create:
1210
- print(f" create {path}")
1797
+ print(f" {_('新建')} {path}")
1211
1798
  for path in replace:
1212
- print(f" replace {path}")
1799
+ print(f" {_('替换')} {path}")
1213
1800
  for path in preserved:
1214
- print(f" preserve {path}")
1801
+ print(f" {_('保留')} {path}")
1215
1802
  for path in symlinked:
1216
- print(f" skip {path} (symlinked parent)")
1803
+ print(_(" 跳过 {0}(父目录是符号链接)").format(path))
1217
1804
  for path in retire:
1218
- print(f" retire {path} (upgraded into {PROFILE_PATH})")
1805
+ print(_(" 退役 {0}(已升级进 {1})").format(path, PROFILE_PATH))
1806
+ for line in recovery_lines(result):
1807
+ print(line)
1219
1808
  return 0 if ok else 1
1220
1809
  except InitError as error:
1221
1810
  if args.output == "json":