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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/package.json +1 -1
  2. package/runtime/index.json +6 -6
  3. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  4. package/runtime/plugins/agent-pack/plugin.json +1 -1
  5. package/runtime/plugins/agent-pack/references/capability-config.md +10 -0
  6. package/runtime/plugins/agent-pack/references/check-opinion-migrate.en.md +31 -0
  7. package/runtime/plugins/agent-pack/references/check-opinion-migrate.md +31 -0
  8. package/runtime/plugins/agent-pack/references/dedupe-contract.en.md +27 -0
  9. package/runtime/plugins/agent-pack/references/dedupe-contract.md +27 -0
  10. package/runtime/plugins/agent-pack/references/inventory-contract.en.md +83 -0
  11. package/runtime/plugins/agent-pack/references/inventory-contract.md +83 -0
  12. package/runtime/plugins/agent-pack/references/nudge.en.md +10 -2
  13. package/runtime/plugins/agent-pack/references/nudge.md +10 -2
  14. package/runtime/plugins/agent-pack/references/relocate-contract.en.md +41 -0
  15. package/runtime/plugins/agent-pack/references/relocate-contract.md +41 -0
  16. package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +572 -30
  17. package/runtime/plugins/agent-pack/runtime/agent_pack_clients.py +233 -0
  18. package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +112 -4
  19. package/runtime/plugins/agent-pack/runtime/agent_pack_dedupe.py +502 -0
  20. package/runtime/plugins/agent-pack/runtime/agent_pack_desktop.py +92 -0
  21. package/runtime/plugins/agent-pack/runtime/agent_pack_ext_common.py +251 -0
  22. package/runtime/plugins/agent-pack/runtime/agent_pack_inventory.py +989 -0
  23. package/runtime/plugins/agent-pack/runtime/agent_pack_mcp_write.py +447 -0
  24. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +29 -4
  25. package/runtime/plugins/agent-pack/runtime/agent_pack_relocate.py +385 -0
  26. package/runtime/plugins/agent-pack/runtime/agent_pack_scope.py +233 -0
  27. package/runtime/plugins/agent-pack/runtime/agenthelm.py +183 -14
  28. package/runtime/plugins/agent-pack/runtime/locale/en.json +250 -1
  29. package/runtime/plugins/agent-pack/runtime/mcp_server.py +12 -0
  30. package/runtime/plugins/agent-pack/runtime/nudge_text.py +8 -2
  31. package/runtime/plugins/agent-pack/runtime/user_settings.py +2 -1
  32. package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +15 -0
  33. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  34. package/runtime/plugins/agents-init/content.json +4 -2
  35. package/runtime/plugins/agents-init/plugin.json +1 -1
  36. package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +2 -0
  37. package/runtime/plugins/agents-init/skills/agents-init/launcher.en.sh +93 -0
  38. package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +27 -0
  39. package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +4 -1
  40. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +24 -9
  41. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  42. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  43. package/runtime/plugins/opinion-manager/catalog/README.md +3 -1
  44. package/runtime/plugins/opinion-manager/catalog/rules/om.align-requirements/versions/1.1.0.json +34 -0
  45. package/runtime/plugins/opinion-manager/catalog/rules/om.assumptions-authority/versions/1.1.0.json +34 -0
  46. package/runtime/plugins/opinion-manager/catalog/rules/om.batch-questions/versions/1.1.0.json +34 -0
  47. package/runtime/plugins/opinion-manager/catalog/rules/om.bilingual-terms/versions/1.1.0.json +34 -0
  48. package/runtime/plugins/opinion-manager/catalog/rules/om.calculations/versions/1.1.0.json +34 -0
  49. package/runtime/plugins/opinion-manager/catalog/rules/om.chinese-response/versions/1.1.0.json +34 -0
  50. package/runtime/plugins/opinion-manager/catalog/rules/om.clean-deliverable/versions/1.1.0.json +34 -0
  51. package/runtime/plugins/opinion-manager/catalog/rules/om.complete-options/versions/1.1.0.json +34 -0
  52. package/runtime/plugins/opinion-manager/catalog/rules/om.conclusion-first/versions/1.1.0.json +34 -0
  53. package/runtime/plugins/opinion-manager/catalog/rules/om.concrete-titles/versions/1.1.0.json +34 -0
  54. package/runtime/plugins/opinion-manager/catalog/rules/om.consistent-items/versions/1.1.0.json +34 -0
  55. package/runtime/plugins/opinion-manager/catalog/rules/om.device-readable/versions/1.1.0.json +34 -0
  56. package/runtime/plugins/opinion-manager/catalog/rules/om.editable-diagrams/versions/1.1.0.json +34 -0
  57. package/runtime/plugins/opinion-manager/catalog/rules/om.evidence-inference/versions/1.1.0.json +34 -0
  58. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-chinese/versions/1.1.0.json +34 -0
  59. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-project-language/versions/1.1.0.json +34 -0
  60. package/runtime/plugins/opinion-manager/catalog/rules/om.markdown-structure/versions/1.1.0.json +34 -0
  61. package/runtime/plugins/opinion-manager/catalog/rules/om.portable-files/versions/1.1.0.json +34 -0
  62. package/runtime/plugins/opinion-manager/catalog/rules/om.report-context/versions/1.1.0.json +34 -0
  63. package/runtime/plugins/opinion-manager/catalog/rules/om.report-formats/versions/1.1.0.json +34 -0
  64. package/runtime/plugins/opinion-manager/catalog/rules/om.report-review/versions/1.1.0.json +34 -0
  65. package/runtime/plugins/opinion-manager/catalog/rules/om.response-brief/versions/1.1.0.json +34 -0
  66. package/runtime/plugins/opinion-manager/catalog/rules/om.response-dense/versions/1.1.0.json +34 -0
  67. package/runtime/plugins/opinion-manager/catalog/rules/om.rules-tools/versions/1.1.0.json +34 -0
  68. package/runtime/plugins/opinion-manager/catalog/rules/om.semantic-wrap/versions/1.1.0.json +34 -0
  69. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-proportional/versions/1.1.0.json +34 -0
  70. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-three-level/versions/1.1.0.json +34 -0
  71. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-compact/versions/1.1.0.json +34 -0
  72. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-list-first/versions/1.1.0.json +34 -0
  73. package/runtime/plugins/opinion-manager/catalog/rules/om.test-evidence/versions/1.1.0.json +34 -0
  74. package/runtime/plugins/opinion-manager/catalog/rules/om.versioned-files/versions/1.1.0.json +34 -0
  75. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/compact-tables/versions/1.1.0.json +32 -0
  76. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/list-first/versions/1.1.0.json +32 -0
  77. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/chinese-maintenance/versions/1.1.0.json +26 -0
  78. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/project-language/versions/1.1.0.json +26 -0
  79. package/runtime/plugins/opinion-manager/catalog/templates/response-style/brief-chinese/versions/1.1.0.json +30 -0
  80. package/runtime/plugins/opinion-manager/catalog/templates/response-style/dense-chinese/versions/1.1.0.json +30 -0
  81. package/runtime/plugins/opinion-manager/catalog/templates/scenario/concise-project/versions/1.1.0.json +181 -0
  82. package/runtime/plugins/opinion-manager/catalog/templates/scenario/reviewed-project/versions/1.1.0.json +179 -0
  83. package/runtime/plugins/opinion-manager/catalog/templates/work-method/proportional/versions/1.1.0.json +31 -0
  84. package/runtime/plugins/opinion-manager/catalog/templates/work-method/three-level/versions/1.1.0.json +31 -0
  85. package/runtime/plugins/opinion-manager/content.json +44 -3
  86. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  87. package/runtime/plugins/opinion-manager/references/inbox.en.md +25 -4
  88. package/runtime/plugins/opinion-manager/references/inbox.md +25 -4
  89. package/runtime/plugins/opinion-manager/references/profile.schema.json +19 -2
  90. package/runtime/plugins/opinion-manager/references/rule.schema.json +25 -3
  91. package/runtime/plugins/opinion-manager/references/versioned-template.schema.json +5 -4
  92. package/runtime/plugins/opinion-manager/references/versioning.md +89 -4
  93. package/runtime/plugins/opinion-manager/runtime/context.py +26 -19
  94. package/runtime/plugins/opinion-manager/runtime/inbox.py +400 -25
  95. package/runtime/plugins/opinion-manager/runtime/inbox_relations.py +106 -0
  96. package/runtime/plugins/opinion-manager/runtime/inbox_routes.py +132 -0
  97. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +117 -11
  98. package/runtime/plugins/opinion-manager/runtime/lifecycle.py +35 -5
  99. package/runtime/plugins/opinion-manager/runtime/locale/en.json +137 -2
  100. package/runtime/plugins/opinion-manager/runtime/migrate.py +582 -0
  101. package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +9 -4
  102. package/runtime/plugins/opinion-manager/runtime/rule_lines.py +247 -0
  103. package/runtime/plugins/opinion-manager/runtime/tags.py +217 -0
  104. package/runtime/plugins/opinion-manager/runtime/versioned.py +289 -41
  105. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +8 -7
  106. package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
  107. package/runtime/plugins/project-orchestrator/plugin.json +1 -1
  108. package/runtime/plugins/project-orchestrator/runtime/locale/en.json +305 -3
  109. package/runtime/plugins/project-orchestrator/runtime/private_paths.py +11 -1
  110. package/runtime/plugins/project-orchestrator/runtime/project_cli.py +101 -1
  111. package/runtime/plugins/project-orchestrator/runtime/project_demo.py +13 -1
  112. package/runtime/plugins/project-orchestrator/runtime/project_ext_actions.py +415 -0
  113. package/runtime/plugins/project-orchestrator/runtime/project_extensions.py +971 -0
  114. package/runtime/plugins/project-orchestrator/runtime/project_extensions_demo.py +86 -0
  115. package/runtime/plugins/project-orchestrator/runtime/project_menu.py +345 -2
  116. package/runtime/plugins/project-orchestrator/runtime/project_real.py +17 -1
  117. package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +2 -0
@@ -0,0 +1,106 @@
1
+ """候选与现有规则之间的机械关系提示:只比较文本,不做语义判断,永不阻断。
2
+
3
+ 比较对象:其他候选(不含已丢弃)、OPINION.md 的自定义规则行(按本工具自己的渲染格式解析)、Profile 里已选的公开规则文本。
4
+ 三种提示:规范化文本相同(same_text)、字符二元组重合度(text_overlap)、条件词重合(condition_overlap)。阈值保守,
5
+ 由固定样例测试守住。冲突、合并、放大缩小、拆分这类语义判断由 Agent 做,写入候选的 relation 备注。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import versioned
15
+ from rule_lines import custom_section_lines, is_global, parse_line
16
+
17
+ TEXT_OVERLAP = 0.5 # 正文字符二元组 Jaccard 重合度下限
18
+ CONDITION_OVERLAP = 0.4 # 触发条件字符二元组 Jaccard 重合度下限
19
+ MIN_TEXT_CHARS, MIN_CONDITION_CHARS = 6, 4 # 规范化后太短的文本不比较,避免短词误报
20
+ MAX_RELATIONS = 5
21
+ EVIDENCE_CHARS = 80
22
+ ORDER = {"same_text": 0, "text_overlap": 1, "condition_overlap": 2}
23
+
24
+
25
+ def squash(text: str) -> str:
26
+ """规范化:小写并去掉空白与标点。"""
27
+ return re.sub(r"[\W_]+", "", (text or "").lower())
28
+
29
+
30
+ def bigrams(text: str) -> set[str]:
31
+ return {text[index:index + 2] for index in range(len(text) - 1)}
32
+
33
+
34
+ def overlap(left: str, right: str) -> float:
35
+ one, other = bigrams(squash(left)), bigrams(squash(right))
36
+ return len(one & other) / len(one | other) if one and other else 0.0
37
+
38
+
39
+ def snippet(text: str) -> str:
40
+ text = " ".join((text or "").split())
41
+ return text if len(text) <= EVIDENCE_CHARS else text[:EVIDENCE_CHARS] + "…"
42
+
43
+
44
+ def plain(value: Any, language: str = "zh") -> str:
45
+ """规则字段可能是字符串,也可能是 {zh, en}:按项目语言取文字(缺该语言时回退),其他类型当空。"""
46
+ if value is None:
47
+ return ""
48
+ text = versioned.pick(value, language)[0]
49
+ return text if isinstance(text, str) else ""
50
+
51
+
52
+ def custom_targets(root: Path) -> list[dict[str, str]]:
53
+ path = root / "OPINION.md"
54
+ try:
55
+ content = versioned.read_text(path) if path.exists() else ""
56
+ except (OSError, versioned.OpinionVersionError, UnicodeDecodeError):
57
+ return []
58
+ found = []
59
+ for number, line in custom_section_lines(content):
60
+ parsed = parse_line(line)
61
+ found.append({"type": "custom_line", "ref": f"OPINION.md:{number}", "title": parsed["title"] if parsed else "",
62
+ "text": parsed["text"] if parsed else line.lstrip("- ").strip(), "trigger": parsed["trigger"] if parsed else ""})
63
+ return found
64
+
65
+
66
+ def public_targets(root: Path) -> list[dict[str, str]]:
67
+ """Profile 里已选的公开规则(锁里的有效规则);没有锁或读不了时为空。"""
68
+ try:
69
+ profile = versioned.read_object(root / "opinion.lock.json")["profile"]
70
+ language = versioned.project_language(root)
71
+ rules = versioned.effective_rules(profile).values()
72
+ return [{"type": "public_rule", "ref": f"{rule['id']}@{rule['version']}", "title": plain(rule["title"], language),
73
+ "text": plain(rule["text"], language), "trigger": plain(rule.get("trigger"), language)} for rule in rules]
74
+ except (OSError, ValueError, KeyError, TypeError, versioned.OpinionVersionError):
75
+ return []
76
+
77
+
78
+ def targets(root: Path, data: dict[str, Any]) -> list[dict[str, str]]:
79
+ """一次性准备全部比较对象;candidate 的 ref 为候选编号。"""
80
+ others = [{"type": "candidate", "ref": item["id"], "title": item["title"], "text": item["text"], "trigger": item.get("trigger") or ""}
81
+ for item in data["candidates"].values() if item["status"] != "rejected"]
82
+ return others + custom_targets(root) + public_targets(root)
83
+
84
+
85
+ def relations_for(candidate: dict[str, Any], pool: list[dict[str, str]]) -> list[dict[str, Any]]:
86
+ """candidate 与 pool 的机械提示,最相关的在前,最多 MAX_RELATIONS 条;没有则为空列表。"""
87
+ text, trigger = squash(candidate["text"]), candidate.get("trigger") or ""
88
+ found = []
89
+ for other in pool:
90
+ if other["type"] == "candidate" and other["ref"] == candidate["id"]:
91
+ continue
92
+ other_text = squash(other["text"])
93
+ kind, score = None, 0.0
94
+ if text and (text == other_text or squash(candidate["title"] + candidate["text"]) == squash(other["title"] + other["text"])):
95
+ kind, score = "same_text", 1.0
96
+ elif len(text) >= MIN_TEXT_CHARS and len(other_text) >= MIN_TEXT_CHARS and (score := overlap(text, other_text)) >= TEXT_OVERLAP:
97
+ kind = "text_overlap"
98
+ elif (trigger and other["trigger"] and not is_global(trigger) and not is_global(other["trigger"])
99
+ and len(squash(trigger)) >= MIN_CONDITION_CHARS and len(squash(other["trigger"])) >= MIN_CONDITION_CHARS
100
+ and (score := overlap(trigger, other["trigger"])) >= CONDITION_OVERLAP):
101
+ kind = "condition_overlap"
102
+ if kind:
103
+ found.append({"kind": kind, "with": {"type": other["type"], "ref": other["ref"]}, "title": other["title"],
104
+ "score": round(score, 2), "evidence": snippet(other["trigger"] if kind == "condition_overlap" else other["text"])})
105
+ found.sort(key=lambda item: (ORDER[item["kind"]], -item["score"], item["with"]["ref"]))
106
+ return found[:MAX_RELATIONS]
@@ -0,0 +1,132 @@
1
+ """路由规则(opinion 规则指定「某类任务使用某个 skill」)的只读清单与机械检查。
2
+
3
+ 清单来源:收件箱候选,以及 OPINION.md 自定义规则小节里本工具自己渲染的行(行末 ``[route …]`` 标记)。认不出的行标「未结构化」,
4
+ 从不猜测。机械检查只比较标记里的字段与字节数,只警告、不阻断,也不检查 skill 是否存在(那需要 agenthelm inventory,属于下一版)。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Any, Callable
11
+
12
+ import versioned
13
+ from rule_lines import candidate_rule, custom_section_lines, parse_line, parse_marker
14
+
15
+ MAX_ROUTES = 6 # 每个项目的路由条数预算(设计文档第 6 节)
16
+ MAX_LINE_BYTES = 500 # 单条路由规则行的字节预算
17
+ LIVE_STATUSES = ("pending", "trial", "formal") # held / rejected 不在生效或待裁决范围内
18
+ UNCHECKED = ("skill_exists", "semantic_overlap", "indirect_cycle", "skill_behavior_drift")
19
+
20
+
21
+ def line_bytes(line: str) -> int:
22
+ return len(line.encode("utf-8"))
23
+
24
+
25
+ def route_entry(candidate: dict[str, Any], language: str) -> dict[str, Any]:
26
+ route = candidate["route"]
27
+ return {"source": "candidate", "ref": candidate["id"], "title": candidate["title"], "status": candidate["status"], "structure": "route",
28
+ **route_fields(route), "bytes": line_bytes(candidate_rule(candidate, language))}
29
+
30
+
31
+ def route_fields(route: dict[str, Any]) -> dict[str, Any]:
32
+ return {"skill": route["skill"], "when": route["when"], "final": bool(route.get("final")), "on": route.get("on") or ""}
33
+
34
+
35
+ def custom_entries(root: Path) -> list[dict[str, Any]]:
36
+ path = root / "OPINION.md"
37
+ try:
38
+ content = versioned.read_text(path) if path.exists() else ""
39
+ except (OSError, versioned.OpinionVersionError, UnicodeDecodeError):
40
+ return []
41
+ found = []
42
+ for number, line in custom_section_lines(content):
43
+ parsed = parse_line(line)
44
+ base = {"source": "custom_line", "ref": f"OPINION.md:{number}", "line": number, "bytes": line_bytes(line)}
45
+ if parsed is None:
46
+ route, problem = parse_marker(line)
47
+ if route or problem or "skill" in line.lower():
48
+ found.append({**base, "structure": "unstructured", "text": " ".join(line.split())[:80]})
49
+ elif parsed.get("route"):
50
+ found.append({**base, "structure": "route", "title": parsed["title"], **route_fields(parsed["route"])})
51
+ elif parsed.get("route_error"):
52
+ found.append({**base, "structure": parsed["route_error"], "title": parsed["title"]})
53
+ return found
54
+
55
+
56
+ def collect(root: Path, data: dict[str, Any], language: str) -> list[dict[str, Any]]:
57
+ """候选在前(按创建时间),OPINION.md 的行在后(按行号)。已转正并写入的候选以 OPINION.md 的行为准,不重复计数。"""
58
+ custom = custom_entries(root)
59
+ written = {(item.get("title"), item.get("skill")) for item in custom if item["structure"] == "route"}
60
+ entries = []
61
+ for candidate in sorted(data["candidates"].values(), key=lambda item: (item["created_at"], item["id"])):
62
+ if candidate["status"] in LIVE_STATUSES and candidate.get("route"):
63
+ if candidate["status"] == "formal" and (candidate["title"], candidate["route"]["skill"]) in written:
64
+ continue
65
+ entries.append(route_entry(candidate, language))
66
+ return entries + custom
67
+
68
+
69
+ def checks(entries: list[dict[str, Any]], say: Callable[..., str]) -> list[dict[str, Any]]:
70
+ """机械检查,全部只警告。只比较标记字段与字节数,不判断语义。"""
71
+ routed = [item for item in entries if item["structure"] == "route"]
72
+ found: list[dict[str, Any]] = []
73
+
74
+ def add(code: str, refs: list[str], **fields: Any) -> None:
75
+ found.append({"code": code, "severity": "warn", "refs": refs, "detail": say(f"routes_check_{code}", **fields), "note": say("routes_check_note")})
76
+
77
+ groups: dict[tuple[str, str], list[dict[str, Any]]] = {}
78
+ for item in routed:
79
+ if item["on"]:
80
+ groups.setdefault((item["on"], item["when"]), []).append(item)
81
+ for (tag, when), members in sorted(groups.items()):
82
+ skills = sorted({item["skill"] for item in members})
83
+ if len(skills) > 1:
84
+ add("same_tag_different_skill", [item["ref"] for item in members], on=tag, when=when, skills=say("sep").join(skills))
85
+ same: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
86
+ for item in routed:
87
+ same.setdefault((item["skill"], item["on"], item["when"]), []).append(item)
88
+ for (skill, tag, when), members in sorted(same.items()):
89
+ if len(members) > 1:
90
+ add("duplicate_route", [item["ref"] for item in members], skill=skill, on=tag or say("routes_no_tag"), when=when, count=len(members))
91
+ finals = [item for item in routed if item["final"]]
92
+ if len(finals) > 1:
93
+ add("multiple_final", [item["ref"] for item in finals], count=len(finals))
94
+ if len(routed) > MAX_ROUTES:
95
+ add("too_many_routes", [item["ref"] for item in routed], count=len(routed), limit=MAX_ROUTES)
96
+ for item in routed:
97
+ if item["bytes"] > MAX_LINE_BYTES:
98
+ add("line_too_long", [item["ref"]], bytes=item["bytes"], limit=MAX_LINE_BYTES)
99
+ return found
100
+
101
+
102
+ def listing(root: Path, data: dict[str, Any], language: str, say: Callable[..., str]) -> dict[str, Any]:
103
+ entries = collect(root, data, language)
104
+ found = checks(entries, say)
105
+ return {"ok": True, "status": "read-only", "routes": entries, "checks": found, "unchecked": list(UNCHECKED), "note": say("routes_check_note"),
106
+ "summary": {"routes": sum(1 for item in entries if item["structure"] == "route"), "unstructured": sum(1 for item in entries if item["structure"] != "route"),
107
+ "warnings": len(found)}}
108
+
109
+
110
+ def entry_line(item: dict[str, Any], say: Callable[..., str]) -> str:
111
+ if item["structure"] != "route":
112
+ return say("routes_line_unstructured", ref=item["ref"], text=item.get("text") or item.get("title") or "")
113
+ return say("routes_line", ref=item["ref"], title=item.get("title") or "", route=route_text(item, say), bytes=item["bytes"])
114
+
115
+
116
+ def route_text(route: dict[str, Any], say: Callable[..., str]) -> str:
117
+ """skill X(时机,收尾,标签):list / brief / present 共用的一段路由说明。"""
118
+ extras = [say(f"route_when_{route['when']}")]
119
+ if route.get("final"):
120
+ extras.append(say("route_final"))
121
+ if route.get("on"):
122
+ extras.append(say("route_on", on=route["on"]))
123
+ return say("route_text", skill=route["skill"], extras=say("brief_join_short").join(extras))
124
+
125
+
126
+ def markdown(result: dict[str, Any], say: Callable[..., str]) -> str:
127
+ if not result["routes"]:
128
+ return say("routes_empty") + "\n"
129
+ lines = [entry_line(item, say) for item in result["routes"]]
130
+ lines += [say("routes_check_line", detail=item["detail"], note=item["note"]) for item in result["checks"]]
131
+ lines.append(say("routes_unchecked", items=", ".join(result["unchecked"])))
132
+ return "\n".join(lines) + "\n"
@@ -23,11 +23,9 @@ MESSAGES: dict[str, dict[str, str]] = {
23
23
  "zh": """[Opinion 协议 · agenthelm]
24
24
  1. 实施前读取项目 OPINION.md(如有)并按其要求工作;下列「试行」候选同样要遵循,交付时说明是否适用。
25
25
  2. 用户在对话里表达长期偏好、纠正或规则(如“以后都…”“不要再…”“必须…”“记住…”)时,先静默暂存为候选,不打断当前工作:
26
- python3 {runtime} inbox add --project {project} --title "<标题>" --text "<完整规则>" --scope "<适用范围>" --quote "<用户原话>"{session} --lang {lang}
27
- 一次性的任务要求、项目事实和命令不是候选。暂存不需要确认,也不会改变任何规则。
28
- 3. 任务完成或即将完成时,若本次暂存了候选,用编号列表一次性请用户裁决:正式采纳 / 项目内试行 / 暂缓 / 丢弃。
29
- 用户明确表态后记录:python3 {runtime} inbox decide <编号…> --project {project} --to trial|held|rejected --confirmed --lang {lang}
30
- 用户说“采纳”时不要 decide:直接 python3 {runtime} inbox adopt <编号…> --project {project} --lang {lang} 预览(零写入),展示 content,用户确认后加 --apply --confirm <confirmation_sha256> 一次写入并读回。「已批准」不等于「已生效」:只有 adopt --apply 成功才写入 OPINION.md。
26
+ python3 {runtime} inbox add --project {project} --title "<标题>" --text "<完整规则>" --scope "<适用范围>" --trigger "<何时适用>" --purpose "<为什么>" --quote "<用户原话>"{session} --lang {lang}
27
+ 暂存时就填好 trigger 与 purpose(缺失仅警告,展示与裁决时按「不完整」处理;可选 --exclude 写不适用情形);不得写「所有」之类占位词,确需全局须用户明确要求并带 --quote。一次性的任务要求、项目事实和命令不是候选。暂存不需要确认,也不会改变任何规则。
28
+ 3. {confirm}
31
29
  4. 未经用户确认,不得把候选写入 OPINION.md,也不得把一次出现当作确认。
32
30
  5. inbox add 的结果带 notice(首次暂存时出现)时,用一句话如实转告用户。收件箱保存用户原话,可能含敏感信息;
33
31
  是否公开仓库、是否排除 .opinion/ 由用户决定,不要自行修改 .gitignore、删除或改写内容。
@@ -35,15 +33,29 @@ MESSAGES: dict[str, dict[str, str]] = {
35
33
  "en": """[Opinion protocol · agenthelm]
36
34
  1. Before working, read the project's OPINION.md (if any) and follow it. The "trial" candidates listed below apply too; say in your delivery whether they applied.
37
35
  2. When the user states a lasting preference, a correction of your behavior or a rule during the conversation (e.g. "from now on...", "never again...", "must...", "remember..."), stash it as a candidate silently, without interrupting the current work:
38
- python3 {runtime} inbox add --project {project} --title "<title>" --text "<the full rule>" --scope "<where it applies>" --quote "<the user's own words>"{session} --lang {lang}
39
- One-off task requirements, project facts and commands are not candidates. Stashing needs no confirmation and changes no rule.
40
- 3. When the task is done or nearly done and you stashed candidates in this session, ask the user once, as a numbered list: adopt as formal / trial in this project / hold / discard.
41
- After the user states a decision explicitly, record it: python3 {runtime} inbox decide <ids...> --project {project} --to trial|held|rejected --confirmed --lang {lang}
42
- When the user says "adopt", do not decide: run python3 {runtime} inbox adopt <ids...> --project {project} --lang {lang} to preview (writes nothing), show the content, and once the user confirms add --apply --confirm <confirmation_sha256> to write and read back in one step. "Approved" is not "in effect": OPINION.md is written only when adopt --apply succeeds.
36
+ python3 {runtime} inbox add --project {project} --title "<title>" --text "<the full rule>" --scope "<where it applies>" --trigger "<when it applies>" --purpose "<why>" --quote "<the user's own words>"{session} --lang {lang}
37
+ Fill trigger and purpose at stash time (missing ones only warn, and the candidate is shown as incomplete when deciding; optional --exclude states when it does not apply); no placeholders like "all"; global only when the user explicitly asked, with --quote. One-off task requirements, project facts and commands are not candidates. Stashing needs no confirmation and changes no rule.
38
+ 3. {confirm}
43
39
  4. Never write a candidate into OPINION.md without the user's confirmation, and never treat a single occurrence as confirmation.
44
40
  5. When the result of inbox add carries a notice (shown on the first stash), pass it on to the user in one sentence, as written. The inbox stores the user's own words, which may contain sensitive information; whether to make the repository public or to exclude .opinion/ is the user's decision. Do not edit .gitignore, delete or rewrite anything yourself.
45
41
  6. Relay and confirm in the language the user is using.""",
46
42
  },
43
+ "protocol_ask": {
44
+ "zh": "确认(ask):下文 inbox 命令的 python3 前缀与 --project 同第 2 条,只换子命令与参数。本会话暂存了候选、任务完成或即将完成、要向用户确认前,先运行 inbox gate{session}{gate_options};allowed 为 false 则不问,继续工作。可以问时,用编号列表请用户裁决:正式采纳 / 项目内试行 / 暂缓 / 丢弃;展示时运行 inbox present <编号…> 记录快照。用户之后更新需求本身不触发确认。\n {handle}",
45
+ "en": "Confirmation (ask): the inbox commands below use the same python3 prefix and --project as the one in item 2, with only the subcommand and arguments changed. When you stashed candidates in this session, the task is done or nearly done and you are about to confirm with the user, first run inbox gate{session}{gate_options}; if allowed is false, do not ask and keep working. When allowed, ask as a numbered list: adopt as formal / trial in this project / hold / discard; while showing it, run inbox present <ids...> to record the snapshot. The user later updating a requirement is not itself a reason to confirm.\n {handle}",
46
+ },
47
+ "protocol_digest": {
48
+ "zh": "确认(digest):下文 inbox 命令的 python3 前缀与 --project 同第 2 条,只换子命令与参数。对话里不单独询问。本会话暂存了候选时,只在任务回复末尾顺带一句说明有几条待处理,每会话至多一次;用户想处理时,用编号列表展示全文并运行 inbox present <编号…>。其余由会话开始的汇总提示。\n {handle}",
49
+ "en": "Confirmation (digest): the inbox commands below use the same python3 prefix and --project as the one in item 2, with only the subcommand and arguments changed. Do not interrupt the conversation with a separate ask. When you stashed candidates in this session, add one closing sentence to a task reply saying how many are waiting, at most once per session; when the user wants to handle them, show the full numbered list and run inbox present <ids...>. The rest is covered by the summary at session start.\n {handle}",
50
+ },
51
+ "protocol_quiet": {
52
+ "zh": "确认(quiet):下文 inbox 命令的 python3 前缀与 --project 同第 2 条,只换子命令与参数。不要在对话里主动提起候选,只由会话开始的汇总提示。用户主动询问或要求处理时,用编号列表展示全文并运行 inbox present <编号…>。\n {handle}",
53
+ "en": "Confirmation (quiet): the inbox commands below use the same python3 prefix and --project as the one in item 2, with only the subcommand and arguments changed. Do not bring candidates up in the conversation; the summary at session start covers them. When the user asks about them or wants to handle them, show the full numbered list and run inbox present <ids...>.\n {handle}",
54
+ },
55
+ "protocol_handle": {
56
+ "zh": "表态后记录:inbox decide <编号…> --to trial|held|rejected --confirmed\n 用户说“采纳”时不要 decide:运行 inbox adopt <编号…> --lang {lang} 预览(零写入)。shown_matches 为真、无 blocked、无冲突时,视为已确认,直接加 --apply --confirm <confirmation_sha256> 写入并读回,告知结果与回退方式(上一个 Profile 版本仍在 .opinion/profiles/ 下);否则展示预览差异后再问一次。「已批准」不等于「已生效」:只有 adopt --apply 成功才写入 OPINION.md。",
57
+ "en": "After a decision, record it: inbox decide <ids...> --to trial|held|rejected --confirmed\n When the user says \"adopt\", do not decide: run inbox adopt <ids...> --lang {lang} to preview (writes nothing). If shown_matches is true with no blocked and no conflicts, treat it as confirmed and add --apply --confirm <confirmation_sha256> to write and read back, then tell the user the result and how to go back (the previous Profile version is still under .opinion/profiles/); otherwise show the preview differences and ask once more. \"Approved\" is not \"in effect\": OPINION.md is written only when adopt --apply succeeds.",
58
+ },
47
59
  "exposure_notice": {
48
60
  "zh": "收件箱会把你的原话保存在 .opinion/inbox.json,其中可能含敏感信息。启用本功能的项目建议保持私有;"
49
61
  "若要公开仓库或让他人看到,是否排除 .opinion/ 及其中内容由你决定。本工具不会替你决定,也不会修改 .gitignore。",
@@ -63,6 +75,50 @@ MESSAGES: dict[str, dict[str, str]] = {
63
75
  "label_text": {"zh": "规则正文", "en": "Rule text"},
64
76
  "label_quote": {"zh": "用户原话", "en": "User's words"},
65
77
  "label_scope": {"zh": "适用范围", "en": "Scope"},
78
+ "label_trigger": {"zh": "触发条件", "en": "Trigger"},
79
+ "label_purpose": {"zh": "目的", "en": "Purpose"},
80
+ "label_exclude": {"zh": "不适用情形", "en": "Exclusion"},
81
+ "label_relation": {"zh": "关系备注", "en": "Relation note"},
82
+ "err_placeholder": {"zh": "{label}不能是占位词({value}):请写具体的条件;确需全局时用标准全局值并附 --quote",
83
+ "en": "{label} must not be a placeholder ({value}): write a concrete condition; if it really is global, use the standard global value and add --quote"},
84
+ "err_global_quote": {"zh": "全局声明(触发条件为「全部场景,用户要求全局」)必须同时带非空 --quote(用户原话)",
85
+ "en": "A global declaration (trigger \"All scenarios; the user asked for this to apply globally\") needs a non-empty --quote with the user's own words"},
86
+ "err_missing_fields": {"zh": "缺少必填项:{fields}", "en": "Missing required fields: {fields}"},
87
+ "warn_missing_fields": {"zh": "已暂存,但缺少:{fields}。候选会按「不完整」展示;请补全(inbox add 时带 --trigger / --purpose)后再请用户裁决。",
88
+ "en": "Stashed, but missing: {fields}. The candidate will be shown as incomplete; fill them in (--trigger / --purpose on inbox add) before asking the user to decide."},
89
+ "global_mark": {"zh": " [全局(请用户确认)]", "en": " [Global (ask the user to confirm)]"},
90
+ "list_trigger": {"zh": " - 条件:{value}{mark}", "en": " - Trigger: {value}{mark}"},
91
+ "list_purpose": {"zh": " - 目的:{value}{mark}", "en": " - Purpose: {value}{mark}"},
92
+ "list_exclude": {"zh": " - 不适用:{value}{mark}", "en": " - Not for: {value}{mark}"},
93
+ "list_relation": {"zh": " - 关系备注:{value}{mark}", "en": " - Relation note: {value}{mark}"},
94
+ "list_incomplete": {"zh": " - 不完整:缺少{fields}", "en": " - Incomplete: missing {fields}"},
95
+ "kind_same_text": {"zh": "正文相同", "en": "same text"},
96
+ "kind_text_overlap": {"zh": "正文相近", "en": "similar text"},
97
+ "kind_condition_overlap": {"zh": "条件相近", "en": "similar condition"},
98
+ "relations_note": {"zh": "机械比对,仅供参考", "en": "Mechanical comparison, for reference only"},
99
+ "list_relations": {"zh": " - 可能相关({kind},机械比对,仅供参考):{ref}:{evidence}",
100
+ "en": " - Possibly related ({kind}; mechanical comparison, for reference only): {ref}: {evidence}"},
101
+ "err_revise_one": {"zh": "revise 需要且只能有一个候选编号", "en": "revise needs exactly one candidate id"},
102
+ "err_revise_nothing": {"zh": "revise 至少要改一项:--title / --text / --scope / --trigger / --purpose / --exclude / --relation / --quote",
103
+ "en": "revise must change something: --title / --text / --scope / --trigger / --purpose / --exclude / --relation / --quote"},
104
+ "err_revise_confirm": {"zh": "候选状态为 {status}(或已展示给用户):修订需要用户确认,先向用户展示修订后的全文,同意后加 --confirmed",
105
+ "en": "The candidate is {status} (or was already shown to the user): revising it needs the user's confirmation; show the user the revised text first and add --confirmed once they agree"},
106
+ "err_revise_collision": {"zh": "修订后的标题与正文和候选 {id} 重复;请改为合并到该候选,或区分两者",
107
+ "en": "The revised title and text duplicate candidate {id}; merge into that candidate or tell them apart"},
108
+ "warn_revise_formal": {"zh": "候选已是 formal:OPINION.md 不会随之改变;要改已写入的规则,走 adopt 的完整预览流程。",
109
+ "en": "The candidate is formal: OPINION.md does not change with it; to change a rule already written, go through the full adopt preview flow."},
110
+ "check_next": {"zh": "逐条给出建议的条件与目的:候选用 revise_command 补全(尚未展示时无需确认,已展示需 --confirmed);OPINION.md 里的行走现有的 adopt 完整预览流程,由用户一次批量确认后写入,本命令不写任何文件。「未结构化」的行只作报告,不要擅自改写。",
111
+ "en": "Propose a suggested trigger and purpose for each item: fix candidates with revise_command (no confirmation while not yet shown, --confirmed once shown); lines in OPINION.md go through the existing full adopt preview flow, confirmed by the user in one batch; this command writes no file. Lines marked unstructured are only reported; do not rewrite them on your own."},
112
+ "check_clean": {"zh": "没有缺少条件或目的的候选,OPINION.md 里也没有需要补全的行。", "en": "No candidate lacks a trigger or purpose, and no line in OPINION.md needs completing."},
113
+ "err_cooldown": {"zh": "--cooldown-hours 不能为负数", "en": "--cooldown-hours must not be negative"},
114
+ "err_max_per_session": {"zh": "--max-per-session 必须是正整数", "en": "--max-per-session must be a positive integer"},
115
+ "gate_ok": {"zh": "可以询问。", "en": "An ask is allowed."},
116
+ "gate_cooldown": {"zh": "距上次询问不足冷却时间:本次不要询问。", "en": "Still within the cooldown since the last ask: do not ask this time."},
117
+ "gate_session_limit": {"zh": "本会话已询问到上限:本次不要询问。", "en": "This session has reached its ask limit: do not ask this time."},
118
+ "brief_trigger": {"zh": "条件:{value}", "en": "when: {value}"},
119
+ "brief_purpose": {"zh": "目的:{value}", "en": "purpose: {value}"},
120
+ "brief_exclude": {"zh": "不适用:{value}", "en": "not for: {value}"},
121
+ "brief_join": {"zh": ";", "en": "; "},
66
122
  "err_symlink": {"zh": "拒绝使用符号链接:{path}", "en": "Refusing to use a symbolic link: {path}"},
67
123
  "err_format": {"zh": "收件箱格式不正确:{path}", "en": "The inbox file is malformed: {path}"},
68
124
  "err_empty": {"zh": "{label}不能为空", "en": "{label} must not be empty"},
@@ -98,12 +154,51 @@ MESSAGES: dict[str, dict[str, str]] = {
98
154
  "list_rule": {"zh": " - 规则:{text}", "en": " - Rule: {text}"},
99
155
  "list_scope": {"zh": " - 适用:{scopes}", "en": " - Applies to: {scopes}"},
100
156
  "list_quote": {"zh": " - 用户原话:{quote}", "en": " - User's words: {quote}"},
157
+ "err_route_need_skill": {"zh": "--route-when / --route-final / --route-on 需要 --route-skill(revise 时候选已有路由则可省略)",
158
+ "en": "--route-when / --route-final / --route-on need --route-skill (on revise it may be omitted when the candidate already has a route)"},
159
+ "err_route_skill": {"zh": "--route-skill 必须是 skill 名称:小写字母、数字、连字符,不超过 64 字符(不接受 plugin:skill):{value}",
160
+ "en": "--route-skill must be a skill name: lowercase letters, digits and hyphens, at most 64 characters (plugin:skill is not accepted): {value}"},
161
+ "err_route_when": {"zh": "--route-when 必须是 before、after、instead 之一:{value}", "en": "--route-when must be one of before, after, instead: {value}"},
162
+ "err_route_final": {"zh": "--route-final 只能与 after 合用(不给 --route-when 时默认 after)", "en": "--route-final only goes with after (without --route-when it defaults to after)"},
163
+ "err_route_on": {"zh": "--route-on 必须是短标签:小写字母、数字、连字符,1 到 32 字符:{value}", "en": "--route-on must be a short tag: lowercase letters, digits and hyphens, 1 to 32 characters: {value}"},
164
+ "warn_route_long": {"zh": "路由规则行 {bytes} 字节,超过 {limit} 字节的预算(只警告):请精简标题、正文或条件。",
165
+ "en": "The route rule line is {bytes} bytes, over the {limit}-byte budget (warning only): shorten the title, text or trigger."},
166
+ "route_text": {"zh": "skill {skill}({extras})", "en": "skill {skill} ({extras})"},
167
+ "route_when_before": {"zh": "开始前", "en": "before"},
168
+ "route_when_after": {"zh": "完成后", "en": "after"},
169
+ "route_when_instead": {"zh": "取代默认做法", "en": "instead"},
170
+ "route_final": {"zh": "收尾", "en": "final"},
171
+ "route_on": {"zh": "标签 {on}", "en": "tag {on}"},
172
+ "brief_join_short": {"zh": ",", "en": ", "},
173
+ "list_route": {"zh": " - 路由:{value}", "en": " - Route: {value}"},
174
+ "brief_route": {"zh": "路由:{value}", "en": "route: {value}"},
175
+ "routes_check_note": {"zh": "机械检查,仅供参考", "en": "Mechanical check, for reference only"},
176
+ "routes_empty": {"zh": "没有路由规则。", "en": "No route rules."},
177
+ "routes_no_tag": {"zh": "无标签", "en": "no tag"},
178
+ "routes_line": {"zh": "- {ref} {title}:{route},{bytes} 字节", "en": "- {ref} {title}: {route}, {bytes} bytes"},
179
+ "routes_line_unstructured": {"zh": "- {ref} 未结构化(本工具认不出的格式,只作报告):{text}", "en": "- {ref} unstructured (a format this tool does not recognize; reported only): {text}"},
180
+ "routes_check_line": {"zh": "- 提示({note}):{detail}", "en": "- Notice ({note}): {detail}"},
181
+ "routes_unchecked": {"zh": "本命令不检查:{items}(skill 是否存在需 agenthelm inventory,下一版提供)", "en": "Not checked by this command: {items} (whether a skill exists needs agenthelm inventory, planned for the next release)"},
182
+ "routes_check_same_tag_different_skill": {"zh": "标签 {on} 下,同一时机({when})路由到不同 skill:{skills}", "en": "Under tag {on}, the same timing ({when}) routes to different skills: {skills}"},
183
+ "routes_check_duplicate_route": {"zh": "重复路由:skill {skill}、标签 {on}、时机 {when} 共 {count} 条", "en": "Duplicate route: skill {skill}, tag {on}, timing {when}, {count} rules"},
184
+ "routes_check_multiple_final": {"zh": "项目里有 {count} 条收尾(--route-final)路由,通常只应有一条", "en": "The project has {count} final (--route-final) routes; normally there should be only one"},
185
+ "routes_check_too_many_routes": {"zh": "共 {count} 条路由,超过 {limit} 条的预算", "en": "{count} routes in total, over the budget of {limit}"},
186
+ "routes_check_line_too_long": {"zh": "单条 {bytes} 字节,超过 {limit} 字节的预算", "en": "A single rule is {bytes} bytes, over the budget of {limit}"},
187
+ "err_route_clear_exclusive": {"zh": "--route-clear 不能与其他 --route-* 参数同时使用", "en": "--route-clear cannot be combined with the other --route-* options"},
188
+ "err_tag_none": {"zh": "当前项目没有标签词表(Profile 需要 schema 2.2 的 loading.tags 声明),不能使用 --tag",
189
+ "en": "This project has no tag vocabulary (the Profile needs a schema 2.2 loading.tags declaration), so --tag cannot be used"},
190
+ "err_tag_unknown": {"zh": "未知标签:{value};有效标签:{valid}", "en": "Unknown tag: {value}; valid tags: {valid}"},
191
+ "err_tag_clear_exclusive": {"zh": "--tag-clear 不能与 --tag 同时使用", "en": "--tag-clear cannot be combined with --tag"},
192
+ "list_tags": {"zh": " - 标签:{value}", "en": " - Tags: {value}"},
193
+ "err_routes_action": {"zh": "routes 只支持 list", "en": "routes only supports list"},
101
194
  "brief_trial_header": {
102
195
  "zh": "\n[试行候选 · 用户已同意在本项目试用,尚未正式;按其工作并在交付时说明是否适用]",
103
196
  "en": "\n[Trial candidates · the user agreed to try these in this project; not formal yet. Follow them and say in your delivery whether they applied]"},
104
197
  "brief_trial_entry": {"zh": "- {id} {title}:{text}(适用:{scopes})", "en": "- {id} {title}: {text} (applies to: {scopes})"},
105
198
  "brief_trial_more": {"zh": "- …另有 {count} 条试行候选未展示:运行 inbox list --status trial 查看",
106
199
  "en": "- ...{count} more trial candidates not shown: run inbox list --status trial"},
200
+ "brief_pending_quiet": {"zh": "\n[待确认候选 {count} 条,尚未生效;不要在对话里单独询问,由会话开始的汇总提示]",
201
+ "en": "\n[{count} candidates await confirmation and are not in effect yet; do not ask about them separately in the conversation]"},
107
202
  "brief_pending": {"zh": "\n[待确认候选 {count} 条,尚未生效;任务结束前可向用户集中确认]",
108
203
  "en": "\n[{count} candidates await confirmation and are not in effect yet; ask the user to decide them together before the task ends]"},
109
204
  }
@@ -112,7 +207,7 @@ PLACEHOLDER = re.compile(r"\{(\w+)\}")
112
207
 
113
208
 
114
209
  # protocol 里的 {runtime} {project} 会被模型原样当作命令行执行,代入的路径必须经 shell 引用(POSIX)。
115
- COMMAND_MESSAGES = {"protocol"}
210
+ COMMAND_MESSAGES = {"protocol", "protocol_ask", "protocol_digest", "protocol_quiet", "protocol_handle"}
116
211
  PATH_FIELDS = ("runtime", "project")
117
212
 
118
213
 
@@ -125,3 +220,14 @@ def text(message_id: str, language: str, /, **fields: Any) -> str:
125
220
  if message_id in COMMAND_MESSAGES:
126
221
  fields = {key: shlex.quote(str(value)) if key in PATH_FIELDS else value for key, value in fields.items()}
127
222
  return MESSAGES[message_id][language].format(**fields)
223
+
224
+
225
+ def protocol(language: str, *, runtime: Any, project: Any, lang: str, session: str = "", mode: str = "ask",
226
+ cooldown: float = 24, limit: int = 1) -> str:
227
+ """注入协议:公共部分加按确认模式(ask / digest / quiet)生成的第 3 条。session 是会话 ID(空串表示未知)。"""
228
+ flag = session_flag(session)
229
+ handle = text("protocol_handle", language, runtime=runtime, project=project, lang=lang)
230
+ options = (f" --cooldown-hours {cooldown:g}" if cooldown != 24 else "") + (f" --max-per-session {limit}" if limit != 1 else "")
231
+ confirm = text(f"protocol_{mode}", language, runtime=runtime, project=project, lang=lang, session=flag,
232
+ gate_options=options, handle=handle)
233
+ return text("protocol", language, runtime=runtime, project=project, lang=lang, session=flag, confirm=confirm)
@@ -100,14 +100,31 @@ def record_use(event: dict[str, Any], lock: dict[str, Any], roots: tuple[str, ..
100
100
  if use["passed"] and "violated" in results.values():
101
101
  fail(_("存在违反的规则时 passed 不能为 true"))
102
102
  use["results"] = results
103
- bundles = {bundle["family"] for bundle in profile["loading"]["bundles"]} if "loading" in profile else None
103
+ loading = profile.get("loading")
104
+ tag_ids = [tag["id"] for tag in loading["tags"]] if isinstance(loading, dict) and "tags" in loading else None
105
+ bundles = {bundle["family"] for bundle in loading.get("bundles", [])} if tag_ids is None and loading else None
104
106
  for key in ("loaded_bundles", "routing_miss"):
105
107
  if key in event:
108
+ if tag_ids is not None:
109
+ fail(_("当前 Profile 使用标签声明(schema 2.2),请改用 {0}").format("loaded_tags" if key == "loaded_bundles" else "routing_miss_tags"))
106
110
  if bundles is None:
107
111
  fail(_("当前 Profile 未声明分层加载,不能记录 {0}").format(key))
108
112
  if not isinstance(event[key], list) or not set(event[key]) <= bundles or len(event[key]) != len(set(event[key])):
109
113
  fail(_("{0} 必须是已声明规则束的不重复列表").format(key))
110
114
  use[key] = event[key]
115
+ for key in ("loaded_tags", "routing_miss_tags"):
116
+ if key in event:
117
+ if tag_ids is None:
118
+ fail(_("当前 Profile 未声明标签(schema 2.2),不能记录 {0};规则束声明请用 loaded_bundles 与 routing_miss").format(key))
119
+ names = event[key]
120
+ if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
121
+ fail(_("{0} 必须是标签 id 的列表").format(key))
122
+ if len(names) != len(set(names)):
123
+ fail(_("{0} 含有重复标签").format(key))
124
+ unknown = [name for name in names if name not in tag_ids]
125
+ if unknown:
126
+ fail(_("{0} 含有未声明的标签:{1};有效标签:{2}").format(key, _("、").join(unknown), _("、").join(tag_ids)))
127
+ use[key] = names
111
128
  if "date" in event:
112
129
  if not isinstance(event["date"], str) or not DATE.fullmatch(event["date"]):
113
130
  fail(_("date 必须为 YYYY-MM-DD"))
@@ -181,7 +198,7 @@ def reduce(state: dict[str, Any], event: dict[str, Any], lock: dict[str, Any] |
181
198
  fail(_("use 指向的 Opinion 内容已经变化"))
182
199
  use = record_use(event, lock, roots)
183
200
  rollout["uses"].append(use)
184
- if not use["fixture"] and (not use["passed"] or use["user_changed"] or use.get("routing_miss")):
201
+ if not use["fixture"] and (not use["passed"] or use["user_changed"] or use.get("routing_miss") or use.get("routing_miss_tags")):
185
202
  rollout["blockers"].append(event_hash)
186
203
  elif kind == "formalize":
187
204
  rollout = result["rollouts"][profile_ref(lock["profile"])]
@@ -215,7 +232,7 @@ def evidence_valid(root: Path, state: dict[str, Any]) -> None:
215
232
 
216
233
 
217
234
  def successful(use: dict[str, Any]) -> bool:
218
- return not use["fixture"] and use["passed"] and not use["user_changed"] and not use.get("routing_miss")
235
+ return not use["fixture"] and use["passed"] and not use["user_changed"] and not use.get("routing_miss") and not use.get("routing_miss_tags")
219
236
 
220
237
 
221
238
  def carried_uses(state: dict[str, Any], profile: dict[str, Any], profiles_root: Path) -> tuple[list[dict[str, Any]], list[dict[str, str]]]:
@@ -261,9 +278,22 @@ def coverage_view(state: dict[str, Any], profile: dict[str, Any], profiles_root:
261
278
  "carried_uses": len([use for use in carried if not use["fixture"]]), "not_carried": skipped,
262
279
  "distinct_successful_uses": len({use["occurrence"] for use in uses if successful(use)}),
263
280
  "rules": rules, "unused_rules": [item["ref"] for item in rules if not item["distinct_successful_uses"]]}
264
- if "loading" in profile:
281
+ if "loading" in profile and "tags" in profile["loading"]:
282
+ members = profile["loading"]["members"]
283
+ tags = []
284
+ for tag in profile["loading"]["tags"]:
285
+ name = tag["id"]
286
+ owned = {rule for rule, names in members.items() if name in names}
287
+ good = [use for use in uses if successful(use)]
288
+ tags.append({"tag": name, "kind": "tag",
289
+ "loaded_in": len({use["occurrence"] for use in good if name in use.get("loaded_tags", [])}),
290
+ "exercised_in": len({use["occurrence"] for use in good if owned & {ref.rsplit("@", 1)[0] for ref in use["rules"]}}),
291
+ "routing_misses": sum(1 for use in uses if not use["fixture"] and name in use.get("routing_miss_tags", []))})
292
+ result["tags"] = tags
293
+ result["unused_tags"] = [item["tag"] for item in tags if not item["exercised_in"]]
294
+ elif "loading" in profile:
265
295
  bundles = []
266
- for bundle in profile["loading"]["bundles"]:
296
+ for bundle in profile["loading"].get("bundles", []):
267
297
  family = bundle["family"]
268
298
  members = {rule for rule, owner in families.items() if owner == family}
269
299
  good = [use for use in uses if successful(use)]