@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.
- 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/plugin.json +1 -1
- package/runtime/plugins/agent-pack/references/capability-config.md +10 -0
- package/runtime/plugins/agent-pack/references/check-opinion-migrate.en.md +31 -0
- package/runtime/plugins/agent-pack/references/check-opinion-migrate.md +31 -0
- package/runtime/plugins/agent-pack/references/dedupe-contract.en.md +27 -0
- package/runtime/plugins/agent-pack/references/dedupe-contract.md +27 -0
- package/runtime/plugins/agent-pack/references/inventory-contract.en.md +83 -0
- package/runtime/plugins/agent-pack/references/inventory-contract.md +83 -0
- package/runtime/plugins/agent-pack/references/nudge.en.md +10 -2
- package/runtime/plugins/agent-pack/references/nudge.md +10 -2
- package/runtime/plugins/agent-pack/references/relocate-contract.en.md +41 -0
- package/runtime/plugins/agent-pack/references/relocate-contract.md +41 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_claude.py +572 -30
- package/runtime/plugins/agent-pack/runtime/agent_pack_clients.py +233 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_config.py +112 -4
- package/runtime/plugins/agent-pack/runtime/agent_pack_dedupe.py +502 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_desktop.py +92 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_ext_common.py +251 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_inventory.py +989 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_mcp_write.py +447 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_nudge.py +29 -4
- package/runtime/plugins/agent-pack/runtime/agent_pack_relocate.py +385 -0
- package/runtime/plugins/agent-pack/runtime/agent_pack_scope.py +233 -0
- package/runtime/plugins/agent-pack/runtime/agenthelm.py +183 -14
- package/runtime/plugins/agent-pack/runtime/locale/en.json +250 -1
- package/runtime/plugins/agent-pack/runtime/mcp_server.py +12 -0
- package/runtime/plugins/agent-pack/runtime/nudge_text.py +8 -2
- package/runtime/plugins/agent-pack/runtime/user_settings.py +2 -1
- package/runtime/plugins/agent-pack/skills/agent-pack/SKILL.md +15 -0
- package/runtime/plugins/agents-init/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/agents-init/content.json +4 -2
- package/runtime/plugins/agents-init/plugin.json +1 -1
- package/runtime/plugins/agents-init/skills/agents-init/SKILL.md +2 -0
- package/runtime/plugins/agents-init/skills/agents-init/launcher.en.sh +93 -0
- package/runtime/plugins/agents-init/skills/agents-init/project.schema.json +27 -0
- package/runtime/plugins/agents-init/skills/agents-init/scripts/baseline.py +4 -1
- package/runtime/plugins/agents-init/skills/agents-init/scripts/init_project.py +24 -9
- 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/catalog/README.md +3 -1
- package/runtime/plugins/opinion-manager/catalog/rules/om.align-requirements/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.assumptions-authority/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.batch-questions/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.bilingual-terms/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.calculations/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.chinese-response/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.clean-deliverable/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.complete-options/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.conclusion-first/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.concrete-titles/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.consistent-items/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.device-readable/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.editable-diagrams/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.evidence-inference/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-chinese/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.maintenance-project-language/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.markdown-structure/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.portable-files/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.report-context/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.report-formats/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.report-review/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.response-brief/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.response-dense/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.rules-tools/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.semantic-wrap/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-proportional/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.solutions-three-level/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.tables-compact/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.tables-list-first/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.test-evidence/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/rules/om.versioned-files/versions/1.1.0.json +34 -0
- package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/compact-tables/versions/1.1.0.json +32 -0
- package/runtime/plugins/opinion-manager/catalog/templates/delivery-standard/list-first/versions/1.1.0.json +32 -0
- package/runtime/plugins/opinion-manager/catalog/templates/development-standard/chinese-maintenance/versions/1.1.0.json +26 -0
- package/runtime/plugins/opinion-manager/catalog/templates/development-standard/project-language/versions/1.1.0.json +26 -0
- package/runtime/plugins/opinion-manager/catalog/templates/response-style/brief-chinese/versions/1.1.0.json +30 -0
- package/runtime/plugins/opinion-manager/catalog/templates/response-style/dense-chinese/versions/1.1.0.json +30 -0
- package/runtime/plugins/opinion-manager/catalog/templates/scenario/concise-project/versions/1.1.0.json +181 -0
- package/runtime/plugins/opinion-manager/catalog/templates/scenario/reviewed-project/versions/1.1.0.json +179 -0
- package/runtime/plugins/opinion-manager/catalog/templates/work-method/proportional/versions/1.1.0.json +31 -0
- package/runtime/plugins/opinion-manager/catalog/templates/work-method/three-level/versions/1.1.0.json +31 -0
- package/runtime/plugins/opinion-manager/content.json +44 -3
- package/runtime/plugins/opinion-manager/plugin.json +1 -1
- package/runtime/plugins/opinion-manager/references/inbox.en.md +25 -4
- package/runtime/plugins/opinion-manager/references/inbox.md +25 -4
- package/runtime/plugins/opinion-manager/references/profile.schema.json +19 -2
- package/runtime/plugins/opinion-manager/references/rule.schema.json +25 -3
- package/runtime/plugins/opinion-manager/references/versioned-template.schema.json +5 -4
- package/runtime/plugins/opinion-manager/references/versioning.md +89 -4
- package/runtime/plugins/opinion-manager/runtime/context.py +26 -19
- package/runtime/plugins/opinion-manager/runtime/inbox.py +400 -25
- package/runtime/plugins/opinion-manager/runtime/inbox_relations.py +106 -0
- package/runtime/plugins/opinion-manager/runtime/inbox_routes.py +132 -0
- package/runtime/plugins/opinion-manager/runtime/inbox_text.py +117 -11
- package/runtime/plugins/opinion-manager/runtime/lifecycle.py +35 -5
- package/runtime/plugins/opinion-manager/runtime/locale/en.json +137 -2
- package/runtime/plugins/opinion-manager/runtime/migrate.py +582 -0
- package/runtime/plugins/opinion-manager/runtime/opinion_manager.py +9 -4
- package/runtime/plugins/opinion-manager/runtime/rule_lines.py +247 -0
- package/runtime/plugins/opinion-manager/runtime/tags.py +217 -0
- package/runtime/plugins/opinion-manager/runtime/versioned.py +289 -41
- package/runtime/plugins/opinion-manager/skills/opinion-manager/SKILL.md +8 -7
- package/runtime/plugins/project-orchestrator/.codex-plugin/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/plugin.json +1 -1
- package/runtime/plugins/project-orchestrator/runtime/locale/en.json +305 -3
- package/runtime/plugins/project-orchestrator/runtime/private_paths.py +11 -1
- package/runtime/plugins/project-orchestrator/runtime/project_cli.py +101 -1
- package/runtime/plugins/project-orchestrator/runtime/project_demo.py +13 -1
- package/runtime/plugins/project-orchestrator/runtime/project_ext_actions.py +415 -0
- package/runtime/plugins/project-orchestrator/runtime/project_extensions.py +971 -0
- package/runtime/plugins/project-orchestrator/runtime/project_extensions_demo.py +86 -0
- package/runtime/plugins/project-orchestrator/runtime/project_menu.py +345 -2
- package/runtime/plugins/project-orchestrator/runtime/project_real.py +17 -1
- package/runtime/plugins/project-orchestrator/skills/project-orchestrator/SKILL.md +2 -0
|
@@ -19,20 +19,33 @@ import shlex
|
|
|
19
19
|
import subprocess
|
|
20
20
|
import tempfile
|
|
21
21
|
from argparse import Namespace
|
|
22
|
-
from datetime import UTC, datetime
|
|
22
|
+
from datetime import UTC, datetime, timedelta
|
|
23
23
|
from pathlib import Path
|
|
24
24
|
from typing import Any
|
|
25
25
|
|
|
26
26
|
import inbox_text as words
|
|
27
|
+
import inbox_relations
|
|
28
|
+
import inbox_routes
|
|
27
29
|
import versioned
|
|
30
|
+
from rule_lines import (GLOBAL_VALUES, RULE_WORDS, candidate_rule, custom_section_lines, is_global, # noqa: F401
|
|
31
|
+
localized_global, parse_line, route_problem, rule_qualifiers)
|
|
28
32
|
|
|
29
33
|
|
|
30
34
|
STORE = Path(".opinion") / "inbox.json"
|
|
35
|
+
ASK_STATE = Path(".opinion") / "ask-state.json"
|
|
36
|
+
MAX_ASK_SESSIONS = 50
|
|
31
37
|
STATUSES = ("pending", "trial", "formal", "held", "rejected")
|
|
32
38
|
DECIDABLE = ("pending", "trial", "formal", "held", "rejected")
|
|
33
39
|
OPEN_STATUSES = ("pending", "trial")
|
|
34
40
|
EMPTY = {"schema_version": 1, "candidates": {}}
|
|
35
|
-
MAX_TITLE, MAX_TEXT, MAX_QUOTE = 120, 1200, 600
|
|
41
|
+
MAX_TITLE, MAX_TEXT, MAX_QUOTE, MAX_FIELD = 120, 1200, 600, 300
|
|
42
|
+
# 本版软必填:缺 trigger / purpose 时 add 仍成功并返回 warnings。置 True 即变为严格拒绝(留给之后的 major)。
|
|
43
|
+
STRICT_REQUIRED = False
|
|
44
|
+
REQUIRED_FIELDS = ("trigger", "purpose")
|
|
45
|
+
OPTIONAL_FIELDS = ("exclude", "relation")
|
|
46
|
+
FIELDS = REQUIRED_FIELDS + OPTIONAL_FIELDS
|
|
47
|
+
# 占位词:传入这些值等于没填,一律拒绝(比较前去掉空白与标点并转小写)。
|
|
48
|
+
PLACEHOLDERS = frozenset({"所有", "全部", "相关", "一切", "任何", "无", "tbd", "any", "all", "everything", "relevant", "anything", "na", "none"})
|
|
36
49
|
RUNTIME = Path(__file__).resolve().with_name("opinion_manager.py")
|
|
37
50
|
|
|
38
51
|
LANGUAGE = words.DEFAULT_LANGUAGE
|
|
@@ -116,7 +129,10 @@ def load(root: Path) -> dict[str, Any]:
|
|
|
116
129
|
|
|
117
130
|
|
|
118
131
|
def save(root: Path, data: dict[str, Any]) -> None:
|
|
119
|
-
|
|
132
|
+
write_json(store_path(root), data)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def write_json(path: Path, data: dict[str, Any]) -> None:
|
|
120
136
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
121
137
|
descriptor, temporary = tempfile.mkstemp(prefix=".inbox-", dir=path.parent)
|
|
122
138
|
try:
|
|
@@ -159,6 +175,74 @@ def clean(value: str | None, label: str, limit: int, *, required: bool = True) -
|
|
|
159
175
|
return text
|
|
160
176
|
|
|
161
177
|
|
|
178
|
+
def field_value(value: str | None, name: str, limit: int = MAX_FIELD) -> str:
|
|
179
|
+
"""可选字段:未传入返回空串;传入了就必须有内容且不是占位词(relation 只要求非空)。"""
|
|
180
|
+
if value is None:
|
|
181
|
+
return ""
|
|
182
|
+
text = clean(value, f"label_{name}", limit)
|
|
183
|
+
if name != "relation" and re.sub(r"[\W_]+", "", text.lower()) in PLACEHOLDERS:
|
|
184
|
+
fail("err_placeholder", label=say(f"label_{name}"), value=text)
|
|
185
|
+
return text
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def missing_fields(candidate: dict[str, Any]) -> list[str]:
|
|
189
|
+
return [name for name in REQUIRED_FIELDS if not candidate.get(name)]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def route_from_args(args: argparse.Namespace, existing: dict[str, Any] | None = None) -> dict[str, Any] | None:
|
|
193
|
+
"""--route-* 参数 -> 路由对象;没有任何 --route-* 参数返回 None(不改变)。revise 时在已有路由上合并。"""
|
|
194
|
+
skill, when, on = (getattr(args, name, None) for name in ("route_skill", "route_when", "route_on"))
|
|
195
|
+
final = bool(getattr(args, "route_final", False))
|
|
196
|
+
if skill is None and when is None and on is None and not final:
|
|
197
|
+
return None
|
|
198
|
+
route = {"when": "before", "final": False, "on": "", **(existing or {})}
|
|
199
|
+
if skill is None and not existing:
|
|
200
|
+
fail("err_route_need_skill")
|
|
201
|
+
if skill is not None:
|
|
202
|
+
route["skill"] = skill.strip()
|
|
203
|
+
if on is not None:
|
|
204
|
+
route["on"] = on.strip()
|
|
205
|
+
if when is not None:
|
|
206
|
+
route["when"] = when
|
|
207
|
+
if when != "after" and not final:
|
|
208
|
+
route["final"] = False
|
|
209
|
+
if final:
|
|
210
|
+
route["final"] = True
|
|
211
|
+
if when is None:
|
|
212
|
+
route["when"] = "after"
|
|
213
|
+
problem = route_problem(route)
|
|
214
|
+
if problem:
|
|
215
|
+
fail(f"err_route_{problem}", value=route.get(problem) or "")
|
|
216
|
+
return {key: route[key] for key in ("skill", "when", "final", "on")}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def tag_vocabulary(root: Path) -> list[str] | None:
|
|
220
|
+
"""项目当前生效 Profile 的标签词表;没有锁或没有标签声明为 None。"""
|
|
221
|
+
path = root / "opinion.lock.json"
|
|
222
|
+
if not versioned.safe_path(path).is_file():
|
|
223
|
+
return None
|
|
224
|
+
loading = versioned.read_object(path).get("profile", {}).get("loading")
|
|
225
|
+
return [tag["id"] for tag in loading["tags"]] if isinstance(loading, dict) and isinstance(loading.get("tags"), list) else None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def check_tags(root: Path, tags: list[str]) -> list[str]:
|
|
229
|
+
"""候选标签对照词表:规范为排序去重的列表;没有词表或含未知标签都报错并列出有效标签。"""
|
|
230
|
+
vocabulary = tag_vocabulary(root)
|
|
231
|
+
if vocabulary is None:
|
|
232
|
+
fail("err_tag_none")
|
|
233
|
+
unknown = [tag for tag in tags if tag not in vocabulary]
|
|
234
|
+
if unknown:
|
|
235
|
+
fail("err_tag_unknown", value=say("sep").join(unknown), valid=say("sep").join(vocabulary))
|
|
236
|
+
return sorted(set(tags))
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def route_warnings(candidate: dict[str, Any], root: Path) -> list[str]:
|
|
240
|
+
if not candidate.get("route"):
|
|
241
|
+
return []
|
|
242
|
+
size = inbox_routes.line_bytes(candidate_rule(candidate, versioned.project_language(root)))
|
|
243
|
+
return [say("warn_route_long", bytes=size, limit=inbox_routes.MAX_LINE_BYTES)] if size > inbox_routes.MAX_LINE_BYTES else []
|
|
244
|
+
|
|
245
|
+
|
|
162
246
|
def next_identity(data: dict[str, Any], moment: datetime) -> str:
|
|
163
247
|
prefix = f"cand-{moment:%Y%m%d}-"
|
|
164
248
|
used = [int(key[len(prefix):]) for key in data["candidates"] if key.startswith(prefix) and key[len(prefix):].isdigit()]
|
|
@@ -172,6 +256,17 @@ def add(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
172
256
|
scopes = [clean(item, "label_scope", MAX_TITLE) for item in args.scope]
|
|
173
257
|
if not scopes:
|
|
174
258
|
fail("err_scope")
|
|
259
|
+
extras = {name: field_value(getattr(args, name, None), name) for name in FIELDS}
|
|
260
|
+
route = route_from_args(args)
|
|
261
|
+
if route:
|
|
262
|
+
extras["route"] = route
|
|
263
|
+
if getattr(args, "tag", None):
|
|
264
|
+
extras["tags"] = check_tags(root, args.tag)
|
|
265
|
+
if is_global(extras["trigger"]) and not quote:
|
|
266
|
+
fail("err_global_quote")
|
|
267
|
+
absent = [name for name in REQUIRED_FIELDS if not extras[name]]
|
|
268
|
+
if absent and STRICT_REQUIRED:
|
|
269
|
+
fail("err_missing_fields", fields=say("sep").join(say(f"label_{name}") for name in absent))
|
|
175
270
|
moment = now()
|
|
176
271
|
first = not store_path(root).exists()
|
|
177
272
|
with Locked(root) as data:
|
|
@@ -186,13 +281,15 @@ def add(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
186
281
|
identity = next_identity(data, moment)
|
|
187
282
|
data["candidates"][identity] = {
|
|
188
283
|
"id": identity, "title": title, "text": text, "scopes": scopes, "quotes": [quote] if quote else [],
|
|
189
|
-
"status": "pending", "digest": digest, "client": args.client or "", "session": args.session or "",
|
|
284
|
+
**extras, "status": "pending", "digest": digest, "client": args.client or "", "session": args.session or "",
|
|
190
285
|
"created_at": stamp(moment), "updated_at": stamp(moment), "last_action_at": stamp(moment),
|
|
191
286
|
"trial_since": None, "presented": 0, "presented_at": None,
|
|
192
287
|
"history": [{"at": stamp(moment), "to": "pending", "note": "captured"}],
|
|
193
288
|
}
|
|
194
289
|
save(root, data)
|
|
195
|
-
result = {"ok": True, "status": "added", "id": identity, "state": "pending", "writes_stable_rules": False
|
|
290
|
+
result = {"ok": True, "status": "added", "id": identity, "state": "pending", "writes_stable_rules": False,
|
|
291
|
+
"complete": not absent, "warnings": [say("warn_missing_fields", fields=say("sep").join(say(f"label_{name}") for name in absent))] if absent else []}
|
|
292
|
+
result["warnings"] += route_warnings({**extras, "title": title, "text": text, "scopes": scopes}, root)
|
|
196
293
|
if first:
|
|
197
294
|
notice = exposure(root)
|
|
198
295
|
if notice["needs_notice"]:
|
|
@@ -200,6 +297,105 @@ def add(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
200
297
|
return result
|
|
201
298
|
|
|
202
299
|
|
|
300
|
+
def revise(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
301
|
+
"""修订候选内容。pending 且从未展示(presented==0)时是 Agent 自己的暂存修正,无需确认;其他状态必须 --confirmed。
|
|
302
|
+
旧值写进 history,摘要重算,与其他候选撞摘要时报错;状态不变。"""
|
|
303
|
+
if len(args.ids) != 1:
|
|
304
|
+
fail("err_revise_one")
|
|
305
|
+
changes: dict[str, Any] = {}
|
|
306
|
+
if args.title is not None:
|
|
307
|
+
changes["title"] = clean(args.title, "label_title", MAX_TITLE)
|
|
308
|
+
if args.text is not None:
|
|
309
|
+
changes["text"] = clean(args.text, "label_text", MAX_TEXT)
|
|
310
|
+
if args.scope:
|
|
311
|
+
changes["scopes"] = [clean(item, "label_scope", MAX_TITLE) for item in args.scope]
|
|
312
|
+
for name in FIELDS:
|
|
313
|
+
if getattr(args, name, None) is not None:
|
|
314
|
+
changes[name] = field_value(getattr(args, name), name)
|
|
315
|
+
if getattr(args, "tag", None) and getattr(args, "tag_clear", False):
|
|
316
|
+
fail("err_tag_clear_exclusive")
|
|
317
|
+
if getattr(args, "tag", None):
|
|
318
|
+
changes["tags"] = check_tags(root, args.tag)
|
|
319
|
+
elif getattr(args, "tag_clear", False):
|
|
320
|
+
changes["tags"] = []
|
|
321
|
+
quote = clean(args.quote, "label_quote", MAX_QUOTE, required=False)
|
|
322
|
+
clearing = bool(getattr(args, "route_clear", False))
|
|
323
|
+
routing = any(getattr(args, name, None) is not None for name in ("route_skill", "route_when", "route_on")) or bool(getattr(args, "route_final", False))
|
|
324
|
+
if clearing and routing:
|
|
325
|
+
fail("err_route_clear_exclusive")
|
|
326
|
+
routing = routing or clearing
|
|
327
|
+
if not changes and not quote and not routing:
|
|
328
|
+
fail("err_revise_nothing")
|
|
329
|
+
moment = now()
|
|
330
|
+
with Locked(root) as data:
|
|
331
|
+
candidate = data["candidates"].get(args.ids[0])
|
|
332
|
+
if candidate is None:
|
|
333
|
+
fail("err_missing", id=args.ids[0])
|
|
334
|
+
if not (candidate["status"] == "pending" and not candidate["presented"]) and not args.confirmed:
|
|
335
|
+
fail("err_revise_confirm", status=candidate["status"])
|
|
336
|
+
if routing:
|
|
337
|
+
changes["route"] = None if clearing else route_from_args(args, candidate.get("route"))
|
|
338
|
+
blank = lambda name: [] if name in ("scopes", "tags") else (None if name == "route" else "") # noqa: E731
|
|
339
|
+
previous = {name: candidate.get(name, blank(name)) for name, value in changes.items()
|
|
340
|
+
if candidate.get(name, blank(name)) != value}
|
|
341
|
+
quotes = list(candidate["quotes"]) + ([quote] if quote and quote not in candidate["quotes"] else [])
|
|
342
|
+
if quotes != candidate["quotes"]:
|
|
343
|
+
previous["quotes"] = list(candidate["quotes"])
|
|
344
|
+
if not previous:
|
|
345
|
+
return {"ok": True, "status": "unchanged", "id": candidate["id"], "changed": [], "candidate": view(candidate), "warnings": []}
|
|
346
|
+
merged = {**candidate, **{name: value for name, value in changes.items() if name in previous}, "quotes": quotes}
|
|
347
|
+
digest = normalized(merged["title"], merged["text"])
|
|
348
|
+
for other in data["candidates"].values():
|
|
349
|
+
if other["id"] != candidate["id"] and other["digest"] == digest:
|
|
350
|
+
fail("err_revise_collision", id=other["id"])
|
|
351
|
+
if is_global(merged.get("trigger") or "") and not quotes:
|
|
352
|
+
fail("err_global_quote")
|
|
353
|
+
if STRICT_REQUIRED and missing_fields(merged):
|
|
354
|
+
fail("err_missing_fields", fields=say("sep").join(say(f"label_{name}") for name in missing_fields(merged)))
|
|
355
|
+
candidate.update({name: merged[name] for name in previous if name != "quotes"})
|
|
356
|
+
candidate["quotes"], candidate["digest"] = quotes, digest
|
|
357
|
+
candidate["updated_at"] = stamp(moment)
|
|
358
|
+
if args.confirmed:
|
|
359
|
+
candidate["last_action_at"] = stamp(moment)
|
|
360
|
+
candidate["history"].append({"at": stamp(moment), "to": candidate["status"], "note": "revised", "previous": previous})
|
|
361
|
+
save(root, data)
|
|
362
|
+
shown = with_relations(candidate, inbox_relations.targets(root, data))
|
|
363
|
+
warnings = route_warnings(candidate, root)
|
|
364
|
+
if candidate["status"] == "formal":
|
|
365
|
+
warnings.append(say("warn_revise_formal"))
|
|
366
|
+
if missing_fields(candidate):
|
|
367
|
+
warnings.append(say("warn_missing_fields", fields=say("sep").join(say(f"label_{name}") for name in missing_fields(candidate))))
|
|
368
|
+
return {"ok": True, "status": "written", "id": candidate["id"], "changed": sorted(previous), "candidate": shown,
|
|
369
|
+
"writes_stable_rules": False, "warnings": warnings}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def check(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
373
|
+
"""只读:列出缺条件 / 目的的候选(pending、trial)与 OPINION.md 自定义行;认不出格式的行标「未结构化」。不写任何文件。"""
|
|
374
|
+
data = load(root)
|
|
375
|
+
candidates = [{"id": item["id"], "title": item["title"], "status": item["status"], "text": item["text"], "scopes": item["scopes"],
|
|
376
|
+
"trigger": item.get("trigger") or "", "purpose": item.get("purpose") or "",
|
|
377
|
+
"missing": missing_fields(item), "revise_command": revise_command(root, item["id"])}
|
|
378
|
+
for item in select(data, list(OPEN_STATUSES)) if missing_fields(item)]
|
|
379
|
+
lines = []
|
|
380
|
+
path = root / "OPINION.md"
|
|
381
|
+
content = versioned.read_text(path) if path.exists() else ""
|
|
382
|
+
for number, line in custom_section_lines(content):
|
|
383
|
+
parsed = parse_line(line)
|
|
384
|
+
if parsed is None:
|
|
385
|
+
lines.append({"line": number, "format": "unstructured", "title": "", "missing": [], "text": inbox_relations.snippet(line)})
|
|
386
|
+
elif missing_fields(parsed):
|
|
387
|
+
lines.append({"line": number, "format": parsed["format"], "title": parsed["title"], "missing": missing_fields(parsed),
|
|
388
|
+
"text": inbox_relations.snippet(parsed["text"])})
|
|
389
|
+
return {"ok": True, "status": "read-only", "candidates": candidates, "custom_lines": lines,
|
|
390
|
+
"summary": {"candidates_incomplete": len(candidates), "custom_lines_incomplete": sum(1 for item in lines if item["format"] != "unstructured"),
|
|
391
|
+
"custom_lines_unstructured": sum(1 for item in lines if item["format"] == "unstructured")},
|
|
392
|
+
"next_step": say("check_next") if candidates or lines else say("check_clean"), "writes_stable_rules": False}
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def revise_command(root: Path, identity: str) -> str:
|
|
396
|
+
return f"python3 {shlex.quote(str(RUNTIME))} inbox revise {shlex.quote(identity)} --project {shlex.quote(str(root))} --trigger \"<…>\" --purpose \"<…>\" --lang {LANGUAGE}"
|
|
397
|
+
|
|
398
|
+
|
|
203
399
|
def decide(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
204
400
|
if not args.confirmed:
|
|
205
401
|
fail("err_confirm")
|
|
@@ -223,7 +419,7 @@ def decide(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
223
419
|
changed.append(identity)
|
|
224
420
|
save(root, data)
|
|
225
421
|
result = {"ok": True, "status": "written", "changed": changed, "to": args.to, "reminder": "",
|
|
226
|
-
"writes_stable_rules": False}
|
|
422
|
+
"writes_stable_rules": False, "candidates": [view(data["candidates"][identity]) for identity in args.ids]}
|
|
227
423
|
if args.to == "formal":
|
|
228
424
|
result["reminder"] = say("formal_reminder")
|
|
229
425
|
result["in_opinion"] = False
|
|
@@ -239,8 +435,16 @@ def adopt_command(root: Path, ids: list[str], confirm: str | None = None) -> str
|
|
|
239
435
|
DEFAULT_PROFILE = "private.my-opinion"
|
|
240
436
|
|
|
241
437
|
|
|
242
|
-
def
|
|
243
|
-
|
|
438
|
+
def fingerprint_input(item: dict[str, Any]) -> list[Any]:
|
|
439
|
+
"""采纳指纹里每条候选的输入;没有新字段的旧记录与旧版指纹一致。"""
|
|
440
|
+
base = [item["title"], item["text"], item["scopes"]]
|
|
441
|
+
extras = [item.get(name) or "" for name in ("trigger", "purpose", "exclude")]
|
|
442
|
+
tail = [item["route"]] if item.get("route") else []
|
|
443
|
+
if item.get("tags"):
|
|
444
|
+
tail.append({"tags": sorted(item["tags"])})
|
|
445
|
+
if tail:
|
|
446
|
+
return [item["id"], versioned.digest(base + extras + tail)]
|
|
447
|
+
return [item["id"], versioned.digest(base + extras if any(extras) else base)]
|
|
244
448
|
|
|
245
449
|
|
|
246
450
|
def raw(path: Path) -> bytes | None:
|
|
@@ -280,7 +484,11 @@ def adopt_plan(root: Path, items: list[dict[str, Any]], workdir: Path) -> dict[s
|
|
|
280
484
|
lock_path = root / "opinion.lock.json"
|
|
281
485
|
current_lock = versioned.file_state(lock_path)
|
|
282
486
|
previous = versioned.validate_lock(json.loads(current_lock))["profile"] if current_lock is not None else None
|
|
283
|
-
|
|
487
|
+
language = versioned.project_language(root)
|
|
488
|
+
for item in items:
|
|
489
|
+
if item.get("tags"):
|
|
490
|
+
check_tags(root, item["tags"])
|
|
491
|
+
custom = "\n\n".join(part for part in ((previous or {}).get("custom"), "\n".join(candidate_rule(item, language) for item in items)) if part)
|
|
284
492
|
custom_file = workdir / "custom.md"
|
|
285
493
|
custom_file.write_text(custom + "\n", encoding="utf-8")
|
|
286
494
|
identity, release = (previous["id"], previous["version"]) if previous else (DEFAULT_PROFILE, "0.0.0")
|
|
@@ -297,7 +505,7 @@ def adopt_plan(root: Path, items: list[dict[str, Any]], workdir: Path) -> dict[s
|
|
|
297
505
|
from_profile.write_text(versioned.pretty(previous), encoding="utf-8")
|
|
298
506
|
profile_args = Namespace(project=root, id=identity, version=number, template=[], rule=[], remove_template=[], remove_rule=[],
|
|
299
507
|
custom_file=custom_file, from_profile=from_profile, overrides_file=None, resolutions_file=None,
|
|
300
|
-
loading_file=None, remove_loading=False, catalog=versioned.PUBLIC_CATALOG, apply=False, confirm=None)
|
|
508
|
+
loading_file=None, remove_loading=False, no_tags=False, catalog=versioned.PUBLIC_CATALOG, apply=False, confirm=None)
|
|
301
509
|
drafted = versioned.profile_command(profile_args)
|
|
302
510
|
if drafted["unresolved"]:
|
|
303
511
|
fail("err_adopt_unresolved", ids=say("sep").join(drafted["unresolved"]))
|
|
@@ -306,10 +514,10 @@ def adopt_plan(root: Path, items: list[dict[str, Any]], workdir: Path) -> dict[s
|
|
|
306
514
|
compose_args = Namespace(project=root, profile=preview_file, template=[], rule=[], custom_file=None, replace=False,
|
|
307
515
|
accept_current=None, apply=False, confirm=None)
|
|
308
516
|
composed = versioned.compose_command(compose_args)
|
|
309
|
-
fingerprint = versioned.digest({"candidates": [
|
|
517
|
+
fingerprint = versioned.digest({"candidates": [fingerprint_input(item) for item in items],
|
|
310
518
|
"profile": drafted["confirmation_sha256"], "compose": composed["confirmation_sha256"]})
|
|
311
519
|
return {"profile_args": profile_args, "compose_args": compose_args, "drafted": drafted, "composed": composed,
|
|
312
|
-
"fingerprint": fingerprint, "target": target, "profile_id": f"{identity}@{number}", "preview_file": preview_file}
|
|
520
|
+
"fingerprint": fingerprint, "items": items, "target": target, "profile_id": f"{identity}@{number}", "preview_file": preview_file}
|
|
313
521
|
|
|
314
522
|
|
|
315
523
|
def adopt(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
@@ -318,9 +526,17 @@ def adopt(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
318
526
|
with tempfile.TemporaryDirectory(prefix="opinion-adopt-") as workdir:
|
|
319
527
|
plan = adopt_plan(root, adoptable(load(root), ids), Path(workdir))
|
|
320
528
|
composed = plan["composed"]
|
|
529
|
+
language = versioned.project_language(root)
|
|
530
|
+
conflicts = plan["drafted"].get("changes", {}).get("conflicts", [])
|
|
531
|
+
matches = [shown_match(item, language) for item in plan["items"]]
|
|
321
532
|
return {"ok": True, "status": "preview", "ids": ids, "profile": plan["profile_id"], "profile_path": str(plan["target"]),
|
|
322
533
|
"path": composed["path"], "content": composed["content"], "blocked": composed["blocked"],
|
|
323
534
|
"confirmation_sha256": plan["fingerprint"], "writes_stable_rules": False,
|
|
535
|
+
"candidates": [view(item) for item in plan["items"]],
|
|
536
|
+
"added_lines": [candidate_rule(item, language) for item in plan["items"]],
|
|
537
|
+
"shown": {item["id"]: match for item, match in zip(plan["items"], matches)},
|
|
538
|
+
"shown_matches": bool(matches) and all(matches) and not composed["blocked"] and not conflicts,
|
|
539
|
+
**{key: composed[key] for key in ("untranslated", "warnings") if key in composed},
|
|
324
540
|
"next_step": say("adopt_next", command=adopt_command(root, ids, plan["fingerprint"]))}
|
|
325
541
|
if not args.confirm:
|
|
326
542
|
fail("err_adopt_confirm")
|
|
@@ -368,7 +584,22 @@ def adopt(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
368
584
|
"verified": verified, "writes_stable_rules": True, "message": say("adopt_done", count=len(ids))}
|
|
369
585
|
|
|
370
586
|
|
|
587
|
+
def line_digest(candidate: dict[str, Any], language: str) -> str:
|
|
588
|
+
return versioned.text_digest(candidate_rule(candidate, language))
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def shown_snapshot(candidate: dict[str, Any], language: str, moment: datetime) -> dict[str, str]:
|
|
592
|
+
"""展示快照:此刻候选将被渲染成的规则行的摘要。之后候选或项目语言变化,摘要就对不上。"""
|
|
593
|
+
return {"at": stamp(moment), "language": language, "line_sha256": line_digest(candidate, language)}
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def shown_match(candidate: dict[str, Any], language: str) -> bool:
|
|
597
|
+
snapshot = candidate.get("shown")
|
|
598
|
+
return isinstance(snapshot, dict) and snapshot.get("line_sha256") == line_digest(candidate, language)
|
|
599
|
+
|
|
600
|
+
|
|
371
601
|
def present(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
602
|
+
language = versioned.project_language(root)
|
|
372
603
|
moment = now()
|
|
373
604
|
marked = []
|
|
374
605
|
with Locked(root) as data:
|
|
@@ -377,9 +608,62 @@ def present(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
377
608
|
if candidate is not None:
|
|
378
609
|
candidate["presented"] += 1
|
|
379
610
|
candidate["presented_at"] = stamp(moment)
|
|
611
|
+
candidate["shown"] = shown_snapshot(candidate, language, moment)
|
|
380
612
|
marked.append(identity)
|
|
381
613
|
save(root, data)
|
|
382
|
-
|
|
614
|
+
pool = inbox_relations.targets(root, data) if marked else []
|
|
615
|
+
return {"ok": True, "status": "written", "marked": marked, "candidates": [with_relations(data["candidates"][identity], pool) for identity in marked]}
|
|
616
|
+
|
|
617
|
+
|
|
618
|
+
def gate(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
619
|
+
"""询问节流(只记账,不决定要不要问):同项目 cooldown 小时内最多放行一次,同会话最多 max-per-session 次。
|
|
620
|
+
状态在 .opinion/ask-state.json;--peek 只读。放行且没有 --peek 时才记一次。"""
|
|
621
|
+
cooldown, limit = args.cooldown_hours, args.max_per_session
|
|
622
|
+
if cooldown < 0:
|
|
623
|
+
fail("err_cooldown")
|
|
624
|
+
if limit < 1:
|
|
625
|
+
fail("err_max_per_session")
|
|
626
|
+
for item in (root / ".opinion", root / ASK_STATE):
|
|
627
|
+
if item.is_symlink():
|
|
628
|
+
fail("err_symlink", path=item)
|
|
629
|
+
moment = now()
|
|
630
|
+
guard_dir = root / ".opinion"
|
|
631
|
+
if not args.peek:
|
|
632
|
+
guard_dir.mkdir(parents=True, exist_ok=True)
|
|
633
|
+
guard = (guard_dir / ".ask.lock").open("a") if guard_dir.is_dir() else None
|
|
634
|
+
try:
|
|
635
|
+
if guard:
|
|
636
|
+
fcntl.flock(guard, fcntl.LOCK_EX)
|
|
637
|
+
path = root / ASK_STATE
|
|
638
|
+
state = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {"schema_version": 1, "last_allowed_at": None, "sessions": {}}
|
|
639
|
+
if not isinstance(state, dict) or not isinstance(state.get("sessions"), dict):
|
|
640
|
+
fail("err_format", path=path)
|
|
641
|
+
last = state.get("last_allowed_at")
|
|
642
|
+
count = int((state["sessions"].get(args.session) or {}).get("count", 0)) if args.session else 0
|
|
643
|
+
elapsed = (moment - parse_stamp(last)).total_seconds() / 3600 if last else None
|
|
644
|
+
reason = "ok"
|
|
645
|
+
if args.session and count >= limit:
|
|
646
|
+
reason = "session_limit"
|
|
647
|
+
elif elapsed is not None and elapsed < cooldown:
|
|
648
|
+
reason = "cooldown"
|
|
649
|
+
allowed = reason == "ok"
|
|
650
|
+
recorded = allowed and not args.peek
|
|
651
|
+
if recorded:
|
|
652
|
+
state["last_allowed_at"] = stamp(moment)
|
|
653
|
+
if args.session:
|
|
654
|
+
state["sessions"][args.session] = {"count": count + 1, "last_at": stamp(moment)}
|
|
655
|
+
recent = sorted(state["sessions"].items(), key=lambda pair: pair[1].get("last_at", ""))[-MAX_ASK_SESSIONS:]
|
|
656
|
+
state["sessions"] = dict(recent)
|
|
657
|
+
write_json(path, state)
|
|
658
|
+
finally:
|
|
659
|
+
if guard:
|
|
660
|
+
fcntl.flock(guard, fcntl.LOCK_UN)
|
|
661
|
+
guard.close()
|
|
662
|
+
next_allowed = stamp(parse_stamp(last) + timedelta(hours=cooldown)) if reason == "cooldown" else None
|
|
663
|
+
return {"ok": True, "status": "written" if recorded else "read-only", "allowed": allowed, "reason": reason, "peek": bool(args.peek),
|
|
664
|
+
"recorded": recorded, "cooldown_hours": cooldown, "max_per_session": limit, "session": args.session or "",
|
|
665
|
+
"session_count": count + (1 if recorded and args.session else 0), "last_allowed_at": state.get("last_allowed_at"),
|
|
666
|
+
"next_allowed_at": next_allowed, "message": say(f"gate_{reason}")}
|
|
383
667
|
|
|
384
668
|
|
|
385
669
|
def expire(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
@@ -404,7 +688,15 @@ def expire(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
404
688
|
def view(candidate: dict[str, Any]) -> dict[str, Any]:
|
|
405
689
|
keys = ("id", "title", "text", "scopes", "quotes", "status", "created_at", "updated_at", "last_action_at",
|
|
406
690
|
"trial_since", "presented", "presented_at", "session", "client")
|
|
407
|
-
|
|
691
|
+
shown = {key: candidate[key] for key in keys}
|
|
692
|
+
shown.update({name: candidate.get(name) or "" for name in FIELDS})
|
|
693
|
+
shown["complete"] = not missing_fields(candidate)
|
|
694
|
+
shown["global"] = is_global(candidate.get("trigger") or "")
|
|
695
|
+
if candidate.get("route"):
|
|
696
|
+
shown["route"] = candidate["route"]
|
|
697
|
+
if candidate.get("tags"):
|
|
698
|
+
shown["tags"] = candidate["tags"]
|
|
699
|
+
return shown
|
|
408
700
|
|
|
409
701
|
|
|
410
702
|
def select(data: dict[str, Any], statuses: list[str] | None, session: str | None = None,
|
|
@@ -417,12 +709,53 @@ def select(data: dict[str, Any], statuses: list[str] | None, session: str | None
|
|
|
417
709
|
return sorted(items, key=lambda item: (item["created_at"], item["id"]))
|
|
418
710
|
|
|
419
711
|
|
|
712
|
+
def field_lines(item: dict[str, Any]) -> list[str]:
|
|
713
|
+
"""列表里的条件 / 目的 / 不适用 / 关系备注;缺必填项时标「不完整」,全局声明标「全局(请用户确认)」。"""
|
|
714
|
+
lines = []
|
|
715
|
+
for name in FIELDS:
|
|
716
|
+
value = item.get(name) or ""
|
|
717
|
+
if value:
|
|
718
|
+
mark = say("global_mark") if name == "trigger" and is_global(value) else ""
|
|
719
|
+
lines.append(say(f"list_{name}", value=value, mark=mark))
|
|
720
|
+
if item.get("route"):
|
|
721
|
+
lines.append(say("list_route", value=inbox_routes.route_text(item["route"], say)))
|
|
722
|
+
if item.get("tags"):
|
|
723
|
+
lines.append(say("list_tags", value=say("sep").join(item["tags"])))
|
|
724
|
+
missing = missing_fields(item)
|
|
725
|
+
if missing:
|
|
726
|
+
lines.append(say("list_incomplete", fields=say("sep").join(say(f"label_{name}") for name in missing)))
|
|
727
|
+
return lines
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def with_relations(item: dict[str, Any], pool: list[dict[str, str]]) -> dict[str, Any]:
|
|
731
|
+
shown = view(item)
|
|
732
|
+
shown["relations"] = [{**entry, "note": say("relations_note")} for entry in inbox_relations.relations_for(item, pool)]
|
|
733
|
+
return shown
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def relation_lines(relations: list[dict[str, Any]]) -> list[str]:
|
|
737
|
+
return [say("list_relations", kind=say(f"kind_{entry['kind']}"), ref=entry["with"]["ref"], evidence=entry["evidence"]) for entry in relations]
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
def brief_qualifiers(item: dict[str, Any]) -> str:
|
|
741
|
+
"""试行条目括号内的适用范围,后接条件 / 目的 / 不适用;跟随界面语言。"""
|
|
742
|
+
parts = [say("sep").join(item["scopes"])]
|
|
743
|
+
for name in ("trigger", "purpose", "exclude"):
|
|
744
|
+
if item.get(name):
|
|
745
|
+
parts.append(say(f"brief_{name}", value=item[name]))
|
|
746
|
+
if item.get("route"):
|
|
747
|
+
parts.append(say("brief_route", value=inbox_routes.route_text(item["route"], say)))
|
|
748
|
+
return say("brief_join").join(parts)
|
|
749
|
+
|
|
750
|
+
|
|
420
751
|
def listing(root: Path, args: argparse.Namespace) -> dict[str, Any] | str:
|
|
421
752
|
statuses = args.status.split(",") if args.status else None
|
|
422
753
|
for item in statuses or []:
|
|
423
754
|
if item not in STATUSES:
|
|
424
755
|
fail("err_status", status=item)
|
|
425
|
-
|
|
756
|
+
data = load(root)
|
|
757
|
+
items = select(data, statuses, args.session, args.unpresented)
|
|
758
|
+
pool = inbox_relations.targets(root, data) if items else []
|
|
426
759
|
if args.output == "markdown":
|
|
427
760
|
if not items:
|
|
428
761
|
return say("list_empty") + "\n"
|
|
@@ -431,10 +764,12 @@ def listing(root: Path, args: argparse.Namespace) -> dict[str, Any] | str:
|
|
|
431
764
|
lines.append(f"{number}. **{item['title']}** ({item['id']} · {item['status']})")
|
|
432
765
|
lines.append(say("list_rule", text=item["text"]))
|
|
433
766
|
lines.append(say("list_scope", scopes=say("sep").join(item["scopes"])))
|
|
767
|
+
lines.extend(field_lines(item))
|
|
768
|
+
lines.extend(relation_lines(inbox_relations.relations_for(item, pool)))
|
|
434
769
|
if item["quotes"]:
|
|
435
770
|
lines.append(say("list_quote", quote=item["quotes"][-1]))
|
|
436
771
|
return "\n".join(lines) + "\n"
|
|
437
|
-
return {"ok": True, "status": "read-only", "value": [
|
|
772
|
+
return {"ok": True, "status": "read-only", "value": [with_relations(item, pool) for item in items]}
|
|
438
773
|
|
|
439
774
|
|
|
440
775
|
def pending(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
@@ -447,7 +782,9 @@ def pending(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
447
782
|
command = f"python3 {shlex.quote(str(RUNTIME))} inbox list --project {shlex.quote(str(root))} --status pending,trial --output markdown"
|
|
448
783
|
items = [{"id": item["id"], "source": "opinion", "kind": "candidate", "title": item["title"],
|
|
449
784
|
"status": item["status"], "created_at": item["created_at"], "last_action_at": item["last_action_at"],
|
|
450
|
-
"age_days": round(days_since(item["last_action_at"], moment), 1), "hint_command": command
|
|
785
|
+
"age_days": round(days_since(item["last_action_at"], moment), 1), "hint_command": command,
|
|
786
|
+
**{name: item.get(name) or "" for name in FIELDS}, "complete": not missing_fields(item),
|
|
787
|
+
**({"route": item["route"]} if item.get("route") else {})}
|
|
451
788
|
for item in open_items]
|
|
452
789
|
session_items = select(data, ["pending"], args.session, True) if args.session else []
|
|
453
790
|
last_actions = [item["last_action_at"] for item in data["candidates"].values()]
|
|
@@ -460,8 +797,15 @@ def pending(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
460
797
|
def brief(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
461
798
|
data = load(root)
|
|
462
799
|
trial = select(data, ["trial"])
|
|
463
|
-
|
|
464
|
-
|
|
800
|
+
mode = getattr(args, "mode", None) or "ask"
|
|
801
|
+
cooldown = getattr(args, "cooldown_hours", 24)
|
|
802
|
+
limit = getattr(args, "max_per_session", 1)
|
|
803
|
+
if cooldown < 0:
|
|
804
|
+
fail("err_cooldown")
|
|
805
|
+
if limit < 1:
|
|
806
|
+
fail("err_max_per_session")
|
|
807
|
+
protocol = words.protocol(LANGUAGE, runtime=RUNTIME, project=root, lang=LANGUAGE, session=args.session or "",
|
|
808
|
+
mode=mode, cooldown=cooldown, limit=limit)
|
|
465
809
|
lines = [protocol]
|
|
466
810
|
used = len(protocol)
|
|
467
811
|
shown = []
|
|
@@ -469,7 +813,7 @@ def brief(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
469
813
|
lines.append(say("brief_trial_header"))
|
|
470
814
|
for item in trial:
|
|
471
815
|
entry = say("brief_trial_entry", id=item["id"], title=item["title"], text=item["text"],
|
|
472
|
-
scopes=
|
|
816
|
+
scopes=brief_qualifiers(item))
|
|
473
817
|
if used + len(entry) > args.max_chars:
|
|
474
818
|
lines.append(say("brief_trial_more", count=len(trial) - len(shown)))
|
|
475
819
|
break
|
|
@@ -478,20 +822,39 @@ def brief(root: Path, args: argparse.Namespace) -> dict[str, Any]:
|
|
|
478
822
|
shown.append(item["id"])
|
|
479
823
|
waiting = len(select(data, ["pending"]))
|
|
480
824
|
if waiting:
|
|
481
|
-
lines.append(say("brief_pending", count=waiting))
|
|
825
|
+
lines.append(say("brief_pending" if mode == "ask" else "brief_pending_quiet", count=waiting))
|
|
482
826
|
return {"ok": True, "status": "read-only", "text": "\n".join(lines), "trial_shown": shown,
|
|
483
|
-
"pending": waiting, "trial": len(trial)}
|
|
827
|
+
"pending": waiting, "trial": len(trial), "mode": mode}
|
|
828
|
+
|
|
829
|
+
|
|
830
|
+
def routes(root: Path, args: argparse.Namespace) -> dict[str, Any] | str:
|
|
831
|
+
"""只读:路由规则清单与机械检查(inbox routes list)。"""
|
|
832
|
+
if args.ids not in ([], ["list"]):
|
|
833
|
+
fail("err_routes_action")
|
|
834
|
+
result = inbox_routes.listing(root, load(root), versioned.project_language(root), say)
|
|
835
|
+
return inbox_routes.markdown(result, say) if args.output == "markdown" else result
|
|
484
836
|
|
|
485
837
|
|
|
486
838
|
def add_command(subparsers: Any) -> None:
|
|
487
839
|
parser = subparsers.add_parser("inbox", help="Project-private candidate inbox: stash, decide and summarize pending items; only adopt --apply writes OPINION.md, through the full preview and fingerprint")
|
|
488
|
-
parser.add_argument("action", choices=("add", "list", "decide", "adopt", "present", "expire", "pending", "brief", "exposure"))
|
|
840
|
+
parser.add_argument("action", choices=("add", "list", "decide", "adopt", "present", "expire", "pending", "brief", "exposure", "check", "revise", "gate", "routes"))
|
|
489
841
|
parser.add_argument("ids", nargs="*", help="candidate ids for decide / adopt / present")
|
|
490
842
|
parser.add_argument("--project", type=Path, required=True)
|
|
491
843
|
parser.add_argument("--title")
|
|
492
844
|
parser.add_argument("--text")
|
|
493
845
|
parser.add_argument("--scope", action="append", default=[])
|
|
494
|
-
parser.add_argument("--quote", help="the user's own words, kept as evidence for the candidate")
|
|
846
|
+
parser.add_argument("--quote", help="the user's own words, kept as evidence for the candidate (revise: appended)")
|
|
847
|
+
parser.add_argument("--trigger", help="add: when the rule applies (required in spirit: omitting it only warns; placeholders such as 'all' are rejected)")
|
|
848
|
+
parser.add_argument("--purpose", help="add: why the rule exists (omitting it only warns)")
|
|
849
|
+
parser.add_argument("--exclude", help="add: when the rule does not apply")
|
|
850
|
+
parser.add_argument("--relation", help="add: the agent's own note on how this relates to existing rules; stored and shown verbatim, never interpreted")
|
|
851
|
+
parser.add_argument("--route-skill", help="add / revise: route this rule to a skill by name (lowercase letters, digits, hyphens; at most 64 characters)")
|
|
852
|
+
parser.add_argument("--route-when", choices=("before", "after", "instead"), help="add / revise: when to use the routed skill (default before)")
|
|
853
|
+
parser.add_argument("--route-final", action="store_true", help="add / revise: the routed skill is the last step before delivery (implies --route-when after)")
|
|
854
|
+
parser.add_argument("--route-on", help="add / revise: a short tag (lowercase letters, digits, hyphens) for mechanical comparison between routes")
|
|
855
|
+
parser.add_argument("--route-clear", action="store_true", help="revise: remove the whole route (cannot be combined with the other --route-* options)")
|
|
856
|
+
parser.add_argument("--tag", action="append", default=[], help="add / revise: load this rule on demand under a tag of the project's closed tag vocabulary (repeatable; revise replaces the whole set)")
|
|
857
|
+
parser.add_argument("--tag-clear", action="store_true", help="revise: remove all tags (the rule becomes always loaded; cannot be combined with --tag)")
|
|
495
858
|
parser.add_argument("--client", help="source client: claude / codex / cursor")
|
|
496
859
|
parser.add_argument("--session", help="source session id; lets the end-of-task confirmation cover only this session's candidates")
|
|
497
860
|
parser.add_argument("--status", help="list: comma-separated status filter")
|
|
@@ -502,7 +865,11 @@ def add_command(subparsers: Any) -> None:
|
|
|
502
865
|
parser.add_argument("--apply", action="store_true", help="adopt: write OPINION.md and the lock (needs --confirm); without it adopt only previews")
|
|
503
866
|
parser.add_argument("--confirm", help="adopt: the confirmation_sha256 of the preview the user has reviewed")
|
|
504
867
|
parser.add_argument("--days", type=int, help="expire: revert trials older than this many days to pending")
|
|
868
|
+
parser.add_argument("--cooldown-hours", type=float, default=24, help="gate / brief: allow at most one ask per project within this many hours (default 24)")
|
|
869
|
+
parser.add_argument("--max-per-session", type=int, default=1, help="gate / brief: allow at most this many asks per session (default 1)")
|
|
870
|
+
parser.add_argument("--peek", action="store_true", help="gate: only report whether an ask would be allowed; record nothing")
|
|
505
871
|
parser.add_argument("--max-chars", type=int, default=6000, help="brief: size limit of the text")
|
|
872
|
+
parser.add_argument("--mode", choices=("ask", "digest", "quiet"), default="ask", help="brief: how the protocol asks for confirmation (ask: once per cooldown and session, digest: one closing sentence, quiet: only the session-start summary)")
|
|
506
873
|
parser.add_argument("--output", choices=("json", "markdown"), default="json")
|
|
507
874
|
parser.add_argument("--lang", choices=("auto", *words.LANGUAGES), help="message language: zh / en; by default AGENTHELM_LANG, then the system locale, then English")
|
|
508
875
|
|
|
@@ -523,10 +890,18 @@ def run(args: argparse.Namespace) -> dict[str, Any] | str:
|
|
|
523
890
|
return brief(root, args)
|
|
524
891
|
if args.action == "exposure":
|
|
525
892
|
return exposure(root)
|
|
526
|
-
if args.action
|
|
893
|
+
if args.action == "check":
|
|
894
|
+
return check(root, args)
|
|
895
|
+
if args.action == "gate":
|
|
896
|
+
return gate(root, args)
|
|
897
|
+
if args.action == "routes":
|
|
898
|
+
return routes(root, args)
|
|
899
|
+
if args.action in ("decide", "adopt", "present", "revise") and not args.ids:
|
|
527
900
|
fail("err_ids")
|
|
528
901
|
if args.action == "adopt":
|
|
529
902
|
return adopt(root, args)
|
|
903
|
+
if args.action == "revise":
|
|
904
|
+
return revise(root, args)
|
|
530
905
|
if args.action == "decide":
|
|
531
906
|
if not args.to:
|
|
532
907
|
fail("err_need_to")
|