@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.
- package/README.md +1 -1
- package/README.zh-CN.md +2 -0
- package/package.json +1 -1
- package/runtime/index.json +6 -6
- package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agent-pack/hooks/hooks.json +32 -0
- package/runtime/plugins/agent-pack/plugin.json +1 -1
- package/runtime/plugins/agent-pack/references/local-only.md +126 -0
- package/runtime/plugins/agent-pack/references/nudge.en.md +58 -0
- package/runtime/plugins/agent-pack/references/nudge.md +58 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +613 -0
- package/runtime/plugins/agent-pack/runtime/agenthelm.py +1271 -221
- package/runtime/plugins/agent-pack/runtime/agenthelm_runtime.py +114 -65
- package/runtime/plugins/agent-pack/runtime/i18n_agent_pack.py +78 -0
- package/runtime/plugins/agent-pack/runtime/local_only.py +1132 -0
- package/runtime/plugins/agent-pack/runtime/locale/en.json +569 -0
- package/runtime/plugins/agent-pack/runtime/mcp_server.py +25 -0
- package/runtime/plugins/agent-pack/runtime/nudge_text.py +127 -0
- package/runtime/plugins/agent-pack/runtime/user_settings.py +275 -0
- package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +11 -1
- package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agents-init/content.json +4 -4
- package/runtime/plugins/agents-init/plugin.json +1 -1
- package/runtime/plugins/agents-init/skills/agents-init/AGENT.template.md +141 -5
- package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +41 -8
- package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +408 -80
- package/runtime/plugins/agents-init/skills/agents-init/scripts/adopt.py +615 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +221 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/i18n_init.py +78 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +748 -159
- package/runtime/plugins/agents-init/skills/agents-init/scripts/locale/en.json +289 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/merge3.py +149 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/regions.py +99 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/scaffold.py +594 -90
- package/runtime/plugins/agents-init/skills/agents-init/skeleton.json +2 -0
- package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
- package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/references/inbox.en.md +48 -0
- package/runtime/plugins/opinion-manager/references/inbox.md +48 -0
- package/runtime/plugins/opinion-manager/runtime/context.py +31 -26
- package/runtime/plugins/opinion-manager/runtime/i18n_opinion.py +78 -0
- package/runtime/plugins/opinion-manager/runtime/inbox.py +398 -0
- package/runtime/plugins/opinion-manager/runtime/inbox_text.py +114 -0
- package/runtime/plugins/opinion-manager/runtime/lifecycle.py +45 -44
- package/runtime/plugins/opinion-manager/runtime/locale/en.json +193 -0
- package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +55 -50
- package/runtime/plugins/opinion-manager/runtime/versioned.py +90 -85
- package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +15 -2
- package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/content.json +30 -3
- package/runtime/plugins/project-orchestrator/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/references/case-workspaces.md +9 -1
- package/runtime/plugins/project-orchestrator/references/case.schema.json +1 -0
- package/runtime/plugins/project-orchestrator/references/sop-interview.md +83 -0
- package/runtime/plugins/project-orchestrator/references/sop.md +156 -0
- package/runtime/plugins/project-orchestrator/runtime/assets.py +52 -57
- package/runtime/plugins/project-orchestrator/runtime/case.py +139 -80
- package/runtime/plugins/project-orchestrator/runtime/case_structure.py +71 -0
- package/runtime/plugins/project-orchestrator/runtime/case_workspace.py +47 -46
- package/runtime/plugins/project-orchestrator/runtime/i18n_orchestrator.py +78 -0
- package/runtime/plugins/project-orchestrator/runtime/locale/en.json +1450 -0
- package/runtime/plugins/project-orchestrator/runtime/memory.py +45 -45
- package/runtime/plugins/project-orchestrator/runtime/private_paths.py +119 -0
- package/runtime/plugins/project-orchestrator/runtime/project_base.py +37 -19
- package/runtime/plugins/project-orchestrator/runtime/project_cli.py +307 -195
- package/runtime/plugins/project-orchestrator/runtime/project_demo.py +130 -48
- package/runtime/plugins/project-orchestrator/runtime/project_maintain.py +328 -221
- package/runtime/plugins/project-orchestrator/runtime/project_menu.py +167 -89
- package/runtime/plugins/project-orchestrator/runtime/project_real.py +187 -105
- package/runtime/plugins/project-orchestrator/runtime/project_write.py +58 -55
- package/runtime/plugins/project-orchestrator/runtime/sop.py +1670 -0
- package/runtime/plugins/project-orchestrator/runtime/sop_structure.py +226 -0
- package/runtime/plugins/project-orchestrator/runtime/wf.py +74 -70
- package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +22 -0
- package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.en.md +57 -0
- package/runtime/plugins/project-orchestrator/sop-templates/blank/SOP.md +57 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.en.md +77 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/SOP.md +77 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.en.md +11 -0
- package/runtime/plugins/project-orchestrator/sop-templates/knowledge-digest/templates/digest.md +11 -0
- package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.en.md +87 -0
- package/runtime/plugins/project-orchestrator/sop-templates/video-to-transcript/SOP.md +87 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.en.md +75 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/SOP.md +75 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.en.md +11 -0
- package/runtime/plugins/project-orchestrator/sop-templates/weekly-review/templates/review.md +12 -0
- package/runtime/plugins/project-orchestrator/templates/CASE.en.md +39 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/test_init_project.py +0 -678
- package/runtime/plugins/agents-init/skills/agents-init/scripts/test_scaffold.py +0 -551
|
@@ -24,6 +24,9 @@ import sys
|
|
|
24
24
|
from datetime import datetime
|
|
25
25
|
from pathlib import Path
|
|
26
26
|
from typing import Any
|
|
27
|
+
if str(Path(__file__).resolve().parent) not in sys.path: # also loaded by path from other plugins
|
|
28
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
29
|
+
from i18n_init import _ # noqa: E402
|
|
27
30
|
|
|
28
31
|
HERE = Path(__file__).resolve().parent
|
|
29
32
|
MANIFEST_PATH = HERE.parent / "skeleton.json"
|
|
@@ -38,6 +41,15 @@ SF_DATALESS = 0x40000000
|
|
|
38
41
|
init: Any = None # init_project 模块;由 bind() 或首次使用时加载
|
|
39
42
|
|
|
40
43
|
|
|
44
|
+
def _regions() -> Any:
|
|
45
|
+
here = str(HERE)
|
|
46
|
+
if here not in sys.path:
|
|
47
|
+
sys.path.insert(0, here)
|
|
48
|
+
import regions # noqa: PLC0415
|
|
49
|
+
|
|
50
|
+
return regions
|
|
51
|
+
|
|
52
|
+
|
|
41
53
|
def _load_default() -> Any:
|
|
42
54
|
name = "agenthelm_init_project"
|
|
43
55
|
path = HERE / "init_project.py"
|
|
@@ -82,9 +94,9 @@ def load_manifest() -> dict:
|
|
|
82
94
|
try:
|
|
83
95
|
manifest = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
|
|
84
96
|
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
85
|
-
raise _fail(
|
|
97
|
+
raise _fail(_("无法读取期望骨架清单:{0}").format(MANIFEST_PATH), "template-invalid") from exc
|
|
86
98
|
if not isinstance(manifest, dict) or not isinstance(manifest.get("files"), list):
|
|
87
|
-
raise _fail("期望骨架清单格式不对", "template-invalid")
|
|
99
|
+
raise _fail(_("期望骨架清单格式不对"), "template-invalid")
|
|
88
100
|
return manifest
|
|
89
101
|
|
|
90
102
|
|
|
@@ -143,7 +155,15 @@ class Context:
|
|
|
143
155
|
case = work.get("case") if isinstance(work.get("case"), dict) else {}
|
|
144
156
|
memory = self.profile.get("memory") if isinstance(self.profile.get("memory"), dict) else {}
|
|
145
157
|
self.case_root = case.get("root") if _relative_ok(case.get("root")) else "cases"
|
|
158
|
+
# 项目声明了自己的 Case 工具:Case 目录结构由它负责,不再按默认结构要求。
|
|
159
|
+
self.own_case_tool = bool(case.get("command"))
|
|
146
160
|
self.memory_root = memory.get("root") if _relative_ok(memory.get("root")) else "memory"
|
|
161
|
+
sop = self.profile.get("sop") if isinstance(self.profile.get("sop"), dict) else None
|
|
162
|
+
privacy = self.profile.get("privacy") if isinstance(self.profile.get("privacy"), dict) else {}
|
|
163
|
+
reads = privacy.get("forbidden_default_reads") if isinstance(privacy.get("forbidden_default_reads"), list) else []
|
|
164
|
+
self.private_declared = any(isinstance(item, str) and item.strip().strip("/") == "private" for item in reads)
|
|
165
|
+
self.sop_declared = sop is not None
|
|
166
|
+
self.sop_root = sop.get("root") if sop is not None and _relative_ok(sop.get("root")) else "sops"
|
|
147
167
|
self.rendered = self._rendered()
|
|
148
168
|
self.fresh = json.loads(self.rendered[module.PROFILE_PATH])
|
|
149
169
|
self.pack = module.contract_pack()
|
|
@@ -164,12 +184,18 @@ class Context:
|
|
|
164
184
|
tuple(details.get("stack") or ()), str(details.get("runtime") or ""),
|
|
165
185
|
tuple(details.get("agent_cli") or ()), str(work.get("mode") or "legacy"),
|
|
166
186
|
module._profile_launcher(self.profile),
|
|
187
|
+
module.project_language(self.profile), module.privacy_declared_in(self.profile),
|
|
167
188
|
)
|
|
168
189
|
|
|
169
190
|
def _rendered(self) -> dict[Path, str]:
|
|
170
191
|
files = _init().files_for(self.inputs)
|
|
171
192
|
files.pop(Path("cases/.gitkeep"), None)
|
|
172
193
|
files.pop(Path("memory/.gitkeep"), None)
|
|
194
|
+
files.pop(Path("sops/.gitkeep"), None)
|
|
195
|
+
if not self.private_declared:
|
|
196
|
+
files.pop(Path("private/.gitignore"), None) # 老项目没有声明私有目录:不要求,也不产生新差异
|
|
197
|
+
if self.sop_declared:
|
|
198
|
+
files[Path(self.sop_root) / ".gitkeep"] = ""
|
|
173
199
|
if self.inputs.work_mode == "case-workspace":
|
|
174
200
|
files[Path(self.case_root) / ".gitkeep"] = ""
|
|
175
201
|
files[Path(self.memory_root) / ".gitkeep"] = ""
|
|
@@ -180,11 +206,16 @@ class Context:
|
|
|
180
206
|
resolved = []
|
|
181
207
|
for entry in self.manifest["files"]:
|
|
182
208
|
when = entry.get("when")
|
|
183
|
-
if when == "case-workspace" and self.inputs.work_mode != "case-workspace":
|
|
209
|
+
if when == "case-workspace" and (self.inputs.work_mode != "case-workspace" or self.own_case_tool):
|
|
184
210
|
continue
|
|
185
211
|
if when == "entry" and not self.inputs.entry_launcher:
|
|
186
212
|
continue
|
|
213
|
+
if when == "private" and not self.private_declared:
|
|
214
|
+
continue
|
|
215
|
+
if when == "sop" and not self.sop_declared:
|
|
216
|
+
continue # 旧项目没有声明 sop 段:不要求 sops/,也不产生新的差异
|
|
187
217
|
path = (entry["path"].replace("{case_root}", self.case_root).replace("{memory_root}", self.memory_root)
|
|
218
|
+
.replace("{sop_root}", self.sop_root)
|
|
188
219
|
.replace("{launcher}", self.inputs.entry_launcher or ""))
|
|
189
220
|
text = self.rendered.get(Path(path))
|
|
190
221
|
resolved.append({**entry, "path": path, "fingerprint": sha(text if text is not None else path)})
|
|
@@ -199,7 +230,7 @@ class Context:
|
|
|
199
230
|
def _lstat(path: Path) -> os.stat_result | None:
|
|
200
231
|
try:
|
|
201
232
|
return path.lstat()
|
|
202
|
-
except FileNotFoundError:
|
|
233
|
+
except (FileNotFoundError, NotADirectoryError): # a user file standing where a parent directory should be
|
|
203
234
|
return None
|
|
204
235
|
|
|
205
236
|
|
|
@@ -243,14 +274,77 @@ def _skeleton_state(ctx: Context, entry: dict, baseline: dict[str, str]) -> str:
|
|
|
243
274
|
return "ok"
|
|
244
275
|
|
|
245
276
|
|
|
277
|
+
def _text_of(path: Path) -> str | None:
|
|
278
|
+
if _lstat(path) is None or path.is_symlink() or not path.is_file():
|
|
279
|
+
return None
|
|
280
|
+
try:
|
|
281
|
+
return path.read_text(encoding="utf-8")
|
|
282
|
+
except (OSError, UnicodeDecodeError):
|
|
283
|
+
return None
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def region_rows(root: Path, pack_entry: dict | None, language: str = "zh") -> list[dict]:
|
|
287
|
+
"""State of every managed region the lock says this tool put into a file the user owns."""
|
|
288
|
+
module, regions = _init(), _regions()
|
|
289
|
+
templates = module.load_templates()
|
|
290
|
+
rows = []
|
|
291
|
+
for path, ids in sorted(((pack_entry or {}).get("regions") or {}).items()):
|
|
292
|
+
text = _text_of(root / path)
|
|
293
|
+
for region_id, recorded in sorted(ids.items()):
|
|
294
|
+
if f"region/{region_id}" not in templates:
|
|
295
|
+
continue
|
|
296
|
+
template = module.localized(templates, f"region/{region_id}", language)
|
|
297
|
+
expected = regions.digest(template)
|
|
298
|
+
region = regions.get(text, region_id) if text is not None else None
|
|
299
|
+
if region is None:
|
|
300
|
+
state = "missing"
|
|
301
|
+
elif not region.intact or region.digest != recorded:
|
|
302
|
+
state = "modified"
|
|
303
|
+
elif region.digest != expected:
|
|
304
|
+
state = "outdated"
|
|
305
|
+
else:
|
|
306
|
+
state = "ok"
|
|
307
|
+
rows.append({"path": path, "id": region_id, "state": state, "expected": expected,
|
|
308
|
+
"fingerprint": sha(f"{path}#{region_id}:{expected}")})
|
|
309
|
+
return rows
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _check_privacy(ctx: Context, root: Path) -> list[dict]:
|
|
313
|
+
"""AGENTS.md's privacy convention against the Profile's ``privacy.forbidden_default_reads``.
|
|
314
|
+
|
|
315
|
+
The convention names the field instead of copying the paths, so only the field going empty or non-empty makes
|
|
316
|
+
the text wrong. Anything the user wrote themselves about the field counts as their own convention.
|
|
317
|
+
"""
|
|
318
|
+
module = _init()
|
|
319
|
+
text = _text_of(root / "AGENTS.md")
|
|
320
|
+
privacy = ctx.profile.get("privacy") if isinstance(ctx.profile.get("privacy"), dict) else {}
|
|
321
|
+
if text is None or not isinstance(privacy.get("forbidden_default_reads"), list):
|
|
322
|
+
return [] # 字段缺失由 profile-missing 报告,不重复
|
|
323
|
+
declared = ctx.inputs.privacy_declared
|
|
324
|
+
state = module.privacy_convention_state(text, module.load_templates())
|
|
325
|
+
if declared and state == "absent":
|
|
326
|
+
kind, title = "privacy-contract-missing", _("AGENTS.md 没有隐私约定,Profile 已声明私有路径")
|
|
327
|
+
reason = _("Profile 的 privacy.forbidden_default_reads 非空,但 AGENTS.md 没有写默认不读、先经用户确认的约定;update-content --append AGENTS.md 可以保留原文并补上")
|
|
328
|
+
elif declared and state == "undeclared":
|
|
329
|
+
kind, title = "privacy-contract-stale", _("AGENTS.md 写着未声明私有路径,Profile 已声明")
|
|
330
|
+
reason = _("Profile 的 privacy.forbidden_default_reads 已非空;update-content 刷新 AGENTS.md 的隐私约定(改过的文件用 --append)")
|
|
331
|
+
elif not declared and state == "declared":
|
|
332
|
+
kind, title = "privacy-contract-stale", _("AGENTS.md 写着私有路径约定,Profile 的 privacy.forbidden_default_reads 为空")
|
|
333
|
+
reason = _("字段为空表示没有私有路径;update-content 刷新 AGENTS.md,或把路径写回该字段")
|
|
334
|
+
else:
|
|
335
|
+
return []
|
|
336
|
+
return [_finding("privacy-contract", kind, title, reason, sha(f"privacy-contract:{kind}:{declared}"), "update-content",
|
|
337
|
+
path="AGENTS.md")]
|
|
338
|
+
|
|
339
|
+
|
|
246
340
|
def _check_profile(ctx: Context) -> list[dict]:
|
|
247
341
|
work_mode = ctx.inputs.work_mode
|
|
248
342
|
rows = []
|
|
249
343
|
for rule in ctx.manifest.get("profile", []):
|
|
250
|
-
if rule.get("when") == "case-workspace" and work_mode != "case-workspace":
|
|
344
|
+
if rule.get("when") == "case-workspace" and (work_mode != "case-workspace" or ctx.own_case_tool):
|
|
251
345
|
continue
|
|
252
346
|
present, value = _get(ctx.profile, rule["path"])
|
|
253
|
-
|
|
347
|
+
_found, default = _get(ctx.fresh, rule["path"])
|
|
254
348
|
mode = rule["mode"]
|
|
255
349
|
if mode == "default" and default is None:
|
|
256
350
|
mode = "manual"
|
|
@@ -273,15 +367,49 @@ def _check_profile(ctx: Context) -> list[dict]:
|
|
|
273
367
|
return rows
|
|
274
368
|
|
|
275
369
|
|
|
276
|
-
|
|
277
|
-
|
|
370
|
+
# Profile fields other plugins read although the schema does not declare them (path or prefix -> plugin).
|
|
371
|
+
# Declare them in project.schema.json; this list only keeps a project whose schema copy is older from calling them "own".
|
|
372
|
+
READ_BY_OTHER_PLUGINS = {"opinion.nudge": "agent-pack"}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _edit_distance(a: str, b: str) -> int:
|
|
376
|
+
previous = list(range(len(b) + 1))
|
|
377
|
+
for i, ca in enumerate(a, 1):
|
|
378
|
+
current = [i]
|
|
379
|
+
for j, cb in enumerate(b, 1):
|
|
380
|
+
current.append(min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (ca != cb)))
|
|
381
|
+
previous = current
|
|
382
|
+
return previous[-1]
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _likely_typo(key: str, declared: list[str]) -> str | None:
|
|
386
|
+
"""The declared sibling this key is probably a misspelling of (edit distance 1, or 2 for long names)."""
|
|
387
|
+
if key in declared or len(key) < 4:
|
|
388
|
+
return None
|
|
389
|
+
limit = 1 if len(key) <= 6 else 2
|
|
390
|
+
best = min(((_edit_distance(key.lower(), name.lower()), name) for name in declared), default=(limit + 1, ""))
|
|
391
|
+
return best[1] if best[0] <= limit else None
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _profile_extras(ctx: Context) -> list[dict]:
|
|
395
|
+
"""Profile fields the schema does not declare, sorted into: the project's own, suspected typos, read by another plugin."""
|
|
278
396
|
try:
|
|
279
397
|
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
280
398
|
except (OSError, ValueError):
|
|
281
399
|
return []
|
|
282
400
|
known = set(ctx.manifest.get("audit_fields", [])) | set(ctx.manifest.get("opinion_fields", [])) \
|
|
283
401
|
| {rule["path"] for rule in ctx.manifest.get("profile", [])}
|
|
284
|
-
extras: list[
|
|
402
|
+
extras: list[dict] = []
|
|
403
|
+
|
|
404
|
+
def classify(dotted: str, key: str, props: dict, prefix: str) -> dict:
|
|
405
|
+
for declared_path, plugin in READ_BY_OTHER_PLUGINS.items():
|
|
406
|
+
if dotted == declared_path or dotted.startswith(declared_path + "."):
|
|
407
|
+
return {"path": dotted, "kind": "project-field", "category": "read-by-plugin", "plugin": plugin, "similar_to": None}
|
|
408
|
+
similar = _likely_typo(key, sorted(props))
|
|
409
|
+
if similar:
|
|
410
|
+
return {"path": dotted, "kind": "project-field", "category": "suspected-typo", "plugin": None,
|
|
411
|
+
"similar_to": f"{prefix}{similar}"}
|
|
412
|
+
return {"path": dotted, "kind": "project-field", "category": "own", "plugin": None, "similar_to": None}
|
|
285
413
|
|
|
286
414
|
def walk(value: dict, props: dict, prefix: str) -> None:
|
|
287
415
|
for key, child in value.items():
|
|
@@ -289,12 +417,135 @@ def _project_fields(ctx: Context) -> list[str]:
|
|
|
289
417
|
declared = props.get(key)
|
|
290
418
|
if declared is None:
|
|
291
419
|
if not any(item == dotted or item.startswith(dotted + ".") for item in known):
|
|
292
|
-
extras.append(dotted)
|
|
420
|
+
extras.append(classify(dotted, key, props, prefix))
|
|
293
421
|
elif isinstance(child, dict) and isinstance(declared.get("properties"), dict):
|
|
294
422
|
walk(child, declared["properties"], dotted + ".")
|
|
295
423
|
|
|
296
424
|
walk(ctx.profile, schema.get("properties") or {}, "")
|
|
297
|
-
return sorted(extras)
|
|
425
|
+
return sorted(extras, key=lambda item: item["path"])
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _project_fields(ctx: Context) -> list[str]:
|
|
429
|
+
"""Profile fields the scaffold does not know: the project's own, never compared."""
|
|
430
|
+
return [item["path"] for item in _profile_extras(ctx)]
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _extras_summary(extras: list[dict]) -> dict:
|
|
434
|
+
fields = [item for item in extras if item["kind"] == "project-field"]
|
|
435
|
+
return {"total": len(fields),
|
|
436
|
+
"own": sum(item["category"] == "own" for item in fields),
|
|
437
|
+
"suspected_typo": sum(item["category"] == "suspected-typo" for item in fields),
|
|
438
|
+
"read_by_plugin": sum(item["category"] == "read-by-plugin" for item in fields)}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
# A Profile value whose shape differs from what the schema now declares. The tool never rewrites it.
|
|
442
|
+
SHAPE_SKIP_DESCENT = {"work.case.directory_naming"} # has its own check (case_naming_spec)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _resolve(node: Any, defs: dict) -> Any:
|
|
446
|
+
ref = node.get("$ref") if isinstance(node, dict) else None
|
|
447
|
+
if isinstance(ref, str) and ref.startswith("#/$defs/"):
|
|
448
|
+
return defs.get(ref.rsplit("/", 1)[-1], node)
|
|
449
|
+
return node
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _json_kind(value: Any) -> str:
|
|
453
|
+
if isinstance(value, bool):
|
|
454
|
+
return "boolean"
|
|
455
|
+
if isinstance(value, int):
|
|
456
|
+
return "integer"
|
|
457
|
+
return {str: "string", list: "array", dict: "object", float: "number"}.get(type(value), "object")
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _matches_type(value: Any, name: str) -> bool:
|
|
461
|
+
kind = _json_kind(value)
|
|
462
|
+
return kind == name or (name == "number" and kind in ("integer", "number"))
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _shape_problem(value: Any, node: Any, defs: dict) -> str | None:
|
|
466
|
+
"""Why ``value`` does not fit the declared type or enum; None when it fits or the schema says nothing simple."""
|
|
467
|
+
node = _resolve(node, defs)
|
|
468
|
+
if not isinstance(node, dict):
|
|
469
|
+
return None
|
|
470
|
+
if "anyOf" in node:
|
|
471
|
+
branches = [_resolve(branch, defs) for branch in node["anyOf"]]
|
|
472
|
+
if any(_shape_problem(value, branch, defs) is None for branch in branches):
|
|
473
|
+
return None
|
|
474
|
+
return " | ".join(filter(None, (_describe(branch) for branch in branches)))
|
|
475
|
+
types = node.get("type")
|
|
476
|
+
types = [types] if isinstance(types, str) else list(types or [])
|
|
477
|
+
if types and not any(_matches_type(value, name) for name in types):
|
|
478
|
+
return _describe(node)
|
|
479
|
+
if "enum" in node and value not in node["enum"]:
|
|
480
|
+
return _describe(node)
|
|
481
|
+
return None
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _describe(node: Any) -> str:
|
|
485
|
+
if not isinstance(node, dict):
|
|
486
|
+
return ""
|
|
487
|
+
if "enum" in node:
|
|
488
|
+
return " / ".join(json.dumps(item, ensure_ascii=False) for item in node["enum"])
|
|
489
|
+
types = node.get("type")
|
|
490
|
+
return "/".join([types] if isinstance(types, str) else list(types or []))
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _example_for(node: Any, defs: dict) -> Any:
|
|
494
|
+
node = _resolve(node, defs)
|
|
495
|
+
if not isinstance(node, dict):
|
|
496
|
+
return None
|
|
497
|
+
if "enum" in node:
|
|
498
|
+
return node["enum"][0]
|
|
499
|
+
types = node.get("type")
|
|
500
|
+
first = (types if isinstance(types, str) else (types or ["string"])[0])
|
|
501
|
+
return {"object": {}, "array": [], "string": "...", "boolean": True, "integer": 1, "number": 1}.get(first)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _naming_example() -> dict:
|
|
505
|
+
return {"style": "date-topic"}
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _naming_hint() -> str:
|
|
509
|
+
return _("可用写法:{0} 或 {1};要保留原文字不改动:把它移到你自己的字段名下(如 work.case.project_directory_naming),再删掉这一项").format(
|
|
510
|
+
json.dumps(_naming_example(), ensure_ascii=False),
|
|
511
|
+
json.dumps({"style": "custom", "pattern": r"^CASE-[0-9]{8}-.+$"}, ensure_ascii=False))
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _profile_conflicts(ctx: Context) -> list[dict]:
|
|
515
|
+
"""Values the project wrote before the schema declared the field, whose shape no longer fits: information only."""
|
|
516
|
+
try:
|
|
517
|
+
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
|
518
|
+
except (OSError, ValueError):
|
|
519
|
+
return []
|
|
520
|
+
defs = schema.get("$defs") or {}
|
|
521
|
+
skip = {rule["path"] for rule in ctx.manifest.get("profile", [])} | set(ctx.manifest.get("audit_fields", []))
|
|
522
|
+
found: list[dict] = []
|
|
523
|
+
|
|
524
|
+
def walk(value: dict, props: dict, prefix: str) -> None:
|
|
525
|
+
for key, child in value.items():
|
|
526
|
+
node = _resolve(props.get(key), defs)
|
|
527
|
+
dotted = f"{prefix}{key}"
|
|
528
|
+
if not isinstance(node, dict) or dotted in skip or child is None:
|
|
529
|
+
continue
|
|
530
|
+
problem = _shape_problem(child, node, defs)
|
|
531
|
+
if problem:
|
|
532
|
+
found.append(_conflict(dotted, key, prefix, problem, child, node, defs))
|
|
533
|
+
elif isinstance(child, dict) and isinstance(node.get("properties"), dict) and dotted not in SHAPE_SKIP_DESCENT:
|
|
534
|
+
walk(child, node["properties"], dotted + ".")
|
|
535
|
+
|
|
536
|
+
walk(ctx.profile, schema.get("properties") or {}, "")
|
|
537
|
+
return sorted(found, key=lambda item: item["path"])
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _conflict(dotted: str, key: str, prefix: str, expected: str, value: Any, node: dict, defs: dict) -> dict:
|
|
541
|
+
example = _naming_example() if dotted == "work.case.directory_naming" else _example_for(node, defs)
|
|
542
|
+
rename_to = f"{prefix}project_{key}"
|
|
543
|
+
return {"id": f"conflict:{dotted}", "kind": "profile-conflict", "level": "info", "path": dotted,
|
|
544
|
+
"expected": expected, "found": _json_kind(value), "example": example, "rename_to": rename_to,
|
|
545
|
+
"options": ["convert", "keep-as-own-field", "ignore"],
|
|
546
|
+
"message": _("Profile 的 {0} 是{1},schema 现在把它声明为 {2}:它按项目自定义处理,工具不读取、不检查,也不会改写你的值。"
|
|
547
|
+
"三个选项:转换成 {2} 的写法(例如 {3});保留为项目自有字段(改名,如 {4});忽略(什么都不用做,不影响退出码)").format(
|
|
548
|
+
dotted, _json_kind(value), expected, json.dumps(example, ensure_ascii=False), rename_to)}
|
|
298
549
|
|
|
299
550
|
|
|
300
551
|
# ---------------------------------------------------------------- decisions
|
|
@@ -311,21 +562,21 @@ def default_state_dir() -> Path:
|
|
|
311
562
|
def read_decisions(path: Path) -> tuple[dict[str, dict], str | None, str | None]:
|
|
312
563
|
"""(decisions, sha256 of the file text or None, error)."""
|
|
313
564
|
if path.is_symlink():
|
|
314
|
-
return {}, None,
|
|
565
|
+
return {}, None, _("拒绝符号链接:{0}").format(path.name)
|
|
315
566
|
try:
|
|
316
567
|
text = path.read_text(encoding="utf-8")
|
|
317
568
|
except FileNotFoundError:
|
|
318
569
|
return {}, None, None
|
|
319
570
|
except (OSError, UnicodeDecodeError) as exc:
|
|
320
|
-
return {}, None,
|
|
571
|
+
return {}, None, _("决定文件无法读取:{0}").format(exc)
|
|
321
572
|
try:
|
|
322
573
|
data = json.loads(text)
|
|
323
574
|
except ValueError as exc:
|
|
324
|
-
return {}, sha(text),
|
|
575
|
+
return {}, sha(text), _("决定文件不是合法 JSON:{0}").format(exc)
|
|
325
576
|
table = data.get("decisions") if isinstance(data, dict) else None
|
|
326
577
|
if not isinstance(table, dict) or not all(isinstance(item, dict) and item.get("decision") in DECISION_VALUES
|
|
327
578
|
for item in table.values()):
|
|
328
|
-
return {}, sha(text), "决定文件格式不对(需要 decisions 对象,decision 为 skip / keep / later)"
|
|
579
|
+
return {}, sha(text), _("决定文件格式不对(需要 decisions 对象,decision 为 skip / keep / later)")
|
|
329
580
|
return table, sha(text), None
|
|
330
581
|
|
|
331
582
|
|
|
@@ -371,7 +622,7 @@ def partition(findings: list[dict], decisions: dict, *, reprompt: bool = False)
|
|
|
371
622
|
|
|
372
623
|
def keep_fingerprints(root: Path) -> dict[str, str]:
|
|
373
624
|
"""Files the user chose to keep, with the expected-content fingerprint of that moment (refresh honours them)."""
|
|
374
|
-
table,
|
|
625
|
+
table, _decisions, error = read_decisions(root / DECISIONS_PATH)
|
|
375
626
|
if error:
|
|
376
627
|
return {}
|
|
377
628
|
return {key[len("content:"):]: item["fingerprint"] for key, item in table.items()
|
|
@@ -396,21 +647,22 @@ def case_naming_spec(profile: dict) -> dict:
|
|
|
396
647
|
if declared is None:
|
|
397
648
|
return {"style": "case-id", "pattern": CASE_STYLES["case-id"], "declared": False, "error": None}
|
|
398
649
|
if not isinstance(declared, dict):
|
|
399
|
-
|
|
650
|
+
# Written before the schema declared it: the project's own text. Not an error; the tool does not check names.
|
|
651
|
+
return {"style": None, "pattern": None, "declared": True, "free_text": True, "error": None}
|
|
400
652
|
pattern = declared.get("pattern")
|
|
401
653
|
style = declared.get("style") or ("custom" if pattern else "case-id")
|
|
402
654
|
if style not in (*CASE_STYLES, "custom"):
|
|
403
655
|
return {"style": style, "pattern": None, "declared": True,
|
|
404
|
-
"error": "style 只能是 case-id / date-topic / custom"}
|
|
656
|
+
"error": _("style 只能是 case-id / date-topic / custom")}
|
|
405
657
|
if pattern is not None and not isinstance(pattern, str):
|
|
406
|
-
return {"style": style, "pattern": None, "declared": True, "error": "pattern 必须是字符串(正则,匹配整个目录名)"}
|
|
658
|
+
return {"style": style, "pattern": None, "declared": True, "error": _("pattern 必须是字符串(正则,匹配整个目录名)")}
|
|
407
659
|
if style == "custom" and not pattern:
|
|
408
|
-
return {"style": style, "pattern": None, "declared": True, "error": "style 为 custom 时需要 pattern"}
|
|
660
|
+
return {"style": style, "pattern": None, "declared": True, "error": _("style 为 custom 时需要 pattern")}
|
|
409
661
|
pattern = pattern or CASE_STYLES[style]
|
|
410
662
|
try:
|
|
411
663
|
re.compile(pattern)
|
|
412
664
|
except re.error as exc:
|
|
413
|
-
return {"style": style, "pattern": pattern, "declared": True, "error":
|
|
665
|
+
return {"style": style, "pattern": pattern, "declared": True, "error": _("pattern 不是合法正则:{0}").format(exc)}
|
|
414
666
|
return {"style": style, "pattern": pattern, "declared": True, "error": None}
|
|
415
667
|
|
|
416
668
|
|
|
@@ -426,7 +678,9 @@ def check_case_naming(ctx: Context) -> dict:
|
|
|
426
678
|
spec = case_naming_spec(ctx.profile)
|
|
427
679
|
names = _case_directories(ctx)
|
|
428
680
|
mismatched = []
|
|
429
|
-
|
|
681
|
+
# 项目自带 Case 工具又没有声明命名规则:命名归它管,不拿默认的 CASE-日期-序号-主题去比。
|
|
682
|
+
own_naming = ctx.own_case_tool and not spec["declared"]
|
|
683
|
+
if spec["error"] is None and spec["pattern"] and ctx.inputs.work_mode == "case-workspace" and not own_naming:
|
|
430
684
|
compiled = re.compile(spec["pattern"])
|
|
431
685
|
mismatched = [name for name in names if not compiled.fullmatch(name)]
|
|
432
686
|
return {**spec, "root": ctx.case_root, "directories": len(names), "mismatched": mismatched[:200],
|
|
@@ -484,6 +738,9 @@ def case_naming_plan(root: Path) -> dict:
|
|
|
484
738
|
"error": naming["error"], "renames": [], "declaration_hint": None, "moves_directories": False}
|
|
485
739
|
if naming["error"]:
|
|
486
740
|
return result
|
|
741
|
+
if naming.get("free_text"):
|
|
742
|
+
result["note"] = _("work.case.directory_naming 是项目自己的文字,工具不检查目录命名,也没有改名计划")
|
|
743
|
+
return result
|
|
487
744
|
names = _case_directories(ctx)
|
|
488
745
|
taken = set(names)
|
|
489
746
|
mismatched = naming["mismatched"]
|
|
@@ -494,14 +751,14 @@ def case_naming_plan(root: Path) -> dict:
|
|
|
494
751
|
taken.add(suggestion)
|
|
495
752
|
result["renames"].append({"from": f"{ctx.case_root}/{name}", "to": f"{ctx.case_root}/{suggestion}" if suggestion else None,
|
|
496
753
|
"references": refs.get(name, []),
|
|
497
|
-
"note": "" if suggestion else "名称里没有日期或主题,需要你自己决定新名字",
|
|
754
|
+
"note": "" if suggestion else _("名称里没有日期或主题,需要你自己决定新名字"),
|
|
498
755
|
})
|
|
499
756
|
if not naming["declared"] and mismatched:
|
|
500
757
|
names_style = "date-topic" if all(re.fullmatch(CASE_STYLES["date-topic"], n) for n in mismatched) else "custom"
|
|
501
758
|
result["declaration_hint"] = {
|
|
502
759
|
"if_this_is_your_convention": {"work": {"case": {"directory_naming": (
|
|
503
|
-
{"style": "date-topic"} if names_style == "date-topic" else {"style": "custom", "pattern": "<匹配全部目录名的正则>"})}}},
|
|
504
|
-
"note": "目录名是你的约定的话,在 Profile 里声明它(fix profile 不会替你写这一项),之后 check 按声明检查"}
|
|
760
|
+
{"style": "date-topic"} if names_style == "date-topic" else {"style": "custom", "pattern": _("<匹配全部目录名的正则>")})}}},
|
|
761
|
+
"note": _("目录名是你的约定的话,在 Profile 里声明它(fix profile 不会替你写这一项),之后 check 按声明检查")}
|
|
505
762
|
return result
|
|
506
763
|
|
|
507
764
|
|
|
@@ -524,6 +781,9 @@ def fingerprint(report: dict) -> dict:
|
|
|
524
781
|
for row in report["profile"]:
|
|
525
782
|
if f"profile:{row['field']}" not in skipped:
|
|
526
783
|
detail[f"profile:{row['field']}"] = row["state"]
|
|
784
|
+
for row in report.get("regions", []):
|
|
785
|
+
if f"region:{row['path']}#{row['id']}" not in skipped:
|
|
786
|
+
detail[f"region:{row['path']}#{row['id']}"] = row["state"]
|
|
527
787
|
lock = report["lock"]
|
|
528
788
|
if lock["pack"] and f"lock:{lock['pack']}" not in skipped:
|
|
529
789
|
detail["lock:version"] = f"{lock['status']}@{lock['version']}"
|
|
@@ -542,22 +802,80 @@ def explain(mine: dict[str, str], theirs: dict[str, str]) -> list[str]:
|
|
|
542
802
|
if mine.get(key) == theirs.get(key):
|
|
543
803
|
continue
|
|
544
804
|
if key not in theirs:
|
|
545
|
-
lines.append(
|
|
805
|
+
lines.append(_("{0}:只有这台有({1})").format(key, mine[key]))
|
|
546
806
|
elif key not in mine:
|
|
547
|
-
lines.append(
|
|
807
|
+
lines.append(_("{0}:只有对方有({1})").format(key, theirs[key]))
|
|
548
808
|
elif key.startswith("expected:"):
|
|
549
|
-
lines.append(
|
|
809
|
+
lines.append(_("{0}:期望清单版本不同——这台 {1},对方 {2}(先把两边的 agents-init 更新到同一版本)").format(key, mine[key], theirs[key]))
|
|
550
810
|
else:
|
|
551
|
-
lines.append(
|
|
811
|
+
lines.append(_("{0}:这台 {1},对方 {2}").format(key, mine[key], theirs[key]))
|
|
552
812
|
return lines
|
|
553
813
|
|
|
554
814
|
|
|
555
815
|
# ---------------------------------------------------------------- check
|
|
556
816
|
|
|
817
|
+
# 发现分三级(沿用 health 的 level 词汇):must 会影响使用,参与退出码、--strict 与会话开始提示;
|
|
818
|
+
# suggest 是脚手架风格上的可选项;info 只是提示。其余类型一律按可选处理。
|
|
819
|
+
LEVEL_BY_KIND = {"profile-invalid": "must", "region-outdated": "info"}
|
|
820
|
+
CATEGORY_BY_KIND = {"skeleton-missing": "skeleton", "content-differs": "content", "region-missing": "region",
|
|
821
|
+
"region-modified": "region", "region-outdated": "region", "profile-missing": "profile",
|
|
822
|
+
"profile-invalid": "profile", "case-naming": "case-naming", "lock-version": "lock",
|
|
823
|
+
"privacy-contract-missing": "content", "privacy-contract-stale": "content"}
|
|
824
|
+
LEVEL_ORDER = ("must", "suggest", "info")
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def level_of(kind: str) -> str:
|
|
828
|
+
return LEVEL_BY_KIND.get(kind, "suggest")
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def category_of(kind: str) -> str:
|
|
832
|
+
if kind.startswith("profile-"):
|
|
833
|
+
return "profile"
|
|
834
|
+
return CATEGORY_BY_KIND.get(kind, kind)
|
|
835
|
+
|
|
836
|
+
|
|
557
837
|
def _finding(identifier: str, kind: str, title: str, reason: str, fingerprint: str, fix: str | None,
|
|
558
838
|
**extra: Any) -> dict:
|
|
559
|
-
return {"id": identifier, "kind": kind, "level": "
|
|
560
|
-
"reason": reason, "fingerprint": fingerprint, "fix": fix, **extra}
|
|
839
|
+
return {"id": identifier, "kind": kind, "level": level_of(kind), "category": category_of(kind), "scope": "project",
|
|
840
|
+
"title": title, "reason": reason, "fingerprint": fingerprint, "fix": fix, **extra}
|
|
841
|
+
|
|
842
|
+
|
|
843
|
+
def category_label(category: str, count: int) -> str:
|
|
844
|
+
"""The one-line summary of ``count`` findings of one category (用于归并显示)."""
|
|
845
|
+
labels = {
|
|
846
|
+
"skeleton": _("{0} 个缺失文件"),
|
|
847
|
+
"content": _("{0} 个文件与当前模板不同"),
|
|
848
|
+
"region": _("{0} 个受管区块有差异"),
|
|
849
|
+
"profile": _("{0} 个 Profile 字段缺失或不符"),
|
|
850
|
+
"case-naming": _("{0} 项 Case 目录命名差异"),
|
|
851
|
+
"lock": _("{0} 项内容锁问题"),
|
|
852
|
+
}
|
|
853
|
+
return labels.get(category, _("{0} 项其他差异")).format(count)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def summarize(findings: list[dict]) -> list[dict]:
|
|
857
|
+
"""Group findings by (level, category): one row each with the count and the ids (明细仍在 findings 里)."""
|
|
858
|
+
rows: dict[tuple[str, str], dict] = {}
|
|
859
|
+
for finding in findings:
|
|
860
|
+
level = finding.get("level") or level_of(finding.get("kind", ""))
|
|
861
|
+
category = finding.get("category") or category_of(finding.get("kind", ""))
|
|
862
|
+
row = rows.setdefault((level, category), {"level": level, "category": category, "count": 0, "ids": [],
|
|
863
|
+
"fixes": []})
|
|
864
|
+
row["count"] += 1
|
|
865
|
+
row["ids"].append(finding["id"])
|
|
866
|
+
if finding.get("fix") and finding["fix"] not in row["fixes"]:
|
|
867
|
+
row["fixes"].append(finding["fix"])
|
|
868
|
+
ordered = sorted(rows.values(), key=lambda r: (LEVEL_ORDER.index(r["level"]) if r["level"] in LEVEL_ORDER else 9,
|
|
869
|
+
r["category"]))
|
|
870
|
+
return [{**row, "label": category_label(row["category"], row["count"])} for row in ordered]
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def level_counts(findings: list[dict]) -> dict[str, int]:
|
|
874
|
+
counts = {level: 0 for level in LEVEL_ORDER}
|
|
875
|
+
for finding in findings:
|
|
876
|
+
level = finding.get("level") or level_of(finding.get("kind", ""))
|
|
877
|
+
counts[level if level in counts else "suggest"] += 1
|
|
878
|
+
return counts
|
|
561
879
|
|
|
562
880
|
|
|
563
881
|
def check(root: Path, *, state_dir: Path | None = None, reprompt: bool = False) -> dict:
|
|
@@ -576,33 +894,49 @@ def check(root: Path, *, state_dir: Path | None = None, reprompt: bool = False)
|
|
|
576
894
|
skeleton.append({"path": entry["path"], "compare": entry["compare"], "required": entry["required"],
|
|
577
895
|
"state": state, "fingerprint": entry["fingerprint"]})
|
|
578
896
|
if state == "missing" and entry["required"]:
|
|
579
|
-
findings.append(_finding(f"skel:{entry['path']}", "skeleton-missing",
|
|
580
|
-
"期望骨架清单里有,项目里没有", entry["fingerprint"], "add-skeleton",
|
|
897
|
+
findings.append(_finding(f"skel:{entry['path']}", "skeleton-missing", _("缺少脚手架文件 {0}").format(entry['path']),
|
|
898
|
+
_("期望骨架清单里有,项目里没有"), entry["fingerprint"], "add-skeleton",
|
|
581
899
|
path=entry["path"]))
|
|
582
900
|
elif state == "differs":
|
|
583
|
-
findings.append(_finding(f"content:{entry['path']}", "content-differs",
|
|
584
|
-
"内容锁里没有它的基线,无法判断是你改过还是模板变了",
|
|
901
|
+
findings.append(_finding(f"content:{entry['path']}", "content-differs", _("{0} 与当前模板不同").format(entry['path']),
|
|
902
|
+
_("内容锁里没有它的基线,无法判断是你改过还是模板变了"),
|
|
585
903
|
entry["fingerprint"], "update-content", path=entry["path"]))
|
|
586
904
|
|
|
905
|
+
region_state = region_rows(root, pack_entry, ctx.inputs.language)
|
|
906
|
+
for row in region_state:
|
|
907
|
+
identifier = f"region:{row['path']}#{row['id']}"
|
|
908
|
+
if row["state"] == "missing":
|
|
909
|
+
findings.append(_finding(identifier, "region-missing", _("{0} 里的受管区块 {1} 不见了").format(row['path'], row['id']),
|
|
910
|
+
_("区块被移除;若是有意移除,可永久跳过"), row["fingerprint"], None, path=row["path"]))
|
|
911
|
+
elif row["state"] == "modified":
|
|
912
|
+
findings.append(_finding(identifier, "region-modified", _("{0} 里的受管区块 {1} 被改过").format(row['path'], row['id']),
|
|
913
|
+
_("区块内部有你的改动,升级不会覆盖;--mode region 里选择保留或采用模板"),
|
|
914
|
+
row["fingerprint"], "update-region", path=row["path"]))
|
|
915
|
+
elif row["state"] == "outdated":
|
|
916
|
+
findings.append(_finding(identifier, "region-outdated", _("{0} 里的受管区块 {1} 有新版本").format(row['path'], row['id']),
|
|
917
|
+
_("区块完好,可以更新(先备份)"), row["fingerprint"], "update-region", path=row["path"]))
|
|
918
|
+
|
|
919
|
+
findings.extend(_check_privacy(ctx, root))
|
|
920
|
+
|
|
587
921
|
profile_rows = _check_profile(ctx)
|
|
588
922
|
for row in profile_rows:
|
|
589
923
|
if row["state"] == "ok":
|
|
590
924
|
continue
|
|
591
925
|
fixable = row["mode"] in ("default", "equal")
|
|
592
|
-
what = "缺少" if row["state"] == "missing" else "不符合期望"
|
|
926
|
+
what = _("缺少") if row["state"] == "missing" else _("不符合期望")
|
|
593
927
|
findings.append(_finding(f"profile:{row['field']}", f"profile-{row['state']}",
|
|
594
|
-
|
|
595
|
-
|
|
928
|
+
_("Profile {0}:{1}").format(what, row['field']),
|
|
929
|
+
_("期望 {0}").format(json.dumps(row['expected'], ensure_ascii=False)) if fixable else _("需要你自己填写"),
|
|
596
930
|
row["fingerprint"], "profile" if fixable else None, field=row["field"]))
|
|
597
931
|
|
|
598
932
|
lock_state = {"pack": ctx.pack["id"] if ctx.pack else None, "version": (pack_entry or {}).get("version"),
|
|
599
933
|
"latest": ctx.pack["version"] if ctx.pack else None, "error": lock_error, "status": "ok"}
|
|
600
934
|
if pack_entry is not None and pack_entry.get("version") == module.UNKNOWN_PACK_VERSION:
|
|
601
|
-
repairable,
|
|
935
|
+
repairable, _plan = _lock_repair_plan(ctx, lock)
|
|
602
936
|
lock_state["status"] = "unknown-version"
|
|
603
937
|
findings.append(_finding(
|
|
604
|
-
f"lock:{ctx.pack['id']}", "lock-version", "内容锁的模板版本未知(0.0.0)",
|
|
605
|
-
"旧版本写入的占位版本" + (";基线与当前模板一致,可自动修复" if repairable else ";基线与当前模板不同,需要逐文件选择"),
|
|
938
|
+
f"lock:{ctx.pack['id']}", "lock-version", _("内容锁的模板版本未知(0.0.0)"),
|
|
939
|
+
_("旧版本写入的占位版本") + (_(";基线与当前模板一致,可自动修复") if repairable else _(";基线与当前模板不同,需要逐文件选择")),
|
|
606
940
|
sha(f"{ctx.pack['id']}@{module.UNKNOWN_PACK_VERSION}"), "repair-lock" if repairable else "update-content"))
|
|
607
941
|
if lock_error:
|
|
608
942
|
lock_state["status"] = "error"
|
|
@@ -610,40 +944,75 @@ def check(root: Path, *, state_dir: Path | None = None, reprompt: bool = False)
|
|
|
610
944
|
naming = check_case_naming(ctx)
|
|
611
945
|
if naming["error"]:
|
|
612
946
|
findings.append(_finding("profile:work.case.directory_naming", "profile-invalid",
|
|
613
|
-
"Profile 的 work.case.directory_naming 无法使用", naming[
|
|
947
|
+
_("Profile 的 work.case.directory_naming 无法使用"), _("{0}。{1}").format(naming['error'], _naming_hint()),
|
|
614
948
|
sha(json.dumps({"field": "work.case.directory_naming", "error": naming["error"]})), None,
|
|
615
949
|
field="work.case.directory_naming"))
|
|
616
950
|
elif naming["mismatched_count"]:
|
|
617
|
-
shown = "、".join(naming["mismatched"][:3]) + ("……" if naming["mismatched_count"] > 3 else "")
|
|
618
|
-
source = "Profile 声明的" if naming["declared"] else "默认的 CASE-日期-序号-主题"
|
|
951
|
+
shown = _("、").join(naming["mismatched"][:3]) + ("……" if naming["mismatched_count"] > 3 else "")
|
|
952
|
+
source = _("Profile 声明的") if naming["declared"] else _("默认的 CASE-日期-序号-主题")
|
|
619
953
|
findings.append(_finding("case-naming", "case-naming",
|
|
620
|
-
|
|
621
|
-
|
|
954
|
+
_("{0} 个 Case 目录的命名与{1}规则不符").format(naming['mismatched_count'], source),
|
|
955
|
+
_("例如 {0};规则 {1}").format(shown, naming['pattern']),
|
|
622
956
|
sha(json.dumps({"style": naming["style"], "pattern": naming["pattern"]})), "case-naming"))
|
|
623
957
|
extras = [{"path": p, "kind": "legacy"} for p in ctx.manifest.get("legacy_paths", []) if _lstat(root / p)]
|
|
624
|
-
extras +=
|
|
958
|
+
extras += _profile_extras(ctx)
|
|
959
|
+
conflicts = _profile_conflicts(ctx)
|
|
625
960
|
|
|
626
961
|
decisions = load_decisions(root, state_dir)
|
|
627
962
|
active, skipped = partition(findings, decisions, reprompt=reprompt)
|
|
628
|
-
|
|
629
|
-
|
|
963
|
+
declared = ctx.profile.get("language") if ctx.profile.get("language") in ("zh", "en") else None
|
|
964
|
+
return {"ok": not active, "required_ok": not any(f["level"] == "must" for f in active), "mode": "check", "packs": versions, "skeleton": skeleton, "profile": profile_rows,
|
|
965
|
+
"project_language": {"declared": declared, "effective": declared or "zh"},
|
|
966
|
+
"regions": region_state, "lock": lock_state, "case_naming": naming, "extras": extras,
|
|
967
|
+
"profile_extras": _extras_summary(extras), "profile_conflicts": conflicts, "findings": active, "skipped": skipped,
|
|
968
|
+
"levels": level_counts(active), "categories": summarize(active),
|
|
630
969
|
"decisions": {"path": DECISIONS_PATH.as_posix(), "errors": decisions["errors"],
|
|
631
970
|
"conflict_copies": decisions["conflict_copies"], "local_path": decisions["local_path"]}}
|
|
632
971
|
|
|
633
972
|
|
|
973
|
+
# ---------------------------------------------------------------- project file language
|
|
974
|
+
|
|
975
|
+
def set_project_language(root: Path, language: str, *, apply: bool = False, recovery_dir: Path | None = None) -> dict:
|
|
976
|
+
"""Write the Profile's top-level ``language`` (the language of files the tool writes into the project).
|
|
977
|
+
|
|
978
|
+
Nothing else in the Profile changes and no existing project file is rewritten; the Profile itself is copied to the
|
|
979
|
+
recovery folder first. It is separate from the interface language, which only affects what commands print.
|
|
980
|
+
"""
|
|
981
|
+
module = _init()
|
|
982
|
+
if language not in ("zh", "en"):
|
|
983
|
+
raise _fail(_("项目文件语言只能是 zh 或 en(用 --language 指定)"))
|
|
984
|
+
profile = module._read_project_json(root, module.PROFILE_PATH, "Project Profile")
|
|
985
|
+
if "language" in profile:
|
|
986
|
+
updated = {**profile, "language": language} # keeps its place
|
|
987
|
+
else:
|
|
988
|
+
updated = {}
|
|
989
|
+
for key, value in profile.items(): # a new key goes right after "name", where init puts it
|
|
990
|
+
updated[key] = value
|
|
991
|
+
if key == "name":
|
|
992
|
+
updated["language"] = language
|
|
993
|
+
updated["language"] = language
|
|
994
|
+
changed = updated != profile
|
|
995
|
+
result = {"ok": True, "mode": "language", "applied": False, "language": language,
|
|
996
|
+
"from": profile.get("language") if profile.get("language") in ("zh", "en") else None, "changed": changed,
|
|
997
|
+
"diff": module._unified_diff(module.PROFILE_PATH.as_posix(), module.json_text(profile),
|
|
998
|
+
module.json_text(updated)) if changed else ""}
|
|
999
|
+
if not apply or not changed:
|
|
1000
|
+
return result
|
|
1001
|
+
if module._read_project_json(root, module.PROFILE_PATH, "Project Profile") != profile:
|
|
1002
|
+
raise _fail(_("Profile 刚被改过,请重新预览"), "conflict")
|
|
1003
|
+
recovery, defaulted = module.prepare_recovery_dir(root, recovery_dir, "language")
|
|
1004
|
+
result.update(recovery=_backup(root, recovery, module.PROFILE_PATH), recovery_default=defaulted,
|
|
1005
|
+
recovery_files=[module.PROFILE_PATH.as_posix()])
|
|
1006
|
+
module._atomic_write(root / module.PROFILE_PATH, module.json_text(updated))
|
|
1007
|
+
result["applied"] = True
|
|
1008
|
+
return result
|
|
1009
|
+
|
|
1010
|
+
|
|
634
1011
|
# ---------------------------------------------------------------- shared write helpers
|
|
635
1012
|
|
|
636
|
-
def _backup(root: Path,
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
recovery = recovery_dir.expanduser().resolve()
|
|
640
|
-
if recovery == root or root in recovery.parents:
|
|
641
|
-
raise _fail("--recovery-dir must be outside the project root")
|
|
642
|
-
archived = recovery / relative
|
|
643
|
-
if archived.exists():
|
|
644
|
-
raise _fail(f"recovery collision: {relative}")
|
|
645
|
-
archived.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
646
|
-
archived.write_bytes((root / relative).read_bytes())
|
|
1013
|
+
def _backup(root: Path, recovery: Path, relative: Path) -> str:
|
|
1014
|
+
"""Copy one file into the (already prepared) recovery folder."""
|
|
1015
|
+
_init().backup_into(root, recovery, relative)
|
|
647
1016
|
return str(recovery)
|
|
648
1017
|
|
|
649
1018
|
|
|
@@ -678,7 +1047,7 @@ def add_skeleton(root: Path, targets: list[str] | None, *, apply: bool = False,
|
|
|
678
1047
|
if targets:
|
|
679
1048
|
unknown = [t for t in targets if t not in known]
|
|
680
1049
|
if unknown:
|
|
681
|
-
raise _fail("不在期望骨架清单里:" + "、".join(unknown))
|
|
1050
|
+
raise _fail(_("不在期望骨架清单里:") + _("、").join(unknown))
|
|
682
1051
|
wanted = list(dict.fromkeys(targets))
|
|
683
1052
|
else:
|
|
684
1053
|
wanted = [path for path, item in known.items() if item["state"] == "missing" and item["required"]]
|
|
@@ -687,7 +1056,7 @@ def add_skeleton(root: Path, targets: list[str] | None, *, apply: bool = False,
|
|
|
687
1056
|
files = {Path(p): ctx.rendered.get(Path(p), "") for p in missing}
|
|
688
1057
|
create: list[Path] = []
|
|
689
1058
|
if files:
|
|
690
|
-
create, collisions,
|
|
1059
|
+
create, collisions, _extra = module.plan_writes(root, files)
|
|
691
1060
|
unchanged += [str(p) for p in collisions]
|
|
692
1061
|
result = {"ok": True, "mode": "add-skeleton", "applied": False,
|
|
693
1062
|
"create": [{"path": str(p), "bytes": len(files[p].encode("utf-8"))} for p in create],
|
|
@@ -715,7 +1084,7 @@ def fix_profile(root: Path, fields: list[str] | None, *, apply: bool = False, re
|
|
|
715
1084
|
if fields:
|
|
716
1085
|
unknown = [f for f in fields if f not in rows]
|
|
717
1086
|
if unknown:
|
|
718
|
-
raise _fail("这些字段不需要或不能自动修复:" + "、".join(unknown))
|
|
1087
|
+
raise _fail(_("这些字段不需要或不能自动修复:") + _("、").join(unknown))
|
|
719
1088
|
selected = list(dict.fromkeys(fields))
|
|
720
1089
|
else:
|
|
721
1090
|
selected = list(rows)
|
|
@@ -730,8 +1099,10 @@ def fix_profile(root: Path, fields: list[str] | None, *, apply: bool = False, re
|
|
|
730
1099
|
if not apply or not changed:
|
|
731
1100
|
return result
|
|
732
1101
|
if module._read_project_json(root, module.PROFILE_PATH, "Project Profile") != profile:
|
|
733
|
-
raise _fail("Profile 刚被改过,请重新预览", "conflict")
|
|
734
|
-
|
|
1102
|
+
raise _fail(_("Profile 刚被改过,请重新预览"), "conflict")
|
|
1103
|
+
recovery, defaulted = module.prepare_recovery_dir(root, recovery_dir, "profile")
|
|
1104
|
+
result.update(recovery=_backup(root, recovery, module.PROFILE_PATH), recovery_default=defaulted,
|
|
1105
|
+
recovery_files=[module.PROFILE_PATH.as_posix()])
|
|
735
1106
|
module._atomic_write(root / module.PROFILE_PATH, module.json_text(updated))
|
|
736
1107
|
result["applied"] = True
|
|
737
1108
|
return result
|
|
@@ -767,18 +1138,18 @@ def repair_lock(root: Path, *, apply: bool = False) -> dict:
|
|
|
767
1138
|
lock, error = read_lock(root)
|
|
768
1139
|
result = {"ok": True, "mode": "repair-lock", "applied": False, "changes": [], "blocked": "", "diff": ""}
|
|
769
1140
|
if ctx.pack is None or lock is None:
|
|
770
|
-
result["blocked"] = error or "项目没有内容锁"
|
|
1141
|
+
result["blocked"] = error or _("项目没有内容锁")
|
|
771
1142
|
return result
|
|
772
1143
|
entry = (lock.get("packs") or {}).get(ctx.pack["id"])
|
|
773
1144
|
if entry is None:
|
|
774
|
-
result["blocked"] = "内容锁里没有项目契约模板包"
|
|
1145
|
+
result["blocked"] = _("内容锁里没有项目契约模板包")
|
|
775
1146
|
return result
|
|
776
1147
|
comparable, new_entry = _lock_repair_plan(ctx, lock)
|
|
777
1148
|
if entry.get("version") == module.UNKNOWN_PACK_VERSION and not comparable:
|
|
778
|
-
result["blocked"] = "记录的基线与当前模板不同,无法确定真实版本:用 update-content 逐文件选择保留或采用"
|
|
1149
|
+
result["blocked"] = _("记录的基线与当前模板不同,无法确定真实版本:用 update-content 逐文件选择保留或采用")
|
|
779
1150
|
return result
|
|
780
1151
|
if new_entry["version"] != entry.get("version"):
|
|
781
|
-
result["changes"].append(
|
|
1152
|
+
result["changes"].append(_("模板版本 {0} → {1}").format(entry.get('version'), new_entry['version']))
|
|
782
1153
|
if new_entry.get("version") == ctx.pack["version"]:
|
|
783
1154
|
files = dict(new_entry.get("files") or {})
|
|
784
1155
|
for path in sorted(ctx.tracked):
|
|
@@ -786,7 +1157,7 @@ def repair_lock(root: Path, *, apply: bool = False) -> dict:
|
|
|
786
1157
|
current = _file_digest(root / path)
|
|
787
1158
|
if path not in files and text is not None and current == sha(text):
|
|
788
1159
|
files[path] = current
|
|
789
|
-
result["changes"].append(
|
|
1160
|
+
result["changes"].append(_("记录基线:{0}").format(path))
|
|
790
1161
|
new_entry["files"] = dict(sorted(files.items()))
|
|
791
1162
|
if not result["changes"]:
|
|
792
1163
|
return result
|
|
@@ -796,14 +1167,84 @@ def repair_lock(root: Path, *, apply: bool = False) -> dict:
|
|
|
796
1167
|
module.json_text(new_lock))
|
|
797
1168
|
if not apply:
|
|
798
1169
|
return result
|
|
799
|
-
fresh,
|
|
1170
|
+
fresh, _lock = read_lock(root)
|
|
800
1171
|
if fresh != lock:
|
|
801
|
-
raise _fail("内容锁刚被改过,请重新预览", "conflict")
|
|
1172
|
+
raise _fail(_("内容锁刚被改过,请重新预览"), "conflict")
|
|
802
1173
|
module._atomic_write(root / module.CONTENT_LOCK_PATH, module.json_text(new_lock))
|
|
803
1174
|
result["applied"] = True
|
|
804
1175
|
return result
|
|
805
1176
|
|
|
806
1177
|
|
|
1178
|
+
# ---------------------------------------------------------------- managed regions
|
|
1179
|
+
|
|
1180
|
+
def update_regions(root: Path, *, accept: list[str], keep: list[str], apply: bool = False,
|
|
1181
|
+
recovery_dir: Path | None = None, state_dir: Path | None = None) -> tuple[int, dict]:
|
|
1182
|
+
"""Bring managed regions to the current template body.
|
|
1183
|
+
|
|
1184
|
+
A region nobody touched is replaced (after a backup); one the user edited is only replaced with ``--accept
|
|
1185
|
+
<file>#<id>`` and kept with ``--keep <file>#<id>`` (recorded as a decision). Text outside regions is never read
|
|
1186
|
+
for writing.
|
|
1187
|
+
"""
|
|
1188
|
+
module, regions = _init(), _regions()
|
|
1189
|
+
lock, _lock_error = read_lock(root)
|
|
1190
|
+
ctx = Context(root)
|
|
1191
|
+
entry = ((lock or {}).get("packs") or {}).get(ctx.pack["id"]) if ctx.pack else None
|
|
1192
|
+
rows = [row for row in region_rows(root, entry, ctx.inputs.language) if row["state"] != "ok"]
|
|
1193
|
+
known = {f"{row['path']}#{row['id']}" for row in rows}
|
|
1194
|
+
unknown = (set(accept) | set(keep)) - known
|
|
1195
|
+
if unknown:
|
|
1196
|
+
raise _fail(_("不是需要处理的受管区块:") + ", ".join(sorted(unknown)))
|
|
1197
|
+
if set(accept) & set(keep):
|
|
1198
|
+
raise _fail(_("同一区块不能同时 --accept 与 --keep:") + ", ".join(sorted(set(accept) & set(keep))))
|
|
1199
|
+
templates = module.load_templates()
|
|
1200
|
+
plan = []
|
|
1201
|
+
for row in rows:
|
|
1202
|
+
key = f"{row['path']}#{row['id']}"
|
|
1203
|
+
if row["state"] == "outdated":
|
|
1204
|
+
action = "keep" if key in keep else "replace"
|
|
1205
|
+
elif row["state"] == "modified":
|
|
1206
|
+
action = "replace" if key in accept else "keep" if key in keep else "blocked"
|
|
1207
|
+
else:
|
|
1208
|
+
action = "skip"
|
|
1209
|
+
plan.append({"path": row["path"], "id": row["id"], "state": row["state"], "action": action,
|
|
1210
|
+
"fingerprint": row["fingerprint"]})
|
|
1211
|
+
blocked = [f"{i['path']}#{i['id']}" for i in plan if i["action"] == "blocked"]
|
|
1212
|
+
replacing = [i for i in plan if i["action"] == "replace"]
|
|
1213
|
+
result = {"ok": not blocked, "mode": "region", "applied": False, "regions": plan, "blocked": "",
|
|
1214
|
+
"changes": [f"{i['action']:8} {i['path']}#{i['id']} [{i['state']}]" for i in plan]}
|
|
1215
|
+
if blocked:
|
|
1216
|
+
result["blocked"] = _("区块内部有你的改动,需逐个选择:--accept <文件>#<ID> 用模板替换(先备份),或 --keep <文件>#<ID> 保留")
|
|
1217
|
+
if not apply or blocked:
|
|
1218
|
+
return (0 if not blocked else 1), result
|
|
1219
|
+
backed_up: list[str] = []
|
|
1220
|
+
if replacing:
|
|
1221
|
+
recovery, defaulted = module.prepare_recovery_dir(root, recovery_dir, "region")
|
|
1222
|
+
for item in replacing:
|
|
1223
|
+
if item["path"] not in backed_up:
|
|
1224
|
+
_backup(root, recovery, Path(item["path"]))
|
|
1225
|
+
backed_up.append(item["path"])
|
|
1226
|
+
result.update(recovery=str(recovery), recovery_default=defaulted, recovery_files=backed_up)
|
|
1227
|
+
new_digests: dict[str, dict[str, str]] = {}
|
|
1228
|
+
for item in replacing:
|
|
1229
|
+
path = root / item["path"]
|
|
1230
|
+
mode = os.stat(path).st_mode & 0o7777
|
|
1231
|
+
body = module.localized(templates, f"region/{item['id']}", ctx.inputs.language)
|
|
1232
|
+
text, _state = regions.upsert(path.read_text(encoding="utf-8"), item["id"], body, force=True)
|
|
1233
|
+
module._atomic_write(path, text, mode)
|
|
1234
|
+
new_digests.setdefault(item["path"], {})[item["id"]] = regions.digest(body)
|
|
1235
|
+
if new_digests:
|
|
1236
|
+
fresh = copy.deepcopy(lock)
|
|
1237
|
+
for path_, ids in new_digests.items():
|
|
1238
|
+
fresh["packs"][ctx.pack["id"]]["regions"][path_].update(ids)
|
|
1239
|
+
module._atomic_write(root / module.CONTENT_LOCK_PATH, module.json_text(fresh))
|
|
1240
|
+
for item in plan:
|
|
1241
|
+
if item["action"] == "keep":
|
|
1242
|
+
decide(root, f"region:{item['path']}#{item['id']}", "keep", reason="region --keep",
|
|
1243
|
+
fingerprint=item["fingerprint"], scope="project", apply=True, state_dir=state_dir)
|
|
1244
|
+
result["applied"] = True
|
|
1245
|
+
return 0, result
|
|
1246
|
+
|
|
1247
|
+
|
|
807
1248
|
# ---------------------------------------------------------------- recording decisions
|
|
808
1249
|
|
|
809
1250
|
def _decision_file(root: Path, state_dir: Path | None, scope: str) -> Path:
|
|
@@ -817,7 +1258,7 @@ def _store(path: Path, table: dict, expect_sha: str | None, root: Path, scope: s
|
|
|
817
1258
|
if parent == root:
|
|
818
1259
|
break
|
|
819
1260
|
if parent.is_symlink():
|
|
820
|
-
raise _fail(
|
|
1261
|
+
raise _fail(_("拒绝符号链接:{0}").format(parent.relative_to(root)))
|
|
821
1262
|
current_sha = None
|
|
822
1263
|
try:
|
|
823
1264
|
current_sha = sha(path.read_text(encoding="utf-8"))
|
|
@@ -826,23 +1267,28 @@ def _store(path: Path, table: dict, expect_sha: str | None, root: Path, scope: s
|
|
|
826
1267
|
except (OSError, UnicodeDecodeError):
|
|
827
1268
|
pass
|
|
828
1269
|
if current_sha != expect_sha:
|
|
829
|
-
raise _fail("决定文件刚被别处改过(可能是另一台机器同步过来),请重新预览", "conflict")
|
|
1270
|
+
raise _fail(_("决定文件刚被别处改过(可能是另一台机器同步过来),请重新预览"), "conflict")
|
|
830
1271
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700 if scope == "machine" else 0o755)
|
|
831
1272
|
text = module.json_text({"schema_version": 1, "decisions": dict(sorted(table.items()))})
|
|
832
1273
|
module._atomic_write(path, text)
|
|
833
1274
|
|
|
834
1275
|
|
|
1276
|
+
def _same_decision(old: object, new: dict) -> bool:
|
|
1277
|
+
"""Whether a recorded decision already says what ``new`` says (``decided_at`` is not part of the content)."""
|
|
1278
|
+
return isinstance(old, dict) and all(old.get(key) == new.get(key) for key in ("decision", "fingerprint", "reason"))
|
|
1279
|
+
|
|
1280
|
+
|
|
835
1281
|
def decide(root: Path, finding_id: str, decision: str, *, reason: str = "", fingerprint: str | None = None,
|
|
836
1282
|
scope: str | None = None, apply: bool = False, state_dir: Path | None = None) -> dict:
|
|
837
1283
|
"""Record skip / keep / later for a finding. ``fingerprint`` defaults to the finding's current expectation."""
|
|
838
1284
|
if decision not in DECISION_VALUES:
|
|
839
|
-
raise _fail("决定只能是 skip / keep / later")
|
|
1285
|
+
raise _fail(_("决定只能是 skip / keep / later"))
|
|
840
1286
|
scope = scope or ("machine" if finding_id.startswith(LOCAL_PREFIX) else "project")
|
|
841
1287
|
if fingerprint is None:
|
|
842
1288
|
report = check(root, state_dir=state_dir, reprompt=True)
|
|
843
1289
|
match = next((f for f in [*report["findings"], *report["skipped"]] if f["id"] == finding_id), None)
|
|
844
1290
|
if match is None:
|
|
845
|
-
raise _fail(
|
|
1291
|
+
raise _fail(_("现在没有这个发现:{0}(用 check 查看当前的发现 ID)").format(finding_id), "not-found")
|
|
846
1292
|
fingerprint = match["fingerprint"]
|
|
847
1293
|
path = _decision_file(root, state_dir, scope)
|
|
848
1294
|
table, current_sha, error = read_decisions(path)
|
|
@@ -851,11 +1297,48 @@ def decide(root: Path, finding_id: str, decision: str, *, reason: str = "", fing
|
|
|
851
1297
|
entry = {"decision": decision, "fingerprint": fingerprint, "decided_at": now_iso()}
|
|
852
1298
|
if reason:
|
|
853
1299
|
entry["reason"] = reason
|
|
1300
|
+
unchanged = _same_decision(table.get(finding_id), entry)
|
|
1301
|
+
if unchanged:
|
|
1302
|
+
entry = table[finding_id] # 内容没变:保留原 decided_at,不重写文件(同步盘里不产生无意义的冲突副本)
|
|
854
1303
|
table = {**table, finding_id: entry}
|
|
855
1304
|
result = {"ok": True, "mode": "decide", "applied": False, "id": finding_id, "scope": scope, "entry": entry,
|
|
856
1305
|
"file": DECISIONS_PATH.as_posix() if scope == "project" else str(path)}
|
|
857
1306
|
if apply:
|
|
858
|
-
|
|
1307
|
+
if not unchanged:
|
|
1308
|
+
_store(path, table, current_sha, root, scope)
|
|
1309
|
+
result["applied"] = True
|
|
1310
|
+
return result
|
|
1311
|
+
|
|
1312
|
+
|
|
1313
|
+
ACCEPT_REASON = "accept-current"
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
def accept_current(root: Path, *, reason: str = "", apply: bool = False, state_dir: Path | None = None) -> dict:
|
|
1317
|
+
"""Record every current scaffold difference as decided / keep-as-is, in the project decisions file.
|
|
1318
|
+
|
|
1319
|
+
Same table and entry format as ``decide``: ``{decision: keep, fingerprint, decided_at, reason}``, so a later
|
|
1320
|
+
change of the expected content (new fingerprint) prompts again. Findings that must be handled (level ``must``)
|
|
1321
|
+
are left alone and listed in ``excluded``; findings that are already decided with the same expectation are untouched.
|
|
1322
|
+
"""
|
|
1323
|
+
report = check(root, state_dir=state_dir)
|
|
1324
|
+
path = root / DECISIONS_PATH
|
|
1325
|
+
table, current_sha, error = read_decisions(path)
|
|
1326
|
+
if error:
|
|
1327
|
+
raise _fail(error, "profile-invalid")
|
|
1328
|
+
accepted = [f for f in report["findings"] if f["level"] != "must"]
|
|
1329
|
+
excluded = [{"id": f["id"], "title": f["title"]} for f in report["findings"] if f["level"] == "must"]
|
|
1330
|
+
stamp = now_iso()
|
|
1331
|
+
entries = {}
|
|
1332
|
+
for finding in accepted:
|
|
1333
|
+
entry = {"decision": "keep", "fingerprint": finding["fingerprint"], "decided_at": stamp,
|
|
1334
|
+
"reason": reason or ACCEPT_REASON}
|
|
1335
|
+
entries[finding["id"]] = table[finding["id"]] if _same_decision(table.get(finding["id"]), entry) else entry
|
|
1336
|
+
result = {"ok": True, "mode": "accept-current", "applied": False, "count": len(entries),
|
|
1337
|
+
"entries": entries, "categories": summarize(accepted), "excluded": excluded,
|
|
1338
|
+
"already_decided": len(report["skipped"]), "file": DECISIONS_PATH.as_posix(), "reason": reason or ACCEPT_REASON}
|
|
1339
|
+
if apply and entries:
|
|
1340
|
+
if any(table.get(key) != entry for key, entry in entries.items()):
|
|
1341
|
+
_store(path, {**table, **entries}, current_sha, root, "project")
|
|
859
1342
|
result["applied"] = True
|
|
860
1343
|
return result
|
|
861
1344
|
|
|
@@ -876,21 +1359,26 @@ def undecide(root: Path, finding_id: str, *, apply: bool = False, state_dir: Pat
|
|
|
876
1359
|
_store(path, remaining, current_sha, root, scope)
|
|
877
1360
|
result["applied"] = True
|
|
878
1361
|
return result
|
|
879
|
-
raise _fail(
|
|
1362
|
+
raise _fail(_("没有关于 {0} 的决定").format(finding_id), "not-found")
|
|
880
1363
|
|
|
881
1364
|
|
|
882
1365
|
# ---------------------------------------------------------------- command line (called by init_project)
|
|
883
1366
|
|
|
884
1367
|
def run_mode(args: Any, root: Path) -> tuple[int, dict]:
|
|
885
|
-
"""Handle ``--mode check | add-skeleton | profile | repair-lock | decide | case-naming`` of init_project.py."""
|
|
1368
|
+
"""Handle ``--mode check | add-skeleton | profile | repair-lock | decide | case-naming | language`` of init_project.py."""
|
|
886
1369
|
state_dir = args.state_dir
|
|
887
1370
|
targets = list(args.target) or None
|
|
888
1371
|
if args.mode == "check":
|
|
889
1372
|
report = check(root, state_dir=state_dir, reprompt=args.reprompt)
|
|
890
1373
|
report["fingerprint"] = fingerprint(report)
|
|
891
|
-
|
|
1374
|
+
passed = report["required_ok"] if getattr(args, "required_only", False) else report["ok"]
|
|
1375
|
+
return (0 if passed else 1), report
|
|
892
1376
|
if args.mode == "case-naming":
|
|
893
1377
|
return 0, case_naming_plan(root)
|
|
1378
|
+
if args.mode == "accept-current":
|
|
1379
|
+
return 0, accept_current(root, reason=args.reason or "", apply=args.apply, state_dir=state_dir)
|
|
1380
|
+
if args.mode == "language":
|
|
1381
|
+
return 0, set_project_language(root, args.language, apply=args.apply, recovery_dir=args.recovery_dir)
|
|
894
1382
|
if args.mode == "add-skeleton":
|
|
895
1383
|
return 0, add_skeleton(root, targets, apply=args.apply, state_dir=state_dir)
|
|
896
1384
|
if args.mode == "profile":
|
|
@@ -899,7 +1387,7 @@ def run_mode(args: Any, root: Path) -> tuple[int, dict]:
|
|
|
899
1387
|
result = repair_lock(root, apply=args.apply)
|
|
900
1388
|
return (1 if result["blocked"] else 0), result
|
|
901
1389
|
if not args.target or len(args.target) != 1:
|
|
902
|
-
raise _fail("--mode decide 需要且只需要一个 --target <发现 ID>")
|
|
1390
|
+
raise _fail(_("--mode decide 需要且只需要一个 --target <发现 ID>"))
|
|
903
1391
|
if args.decision == "unskip":
|
|
904
1392
|
return 0, undecide(root, args.target[0], apply=args.apply, state_dir=state_dir)
|
|
905
1393
|
return 0, decide(root, args.target[0], args.decision or "skip", reason=args.reason or "",
|
|
@@ -911,23 +1399,39 @@ def render_text(result: dict) -> str:
|
|
|
911
1399
|
mode = result.get("mode")
|
|
912
1400
|
if mode == "check":
|
|
913
1401
|
for item in result["findings"]:
|
|
914
|
-
lines.append(
|
|
1402
|
+
lines.append(_(" [{0}] {1}:{2}").format(item['id'], item['title'], item['reason']) + (_("(修复:{0})").format(item['fix']) if item["fix"] else ""))
|
|
915
1403
|
for item in result["skipped"]:
|
|
916
|
-
reason = item["decision"].get("reason") or "(未写理由)"
|
|
917
|
-
lines.append(
|
|
918
|
-
|
|
1404
|
+
reason = item["decision"].get("reason") or _("(未写理由)")
|
|
1405
|
+
lines.append(_(" [已跳过 {0}] {1}").format(item['id'], reason))
|
|
1406
|
+
for item in result.get("profile_conflicts", []):
|
|
1407
|
+
lines.append(_(" [信息] {0}").format(item["message"]))
|
|
1408
|
+
summary = result.get("profile_extras") or {}
|
|
1409
|
+
if summary.get("total"):
|
|
1410
|
+
lines.append(_(" [信息] Profile 中有 {0} 个 schema 未声明的字段(项目自有 {1}、疑似拼写错误 {2}、已被其他插件读取 {3};工具不读取、不比较):路径在 JSON 输出的 extras 里").format(
|
|
1411
|
+
summary["total"], summary["own"], summary["suspected_typo"], summary["read_by_plugin"]))
|
|
1412
|
+
lines.append(_("脚手架与期望一致。") if result["ok"] else _("{0} 项差异。").format(len(result['findings'])))
|
|
1413
|
+
elif mode == "accept-current":
|
|
1414
|
+
lines.append(_("{0}:把当前 {1} 项脚手架差异记为已决定、保留现状").format(_("已执行") if result["applied"] else _("预览"), result["count"]))
|
|
1415
|
+
for row in result["categories"]:
|
|
1416
|
+
lines.append(f" {row['label']}")
|
|
1417
|
+
for item in result["excluded"]:
|
|
1418
|
+
lines.append(_(" 未包含(需要处理):[{0}] {1}").format(item["id"], item["title"]))
|
|
1419
|
+
lines.append(_("写入 {0}(随项目同步,理由:{1})").format(result["file"], result["reason"]))
|
|
919
1420
|
else:
|
|
920
|
-
label = "已执行" if result.get("applied") else "预览"
|
|
921
|
-
lines.append(
|
|
1421
|
+
label = _("已执行") if result.get("applied") else _("预览")
|
|
1422
|
+
lines.append(_("{0}:{1}").format(label, mode))
|
|
922
1423
|
for item in result.get("renames", []):
|
|
923
|
-
lines.append(f" {item['from']} → {item['to'] or '(需要你决定)'}"
|
|
924
|
-
+ (
|
|
1424
|
+
lines.append(f" {item['from']} → {item['to'] or _('(需要你决定)')}"
|
|
1425
|
+
+ (_(";被 {0} 个文件提到").format(len(item['references'])) if item["references"] else ""))
|
|
925
1426
|
for item in result.get("create", []):
|
|
926
|
-
lines.append(f"
|
|
1427
|
+
lines.append(f" {_('新建')} {item['path']}")
|
|
927
1428
|
for change in result.get("changes", []):
|
|
928
1429
|
lines.append(f" {change}")
|
|
929
1430
|
if result.get("diff"):
|
|
930
1431
|
lines.append(result["diff"].rstrip())
|
|
931
1432
|
if result.get("blocked"):
|
|
932
1433
|
lines.append(result["blocked"])
|
|
1434
|
+
if mode == "language" and not result.get("changed"):
|
|
1435
|
+
lines.append(_("项目文件语言已经是 {0},没有需要改的。").format(result["language"]))
|
|
1436
|
+
lines.extend(_init().recovery_lines(result))
|
|
933
1437
|
return "\n".join(lines) + "\n"
|