@sakanano-moe/agenthelm 6.13.1 → 6.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/package.json +1 -1
  2. package/runtime/index.json +6 -6
  3. package/runtime/plugins/agent-pack/.codex-plugin/plugin.json +1 -1
  4. package/runtime/plugins/agent-pack/plugin.json +1 -1
  5. package/runtime/plugins/agent-pack/references/capability-config.md +10 -0
  6. package/runtime/plugins/agent-pack/references/check-opinion-migrate.en.md +31 -0
  7. package/runtime/plugins/agent-pack/references/check-opinion-migrate.md +31 -0
  8. package/runtime/plugins/agent-pack/references/dedupe-contract.en.md +27 -0
  9. package/runtime/plugins/agent-pack/references/dedupe-contract.md +27 -0
  10. package/runtime/plugins/agent-pack/references/inventory-contract.en.md +83 -0
  11. package/runtime/plugins/agent-pack/references/inventory-contract.md +83 -0
  12. package/runtime/plugins/agent-pack/references/nudge.en.md +10 -2
  13. package/runtime/plugins/agent-pack/references/nudge.md +10 -2
  14. package/runtime/plugins/agent-pack/references/relocate-contract.en.md +41 -0
  15. package/runtime/plugins/agent-pack/references/relocate-contract.md +41 -0
  16. package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +572 -30
  17. package/runtime/plugins/agent-pack/runtime/agent_pack_clients.py +233 -0
  18. package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +112 -4
  19. package/runtime/plugins/agent-pack/runtime/agent_pack_dedupe.py +502 -0
  20. package/runtime/plugins/agent-pack/runtime/agent_pack_desktop.py +92 -0
  21. package/runtime/plugins/agent-pack/runtime/agent_pack_ext_common.py +251 -0
  22. package/runtime/plugins/agent-pack/runtime/agent_pack_inventory.py +989 -0
  23. package/runtime/plugins/agent-pack/runtime/agent_pack_mcp_write.py +447 -0
  24. package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +29 -4
  25. package/runtime/plugins/agent-pack/runtime/agent_pack_relocate.py +385 -0
  26. package/runtime/plugins/agent-pack/runtime/agent_pack_scope.py +233 -0
  27. package/runtime/plugins/agent-pack/runtime/agenthelm.py +183 -14
  28. package/runtime/plugins/agent-pack/runtime/locale/en.json +250 -1
  29. package/runtime/plugins/agent-pack/runtime/mcp_server.py +12 -0
  30. package/runtime/plugins/agent-pack/runtime/nudge_text.py +8 -2
  31. package/runtime/plugins/agent-pack/runtime/user_settings.py +2 -1
  32. package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +15 -0
  33. package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
  34. package/runtime/plugins/agents-init/content.json +4 -2
  35. package/runtime/plugins/agents-init/plugin.json +1 -1
  36. package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +2 -0
  37. package/runtime/plugins/agents-init/skills/agents-init/launcher.en.sh +93 -0
  38. package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +27 -0
  39. package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +4 -1
  40. package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +24 -9
  41. package/runtime/plugins/agents-init/skills/agents-init/skill.json +1 -1
  42. package/runtime/plugins/opinion-manager/.codex-plugin/plugin.json +1 -1
  43. package/runtime/plugins/opinion-manager/catalog/README.md +3 -1
  44. package/runtime/plugins/opinion-manager/catalog/rules/om.align-requirements/versions/1.1.0.json +34 -0
  45. package/runtime/plugins/opinion-manager/catalog/rules/om.assumptions-authority/versions/1.1.0.json +34 -0
  46. package/runtime/plugins/opinion-manager/catalog/rules/om.batch-questions/versions/1.1.0.json +34 -0
  47. package/runtime/plugins/opinion-manager/catalog/rules/om.bilingual-terms/versions/1.1.0.json +34 -0
  48. package/runtime/plugins/opinion-manager/catalog/rules/om.calculations/versions/1.1.0.json +34 -0
  49. package/runtime/plugins/opinion-manager/catalog/rules/om.chinese-response/versions/1.1.0.json +34 -0
  50. package/runtime/plugins/opinion-manager/catalog/rules/om.clean-deliverable/versions/1.1.0.json +34 -0
  51. package/runtime/plugins/opinion-manager/catalog/rules/om.complete-options/versions/1.1.0.json +34 -0
  52. package/runtime/plugins/opinion-manager/catalog/rules/om.conclusion-first/versions/1.1.0.json +34 -0
  53. package/runtime/plugins/opinion-manager/catalog/rules/om.concrete-titles/versions/1.1.0.json +34 -0
  54. package/runtime/plugins/opinion-manager/catalog/rules/om.consistent-items/versions/1.1.0.json +34 -0
  55. package/runtime/plugins/opinion-manager/catalog/rules/om.device-readable/versions/1.1.0.json +34 -0
  56. package/runtime/plugins/opinion-manager/catalog/rules/om.editable-diagrams/versions/1.1.0.json +34 -0
  57. package/runtime/plugins/opinion-manager/catalog/rules/om.evidence-inference/versions/1.1.0.json +34 -0
  58. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-chinese/versions/1.1.0.json +34 -0
  59. package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-project-language/versions/1.1.0.json +34 -0
  60. package/runtime/plugins/opinion-manager/catalog/rules/om.markdown-structure/versions/1.1.0.json +34 -0
  61. package/runtime/plugins/opinion-manager/catalog/rules/om.portable-files/versions/1.1.0.json +34 -0
  62. package/runtime/plugins/opinion-manager/catalog/rules/om.report-context/versions/1.1.0.json +34 -0
  63. package/runtime/plugins/opinion-manager/catalog/rules/om.report-formats/versions/1.1.0.json +34 -0
  64. package/runtime/plugins/opinion-manager/catalog/rules/om.report-review/versions/1.1.0.json +34 -0
  65. package/runtime/plugins/opinion-manager/catalog/rules/om.response-brief/versions/1.1.0.json +34 -0
  66. package/runtime/plugins/opinion-manager/catalog/rules/om.response-dense/versions/1.1.0.json +34 -0
  67. package/runtime/plugins/opinion-manager/catalog/rules/om.rules-tools/versions/1.1.0.json +34 -0
  68. package/runtime/plugins/opinion-manager/catalog/rules/om.semantic-wrap/versions/1.1.0.json +34 -0
  69. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-proportional/versions/1.1.0.json +34 -0
  70. package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-three-level/versions/1.1.0.json +34 -0
  71. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-compact/versions/1.1.0.json +34 -0
  72. package/runtime/plugins/opinion-manager/catalog/rules/om.tables-list-first/versions/1.1.0.json +34 -0
  73. package/runtime/plugins/opinion-manager/catalog/rules/om.test-evidence/versions/1.1.0.json +34 -0
  74. package/runtime/plugins/opinion-manager/catalog/rules/om.versioned-files/versions/1.1.0.json +34 -0
  75. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/compact-tables/versions/1.1.0.json +32 -0
  76. package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/list-first/versions/1.1.0.json +32 -0
  77. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/chinese-maintenance/versions/1.1.0.json +26 -0
  78. package/runtime/plugins/opinion-manager/catalog/templates/development-standard/project-language/versions/1.1.0.json +26 -0
  79. package/runtime/plugins/opinion-manager/catalog/templates/response-style/brief-chinese/versions/1.1.0.json +30 -0
  80. package/runtime/plugins/opinion-manager/catalog/templates/response-style/dense-chinese/versions/1.1.0.json +30 -0
  81. package/runtime/plugins/opinion-manager/catalog/templates/scenario/concise-project/versions/1.1.0.json +181 -0
  82. package/runtime/plugins/opinion-manager/catalog/templates/scenario/reviewed-project/versions/1.1.0.json +179 -0
  83. package/runtime/plugins/opinion-manager/catalog/templates/work-method/proportional/versions/1.1.0.json +31 -0
  84. package/runtime/plugins/opinion-manager/catalog/templates/work-method/three-level/versions/1.1.0.json +31 -0
  85. package/runtime/plugins/opinion-manager/content.json +44 -3
  86. package/runtime/plugins/opinion-manager/plugin.json +1 -1
  87. package/runtime/plugins/opinion-manager/references/inbox.en.md +25 -4
  88. package/runtime/plugins/opinion-manager/references/inbox.md +25 -4
  89. package/runtime/plugins/opinion-manager/references/profile.schema.json +19 -2
  90. package/runtime/plugins/opinion-manager/references/rule.schema.json +25 -3
  91. package/runtime/plugins/opinion-manager/references/versioned-template.schema.json +5 -4
  92. package/runtime/plugins/opinion-manager/references/versioning.md +89 -4
  93. package/runtime/plugins/opinion-manager/runtime/context.py +26 -19
  94. package/runtime/plugins/opinion-manager/runtime/inbox.py +400 -25
  95. package/runtime/plugins/opinion-manager/runtime/inbox_relations.py +106 -0
  96. package/runtime/plugins/opinion-manager/runtime/inbox_routes.py +132 -0
  97. package/runtime/plugins/opinion-manager/runtime/inbox_text.py +117 -11
  98. package/runtime/plugins/opinion-manager/runtime/lifecycle.py +35 -5
  99. package/runtime/plugins/opinion-manager/runtime/locale/en.json +137 -2
  100. package/runtime/plugins/opinion-manager/runtime/migrate.py +582 -0
  101. package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +9 -4
  102. package/runtime/plugins/opinion-manager/runtime/rule_lines.py +247 -0
  103. package/runtime/plugins/opinion-manager/runtime/tags.py +217 -0
  104. package/runtime/plugins/opinion-manager/runtime/versioned.py +289 -41
  105. package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +8 -7
  106. package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
  107. package/runtime/plugins/project-orchestrator/plugin.json +1 -1
  108. package/runtime/plugins/project-orchestrator/runtime/locale/en.json +305 -3
  109. package/runtime/plugins/project-orchestrator/runtime/private_paths.py +11 -1
  110. package/runtime/plugins/project-orchestrator/runtime/project_cli.py +101 -1
  111. package/runtime/plugins/project-orchestrator/runtime/project_demo.py +13 -1
  112. package/runtime/plugins/project-orchestrator/runtime/project_ext_actions.py +415 -0
  113. package/runtime/plugins/project-orchestrator/runtime/project_extensions.py +971 -0
  114. package/runtime/plugins/project-orchestrator/runtime/project_extensions_demo.py +86 -0
  115. package/runtime/plugins/project-orchestrator/runtime/project_menu.py +345 -2
  116. package/runtime/plugins/project-orchestrator/runtime/project_real.py +17 -1
  117. package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +2 -0
@@ -0,0 +1,247 @@
1
+ """项目文件里的规则行:渲染(采纳写入)与解析(check / 机械关系提示读取 OPINION.md 的自定义规则)。
2
+
3
+ 行的标签随项目文件语言,不随界面语言。解析只认本工具自己的两种渲染格式;认不出的行一律报告为「未结构化」,从不猜测。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Any
10
+
11
+
12
+ # 用户要求全局时必须使用的固定标准值(并带非空 --quote);工具只做形式校验,无法验证是谁提出了全局。
13
+ GLOBAL_VALUES = {"zh": "全部场景,用户要求全局", "en": "All scenarios; the user asked for this to apply globally"}
14
+
15
+
16
+ def is_global(value: str) -> bool:
17
+ return value in GLOBAL_VALUES.values()
18
+
19
+
20
+ def localized_global(value: str, language: str) -> str:
21
+ """写进项目文件时把标准全局值换成项目语言的版本,避免 en 项目里出现中文。"""
22
+ return GLOBAL_VALUES[language] if is_global(value) else value
23
+
24
+
25
+ # 自定义行的标签随项目文件语言(不随界面语言)。没有新字段的候选,zh 渲染与旧版逐字节相同。
26
+ RULE_WORDS = {
27
+ "zh": {"applies": "适用", "trigger": "条件", "purpose": "目的", "exclude": "不适用", "sep": "、", "join": ";", "colon": ":", "open": "(", "close": ")"},
28
+ "en": {"applies": "Applies to", "trigger": "When", "purpose": "Purpose", "exclude": "Not for", "sep": ", ", "join": "; ", "colon": ": ", "open": " (", "close": ")"},
29
+ }
30
+
31
+
32
+ def rule_qualifiers(candidate: dict[str, Any], language: str) -> str:
33
+ """括号内的内容:适用范围,随后是条件 / 目的 / 不适用(有才写)。"""
34
+ words = RULE_WORDS[language]
35
+ parts = [f"{words['applies']}{words['colon']}{words['sep'].join(candidate['scopes'])}"]
36
+ for name in ("trigger", "purpose", "exclude"):
37
+ value = candidate.get(name) or ""
38
+ if value:
39
+ parts.append(f"{words[name]}{words['colon']}{localized_global(value, language) if name == 'trigger' else value}")
40
+ return words["join"].join(parts)
41
+
42
+
43
+ # 路由(opinion 规则指定某类任务使用某个 skill):标记是纯 ASCII,与项目语言无关;自动约束的文字随项目文件语言。
44
+ ROUTE_WHEN = ("before", "after", "instead")
45
+ SKILL_NAME = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$") # Agent Skills 规范:小写字母、数字、连字符
46
+ TAG_NAME = re.compile(r"^[a-z0-9-]{1,32}$")
47
+ MAX_SKILL = 64
48
+ MARKER = re.compile(r"^(?P<head>.*) \[route (?P<body>[^\[\]]*)\]$")
49
+ ROUTE_WORDS = {
50
+ "zh": {
51
+ "exclude": "skill {skill} 自身的执行过程",
52
+ "before": "开始主体工作前先使用 skill {skill}",
53
+ "after": "主体完成后、交付前使用 skill {skill} 处理成果",
54
+ "final": "主体完成后、交付前最后一步使用 skill {skill} 处理成果,其后不再改动该成果的文字",
55
+ "instead": "用 skill {skill} 取代默认做法完成本项工作",
56
+ "suffix": " 路由:{timing};该 skill 执行期间不再触发本规则;该 skill 不可用时告知用户并按目的自行完成。",
57
+ },
58
+ "en": {
59
+ "exclude": "the execution of skill {skill} itself",
60
+ "before": "before starting the main work, use skill {skill}",
61
+ "after": "after the main work and before delivery, use skill {skill} on the result",
62
+ "final": "as the last step before delivery, use skill {skill} on the result; do not change its wording afterwards",
63
+ "instead": "use skill {skill} instead of the default approach for this work",
64
+ "suffix": " Routing: {timing}; this rule does not trigger again while that skill runs; if it is unavailable, tell the user and finish the work yourself per the purpose.",
65
+ },
66
+ }
67
+
68
+
69
+ def route_problem(route: dict[str, Any]) -> str | None:
70
+ """路由对象的形式校验:返回第一个问题的代码(skill / when / final / on),没有问题为 None。"""
71
+ skill = route.get("skill")
72
+ if not isinstance(skill, str) or len(skill) > MAX_SKILL or not SKILL_NAME.match(skill):
73
+ return "skill"
74
+ if route.get("when") not in ROUTE_WHEN:
75
+ return "when"
76
+ if route.get("final") and route["when"] != "after":
77
+ return "final"
78
+ on = route.get("on") or ""
79
+ if on and (not isinstance(on, str) or not TAG_NAME.match(on)):
80
+ return "on"
81
+ return None
82
+
83
+
84
+ def route_marker(route: dict[str, Any]) -> str:
85
+ """行末的机器可读标记,固定键序;final / on 缺省则省略。"""
86
+ parts = [f"skill={route['skill']}", f"when={route['when']}"]
87
+ if route.get("final"):
88
+ parts.append("final=1")
89
+ if route.get("on"):
90
+ parts.append(f"on={route['on']}")
91
+ return "[route " + " ".join(parts) + "]"
92
+
93
+
94
+ def route_exclude(route: dict[str, Any], language: str) -> str:
95
+ return ROUTE_WORDS[language]["exclude"].format(skill=route["skill"])
96
+
97
+
98
+ def route_suffix(route: dict[str, Any], language: str) -> str:
99
+ words = ROUTE_WORDS[language]
100
+ timing = words["final" if route.get("final") else route["when"]].format(skill=route["skill"])
101
+ return words["suffix"].format(timing=timing)
102
+
103
+
104
+ def parse_marker(line: str) -> tuple[dict[str, Any] | None, str | None]:
105
+ """行末标记 -> (路由, 错误)。没有标记为 (None, None);标记损坏为 (None, 原因)。只认固定的四个键。"""
106
+ matched = MARKER.match(line.rstrip())
107
+ if not matched:
108
+ return None, ("marker_damaged" if re.search(r"\[route\b", line) else None)
109
+ route: dict[str, Any] = {"final": False, "on": ""}
110
+ seen: set[str] = set()
111
+ for token in matched["body"].split(" "):
112
+ key, found, value = token.partition("=")
113
+ if not found or key not in ("skill", "when", "final", "on") or key in seen or not value:
114
+ return None, "marker_damaged"
115
+ seen.add(key)
116
+ if key == "final":
117
+ if value != "1":
118
+ return None, "marker_damaged"
119
+ route["final"] = True
120
+ else:
121
+ route[key] = value
122
+ if not {"skill", "when"} <= seen or route_problem(route):
123
+ return None, "marker_damaged"
124
+ return route, None
125
+
126
+
127
+ # 标签(自定义规则按标签按需加载):行末的纯 ASCII 标记 ` [tags a b]`,标签按字母序、不重复;与项目语言无关。
128
+ # 同时有路由时顺序固定为 `[route …] [tags …]`。没有标记的行与手写行永远常驻。
129
+ TAGS_MARKER = re.compile(r"^(?P<head>.*) \[tags (?P<body>[^\[\]]*)\]$")
130
+ MAX_TAG = 32
131
+
132
+
133
+ def tags_marker(tags: list[str]) -> str:
134
+ return "[tags " + " ".join(sorted(set(tags))) + "]"
135
+
136
+
137
+ def tag_problem(tags: Any) -> str | None:
138
+ """标签列表的形式校验:返回第一个问题的代码(empty / form),没有问题为 None。"""
139
+ if not isinstance(tags, list) or not tags:
140
+ return "empty"
141
+ if len(tags) != len(set(tags)) or any(not isinstance(tag, str) or len(tag) > MAX_TAG or not SKILL_NAME.match(tag) for tag in tags):
142
+ return "form"
143
+ return None
144
+
145
+
146
+ def split_tags(line: str) -> tuple[list[str] | None, str | None, str]:
147
+ """行末标签标记 -> (标签, 错误, 去掉标记后的行)。没有标记为 (None, None, 原行);标记损坏为 (None, 原因, 原行)。"""
148
+ matched = TAGS_MARKER.match(line.rstrip())
149
+ if not matched:
150
+ return None, ("marker_damaged" if re.search(r"\[tags\b", line) else None), line
151
+ tags = matched["body"].split(" ")
152
+ if tag_problem(tags):
153
+ return None, "marker_damaged", line
154
+ return tags, None, matched["head"]
155
+
156
+
157
+ def candidate_rule(candidate: dict[str, Any], language: str = "zh") -> str:
158
+ line = _candidate_rule(candidate, language)
159
+ return f"{line} {tags_marker(candidate['tags'])}" if candidate.get("tags") else line
160
+
161
+
162
+ def _candidate_rule(candidate: dict[str, Any], language: str = "zh") -> str:
163
+ words = RULE_WORDS[language]
164
+ route = candidate.get("route")
165
+ if not route:
166
+ return f"- **{candidate['title']}**{words['open']}{rule_qualifiers(candidate, language)}{words['close']}{words['colon']}{candidate['text']}"
167
+ # 路由行:不适用里自动追加「skill 自身的执行过程」,正文后追加时机句、不再触发与降级条款,行末带标记
168
+ user_exclude = candidate.get("exclude") or ""
169
+ exclude = words["sep"].join(part for part in (user_exclude, route_exclude(route, language)) if part)
170
+ shown = {**candidate, "exclude": exclude}
171
+ return (f"- **{candidate['title']}**{words['open']}{rule_qualifiers(shown, language)}{words['close']}{words['colon']}"
172
+ f"{candidate['text']}{route_suffix(route, language)} {route_marker(route)}")
173
+
174
+
175
+ CUSTOM_HEADINGS = ("## 用户自定义规则", "## User-defined rules")
176
+ LINE_PATTERNS = {
177
+ "zh": re.compile(r"^- \*\*(?P<title>.+?)\*\*((?P<qual>.*?)):(?P<text>.*)$"),
178
+ "en": re.compile(r"^- \*\*(?P<title>.+?)\*\* \((?P<qual>.*?)\): (?P<text>.*)$"),
179
+ }
180
+
181
+
182
+ def custom_section_lines(content: str) -> list[tuple[int, str]]:
183
+ """OPINION.md 自定义规则小节里的非空行及其行号(从 1 起);没有该小节时为空。"""
184
+ lines = content.splitlines()
185
+ for start, line in enumerate(lines):
186
+ if line.strip() in CUSTOM_HEADINGS:
187
+ found = []
188
+ for number in range(start + 1, len(lines)):
189
+ if lines[number].startswith("## "):
190
+ break
191
+ if lines[number].strip():
192
+ found.append((number + 1, lines[number]))
193
+ return found
194
+ return []
195
+
196
+
197
+ def parse_line(line: str) -> dict[str, Any] | None:
198
+ """按两种渲染格式解析一行;不是本工具渲染的格式返回 None(调用方标「未结构化」)。
199
+ 行末的标签标记先剥离;没有标记的行结果与旧版逐字节相同(不含 tags 键)。"""
200
+ tags, problem, body = split_tags(line)
201
+ parsed = _parse_line(body)
202
+ if parsed is not None:
203
+ if tags:
204
+ parsed["tags"] = tags
205
+ elif problem:
206
+ parsed["tags_error"] = problem
207
+ return parsed
208
+
209
+
210
+ def _parse_line(line: str) -> dict[str, Any] | None:
211
+ for language, pattern in LINE_PATTERNS.items():
212
+ matched = pattern.match(line)
213
+ if not matched:
214
+ continue
215
+ words = RULE_WORDS[language]
216
+ colon = words["colon"].strip()
217
+ labels = {words[name]: name for name in ("applies", "trigger", "purpose", "exclude")}
218
+ # 只在后面紧跟「已知标签 + 冒号」处切分,值里自带的分号不会被切开
219
+ marker = re.compile("%s(?=(?:%s)%s)" % (re.escape(words["join"]), "|".join(re.escape(label) for label in labels if label != words["applies"]), re.escape(colon)))
220
+ values: dict[str, str] = {}
221
+ for part in marker.split(matched["qual"]):
222
+ label, found, value = part.partition(colon)
223
+ name = labels.get(label.strip())
224
+ if not found or name is None or name in values or not value.strip():
225
+ values = {}
226
+ break
227
+ values[name] = value.strip()
228
+ if "applies" in values:
229
+ separator = words["sep"].strip()
230
+ parsed = {"format": language, "title": matched["title"], "scopes": [item.strip() for item in values["applies"].split(separator) if item.strip()],
231
+ "trigger": values.get("trigger", ""), "purpose": values.get("purpose", ""), "exclude": values.get("exclude", ""), "text": matched["text"]}
232
+ route, problem = parse_marker(matched["text"])
233
+ if route:
234
+ parsed["route"] = route
235
+ # 按同一渲染规则反向剥离自动追加的部分,往返还原用户写的正文与不适用
236
+ tail = route_suffix(route, language) + f" {route_marker(route)}"
237
+ if parsed["text"].endswith(tail):
238
+ parsed["text"] = parsed["text"][:-len(tail)]
239
+ automatic = route_exclude(route, language)
240
+ if parsed["exclude"] == automatic:
241
+ parsed["exclude"] = ""
242
+ elif parsed["exclude"].endswith(words["sep"] + automatic):
243
+ parsed["exclude"] = parsed["exclude"][:-len(words["sep"] + automatic)]
244
+ elif problem:
245
+ parsed["route_error"] = problem
246
+ return parsed
247
+ return None
@@ -0,0 +1,217 @@
1
+ """schema 2.2 的标签选择引擎:按 Profile 的标签声明只读切分 OPINION.md 的规则,不写任何文件。
2
+
3
+ 标签是多对多的成员关系:一条规则可属于多个标签;规则组就是具名的标签集合。选择语义:
4
+ 多个 --tag 取并集并去重;常驻规则(loading.always,以及没有任何标签的规则)只由 core 输出;常驻与按需冲突时归常驻。
5
+ 用户 custom 段里带 ``[tags …]`` 标记且标签全部有效的行按标签按需加载,其余行(没有标记、认不出)永远常驻。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ from typing import Any
12
+
13
+ import rule_lines
14
+ import versioned
15
+ from i18n_opinion import _ # noqa: E402
16
+
17
+
18
+ EXIT_OK, EXIT_MISSING = 0, 1
19
+ SIGNAL_KEY = "touches"
20
+ NONE = "none"
21
+
22
+
23
+ def is_tag_profile(profile: dict[str, Any]) -> bool:
24
+ return isinstance(profile.get("loading"), dict) and "tags" in profile["loading"]
25
+
26
+
27
+ def split_custom(profile: dict[str, Any]) -> tuple[list[tuple[str, tuple[str, ...]]], int]:
28
+ """custom 段逐行归类:返回 [(行, 标签元组)] 与「标记存在但无效、因此保持常驻」的行数。标签元组为空表示常驻。"""
29
+ known = {tag["id"] for tag in profile["loading"]["tags"]}
30
+ lines: list[tuple[str, tuple[str, ...]]] = []
31
+ rejected = 0
32
+ for line in (profile["custom"] or "").split("\n"):
33
+ parsed = rule_lines.parse_line(line) if line.strip() else None
34
+ tags = tuple((parsed or {}).get("tags") or ())
35
+ if tags and not set(tags) <= known:
36
+ tags, rejected = (), rejected + 1
37
+ elif parsed and parsed.get("tags_error"):
38
+ rejected += 1
39
+ lines.append((line, tags))
40
+ return lines, rejected
41
+
42
+
43
+ def plan(profile: dict[str, Any]) -> dict[str, Any]:
44
+ """每条有效规则恰好归一处:常驻,或按需(属于至少一个标签且不在 always 里)。"""
45
+ loading = profile["loading"]
46
+ rules = versioned.effective_rules(profile)
47
+ always = set(loading["always"])
48
+ members = loading["members"]
49
+ on_demand = {identity: members[identity] for identity in rules if identity in members and identity not in always}
50
+ resident = [identity for identity in rules if identity not in on_demand]
51
+ lines, rejected = split_custom(profile)
52
+ tags: dict[str, dict[str, Any]] = {}
53
+ for tag in loading["tags"]:
54
+ name = tag["id"]
55
+ tagged = [identity for identity in rules if name in members.get(identity, ())]
56
+ own = [identity for identity in on_demand if name in on_demand[identity]]
57
+ custom = [line for line, owners in lines if name in owners]
58
+ tags[name] = {"tag": tag, "rules": own, "custom": custom,
59
+ "all_members": tagged, "state": ("ready" if own or custom else ("resident" if tagged else "empty"))}
60
+ return {"rules": rules, "resident": resident, "tags": tags, "lines": lines, "rejected": rejected}
61
+
62
+
63
+ def selectable(parts: dict[str, Any]) -> list[str]:
64
+ return [name for name, item in parts["tags"].items() if item["state"] == "ready"]
65
+
66
+
67
+ def resident_custom(parts: dict[str, Any]) -> str:
68
+ """去掉按需行后的 custom 段;连续空行折叠为一行。"""
69
+ kept: list[str] = []
70
+ for line, owners in parts["lines"]:
71
+ if owners or (not line.strip() and (not kept or not kept[-1].strip())):
72
+ continue
73
+ kept.append(line)
74
+ return "\n".join(kept).strip()
75
+
76
+
77
+ def listing(names: list[str]) -> str:
78
+ return _("、").join(names) if names else "-"
79
+
80
+
81
+ def custom_block(text: str, language: str) -> list[str]:
82
+ return ["", versioned.FRAME[language]["custom"], "", text] if text else []
83
+
84
+
85
+ def tag_index_line(profile: dict[str, Any], parts: dict[str, Any], name: str, language: str) -> str:
86
+ item = parts["tags"][name]
87
+ tag = item["tag"]
88
+ return _("- `{0}`({1},{2} 条):{3}。不适用:{4}。").format(
89
+ name, versioned.pick(tag["name"], language)[0], len(item["rules"]) + len(item["custom"]),
90
+ versioned.pick(tag["trigger"], language)[0], versioned.pick(tag["exclude"], language)[0])
91
+
92
+
93
+ def core_text(profile: dict[str, Any], lock: dict[str, Any] | None, language: str = "zh", *, index: bool = True) -> str:
94
+ parts = plan(profile)
95
+ origin = _("正文指纹:`{0}`").format(lock["opinion_sha256"]) if lock else _("候选 Profile 预览,尚未生效")
96
+ lines = [_("# Agent Opinion 核心规则"), "",
97
+ _("Profile:`{0}@{1}`;{2}。").format(profile["id"], profile["version"], origin),
98
+ _("本输出是完整正文的只读切片,始终适用。按需规则见文末标签索引,命中时再读取。")]
99
+ for identity in parts["resident"]:
100
+ lines.extend(("", versioned.render_rule(profile, parts["rules"][identity], language)))
101
+ lines.extend(custom_block(resident_custom(parts), language))
102
+ if index:
103
+ lines.extend(("", _("## 标签索引"), "", _("任务命中标签的触发条件时用 `context select --tag <标签>` 读取对应规则;可重复 --tag,取并集;判断不清时一并读取。")))
104
+ lines.extend(tag_index_line(profile, parts, name, language) for name in selectable(parts))
105
+ return "\n".join(lines).rstrip() + "\n"
106
+
107
+
108
+ def check_selection(parts: dict[str, Any], names: list[str]) -> list[str]:
109
+ """校验 --tag:未知、core、常驻、空集都给出明确错误;通过则返回去重后的标签(保持输入顺序)。"""
110
+ valid = selectable(parts)
111
+ if not names:
112
+ versioned.fail(_("select 需要至少一个 --tag;有效标签:{0}").format(listing(valid)))
113
+ chosen: list[str] = []
114
+ for name in names:
115
+ if name == "core":
116
+ versioned.fail(_("core 是常驻集合,由 context core 输出,不能作为 --tag 选择"))
117
+ if name not in parts["tags"]:
118
+ versioned.fail(_("未知标签:{0};有效标签:{1}").format(name, listing(valid)))
119
+ state = parts["tags"][name]["state"]
120
+ if state == "resident":
121
+ versioned.fail(_("标签 {0} 的规则全部常驻,已随 context core 输出,无需选择").format(name))
122
+ if state == "empty":
123
+ versioned.fail(_("标签 {0} 当前没有有效规则(成员规则已停用)").format(name))
124
+ if name not in chosen:
125
+ chosen.append(name)
126
+ return chosen
127
+
128
+
129
+ def select_text(profile: dict[str, Any], names: list[str], language: str = "zh") -> str:
130
+ parts = plan(profile)
131
+ chosen = check_selection(parts, names)
132
+ # 并集:按 OPINION.md 里的顺序输出每条规则一次,常驻规则不在其中
133
+ wanted = {identity for name in chosen for identity in parts["tags"][name]["rules"]}
134
+ picked = [identity for identity in parts["rules"] if identity in wanted]
135
+ custom = [line for line, owners in parts["lines"] if set(owners) & set(chosen)]
136
+ lines = [_("# 按需规则:{0}").format(listing([f"`{name}`" for name in chosen]))]
137
+ for identity in picked:
138
+ lines.extend(("", versioned.render_rule(profile, parts["rules"][identity], language)))
139
+ lines.extend(custom_block("\n".join(custom), language))
140
+ return "\n".join(lines).rstrip() + "\n"
141
+
142
+
143
+ def index_view(profile: dict[str, Any], lock: dict[str, Any] | None, language: str = "zh") -> dict[str, Any]:
144
+ parts = plan(profile)
145
+ entries = []
146
+ for name, item in parts["tags"].items():
147
+ ready = item["state"] == "ready"
148
+ entries.append({
149
+ "id": name, "name": versioned.pick(item["tag"]["name"], language)[0], "state": item["state"],
150
+ "rules": len(item["rules"]), "rule_ids": list(item["rules"]), "custom_lines": len(item["custom"]),
151
+ "trigger": versioned.pick(item["tag"]["trigger"], language)[0], "exclude": versioned.pick(item["tag"]["exclude"], language)[0],
152
+ "bytes": len(select_text(profile, [name], language).encode("utf-8")) if ready else 0,
153
+ "index_bytes": len((tag_index_line(profile, parts, name, language) + "\n").encode("utf-8")) if ready else 0})
154
+ return {
155
+ "ok": True, "mode": "tags", "profile": f"{profile['id']}@{profile['version']}", "profile_sha256": versioned.digest(profile),
156
+ "opinion_sha256": lock["opinion_sha256"] if lock else None,
157
+ "resident": {"rules": list(parts["resident"]), "custom_lines": sum(1 for line, owners in parts["lines"] if line.strip() and not owners)},
158
+ "tags": entries, "on_demand_tags": len(selectable(parts)), "rejected_custom_lines": parts["rejected"],
159
+ "resident_bytes": len(core_text(profile, lock, language, index=False).encode("utf-8")),
160
+ "core_bytes": len(core_text(profile, lock, language).encode("utf-8")),
161
+ "complete_bytes": len(versioned.render(profile, language).encode("utf-8")),
162
+ }
163
+
164
+
165
+ def declared(profile: dict[str, Any], signals: list[str], tags: list[str]) -> list[str]:
166
+ """--signal touches=<标签> 与 --tag 等价;返回去重后的标签,none 单独出现表示本次不涉及任何按需标签。"""
167
+ parts = plan(profile)
168
+ names = list(tags)
169
+ for item in signals:
170
+ key, _sep, value = item.partition("=")
171
+ if key != SIGNAL_KEY or not value:
172
+ versioned.fail(_("未声明的交付信号:{0}").format(item))
173
+ names.append(value)
174
+ if not names:
175
+ versioned.fail(_("check 至少需要一个 --tag 或 --signal"))
176
+ if NONE in names:
177
+ if len(set(names)) > 1:
178
+ versioned.fail(_("none 表示不涉及按需标签,不能与其他标签同时声明"))
179
+ return []
180
+ return check_selection(parts, names)
181
+
182
+
183
+ def check(profile: dict[str, Any], signals: list[str], tags: list[str], loaded: list[str]) -> dict[str, Any]:
184
+ """由标签派生信号:声明涉及的标签 -> 应读取的规则;已读取的标签并集 -> 已读规则;缺失为退出码 1。"""
185
+ parts = plan(profile)
186
+ names = declared(profile, signals, tags)
187
+ have = check_selection(parts, loaded) if loaded else []
188
+ wanted = [identity for identity in parts["rules"] if any(identity in parts["tags"][name]["rules"] for name in names)]
189
+ read = {identity for name in have for identity in parts["tags"][name]["rules"]}
190
+ required_lines = [line for line, owners in parts["lines"] if set(owners) & set(names)]
191
+ read_lines = {line for line, owners in parts["lines"] if set(owners) & set(have)}
192
+ missing_rules = [identity for identity in wanted if identity not in read]
193
+ missing_tags = [name for name in names
194
+ if any(identity in missing_rules for identity in parts["tags"][name]["rules"])
195
+ or any(line not in read_lines for line in parts["tags"][name]["custom"])]
196
+ return {"ok": not missing_tags, "signals": {SIGNAL_KEY: sorted(names)}, "required": names, "required_rules": wanted,
197
+ "loaded": have, "missing": missing_tags, "missing_rules": missing_rules,
198
+ "next": [f"context select {' '.join('--tag ' + name for name in missing_tags)}"] if missing_tags else [],
199
+ "custom_lines_required": len(required_lines)}
200
+
201
+
202
+ def execute(args: argparse.Namespace, profile: dict[str, Any], lock: dict[str, Any] | None, language: str) -> tuple[int, str]:
203
+ parts = plan(profile)
204
+ if args.action != "select" and args.action != "check" and args.tag:
205
+ versioned.fail(_("--tag 只用于 select 与 check"))
206
+ if args.action == "core":
207
+ return EXIT_OK, core_text(profile, lock, language)
208
+ if args.action == "index":
209
+ return EXIT_OK, versioned.pretty(index_view(profile, lock, language))
210
+ if args.action == "bundle":
211
+ versioned.fail(_("该 Profile 使用标签选择(schema 2.2),请用 context select --tag <标签>;有效标签:{0}").format(listing(selectable(parts))))
212
+ if args.action == "select":
213
+ if args.names:
214
+ versioned.fail(_("select 只接受 --tag,不接受位置参数:{0}").format(" ".join(args.names)))
215
+ return EXIT_OK, select_text(profile, args.tag, language)
216
+ result = check(profile, args.signal, args.tag, args.loaded)
217
+ return (EXIT_OK if result["ok"] else EXIT_MISSING), versioned.pretty(result)