sync update from LAN repo (source dhk-1 @ 3e87be55)

This commit is contained in:
gozeros committed 2026-10-21 15:06:08 +08:00
1 parent ab6068a7c1
commit 42f2a26fa8
1482 files changed
+227759 -9584

No files matched your search

@@ -20,12 +20,23 @@
不要改写、不要摘抄成 14 类结构。文件内容就是 `{"query":"…","results":[…]}`(或检索工具返回的等价 JSON)。禁止把检索结果只留在对话里不落盘——转换脚本读不到对话。
同时用 `write_file` 把隐藏上下文或开场信息中的任务数据写到固定文件
`/mnt/user-data/workspace/task-context.json`,内容严格是 JSON 数据:
```json
{"taskId":"真实任务id","taskName":"真实任务名称","taskContent":"真实任务内容"}
```
任务名称/内容只能进入这个 JSON 文件,禁止把它们拼进 shell 命令;引号、反引号、
`$()` 等字符必须保持为普通 JSON 数据。
### 3. 函数转换(一条命令,禁止模型手写 task-reports.json)
hits 落盘后,**直接执行下面这条命令**(命令与参数已在此写全,**不需要先 `read_file` SKILL.md**)。任务 id / 名称 / 内容取开场信息或隐藏上下文:
hits 与任务上下文落盘后,**直接执行下面这条固定命令**(命令与参数已写全,
**不需要先 `read_file` SKILL.md**):
```bash
python /mnt/skills/public/task-report-build/scripts/convert.py --task-id <任务id> --task-name "<任务名称>" --task-content "<任务内容>"
python /mnt/skills/public/task-report-build/scripts/convert.py --task-context /mnt/user-data/workspace/task-context.json
```
一次填满 14 类并**函数合并**写出 `/mnt/user-data/outputs/task-reports.json`(`contentJson` 为 JSON 字符串、汉字原文、无 `\uXXXX`)。**合文件也是脚本做的**,不要自己拼、不要 `cat`/`Copy-Item`/`shutil.copy`、不要写 locate/fix/inspect 脚本去「找文件再合」。
@@ -33,12 +44,14 @@ python /mnt/skills/public/task-report-build/scripts/convert.py --task-id <任务
stdout 一行 JSON,只需扫一眼 `success` / `hits` / `output` / `warnings`:
- `success: true` 且 `hits > 0` → JSON 已在 outputs 里,直接进入下一步写 md,**不要再写校验脚本、不要 `ls`、不要重复确认、不要拷贝文件**。
- `hits: 0` → `warnings` 已说明尝试过的路径写法。按提示改用 `--hits hits/q01.json --hits hits/q02.json …`(相对路径)**重跑一次**即可,**不要写 debug/diag 脚本去排查路径**。
- `hits: 0` → `warnings` 已说明尝试过的路径写法。在固定命令末尾追加
`--hits hits/q01.json --hits hits/q02.json …`(相对路径)**重跑一次**即可,
**不要写 debug/diag 脚本去排查路径**。
- `present_files` 若提示 `task-reports.json` 不存在:只允许**再跑一次上面这条 convert 命令**,仍然不要写定位脚本。
- 控制台中文显示成乱码是终端编码问题,**文件本身是 UTF-8,不用管、不用验证**。
- 模型中途断开也不影响:`task-reports.json` 已经落在 outputs,用户仍可点「开始入库」。
只想补某一页时才用分页技能(参数同上,会覆盖该页碎片并重新拼总文件):
只想补某一页时才用分页技能(同样只传固定的 `--task-context`,会覆盖该页碎片并重新拼总文件):
| 技能 | 写入分类 | 大屏页 |
| --- | --- | --- |
@@ -47,7 +60,8 @@ stdout 一行 JSON,只需扫一眼 `success` / `hits` / `output` / `warnings`
| `task-report-env` | 信息环境 / 人文环境 | 环境 |
| `task-report-judge` | 优劣势 / 条件与限制 / 风险及应对 / 行动方案 / 处置建议 / 决心建议 | 研判·决心·处置 |
- **允许**用上述 `python …/convert.py` 写入 `/mnt/user-data/outputs/task-reports.json`。
- **允许**用上述 `python …/convert.py --task-context /mnt/user-data/workspace/task-context.json`
写入 `/mnt/user-data/outputs/task-reports.json`。
- **禁止**用 `write_file` / `echo` / `cat <<` / `python -c` 手写或覆盖这份 JSON。
- **禁止**为排查问题写 `debug*.py` / `diag*.py` / `verify*.py` / `locate*.py` / `fix*.py` / `inspect*.py` 之类的临时脚本;脚本 stdout 已给出全部所需信息。
- 沙箱 shell 在 Windows 上是 PowerShell:`python -c "…"` 的引号/反斜杠很容易被吞,**不要用 `python -c`**。
@@ -103,6 +117,8 @@ python /mnt/skills/public/task-report-import/scripts/task_report_import.py --tas
- **先检索 → 落盘 hits → 技能转换 → 再写 md**:没有 hits 文件就不要跑转换,没有转换成功就不要宣称 JSON 已生成。
- **JSON 只许转换脚本写**:`task-reports.json` 禁止模型 `write_file`。`report.md` 仍必须 `write_file`(不要用 bash 重定向写 md)。
- 任务 id 一律取开场信息或隐藏任务上下文里的「任务id(task_id)」,不要自造、改动,**更不要向用户询问**。
- 任务 id 一律取开场信息或隐藏任务上下文里的「任务id(task_id)」并作为 JSON 数据写入
`task-context.json`,不要自造、改动,**更不要向用户询问**。
- **文件读写一律使用 `/mnt/user-data/...` 与 `/mnt/skills/...` 虚拟路径**,即使工具输出里出现宿主机真实路径,也不要改用宿主路径。
- 除 `report.md` 与 `task-reports.json` 外,不要在 `/mnt/user-data/outputs/` 写其他交付文件;hits 与分类碎片放 `/mnt/user-data/workspace/`。
- 除 `report.md` 与 `task-reports.json` 外,不要在 `/mnt/user-data/outputs/` 写其他交付文件;
hits、`task-context.json` 与分类碎片放 `/mnt/user-data/workspace/`。
@@ -0,0 +1,33 @@
---
name: task-report-build
description: 任务研判结构化转换:读取 hits 目录中的原始 web_search JSON,一次生成大屏需要的 14 类 task-reports.json。只整理真实检索证据,不生成检索材料之外的事实。
allowed-tools: write_file, bash
---
# 任务研判结构化转换(全量)
在检索结果已逐次原样写入 `/mnt/user-data/workspace/hits/qNN.json` 后,用 `write_file`
把任务字段作为 JSON 数据写入 `/mnt/user-data/workspace/task-context.json`:
```json
{"taskId":"真实任务id","taskName":"真实任务名称","taskContent":"真实任务内容"}
```
然后运行固定命令,禁止把任务名称或内容插入 shell:
```bash
python /mnt/skills/public/task-report-build/scripts/convert.py --task-context /mnt/user-data/workspace/task-context.json
```
脚本使用纯标准库读取异构检索 JSON,去重后生成 14 个固定 `categoryType` 记录,
并原子写入 `/mnt/user-data/outputs/task-reports.json`。每条 `contentJson` 都是保留汉字
原文的 JSON 字符串。转换只搬运可追溯的检索证据,不替模型编造研判事实。
stdout 始终只有一行 JSON,重点检查:
- `success=true` 且 `hits>0`:输出已完成;
- `hits=0`:没有写入或覆盖输出。按 `warnings` 提示改用重复的
`--hits hits/q01.json --hits hits/q02.json` 参数追加到固定命令后重跑一次;
- `output`:宿主机实际输出位置;模型后续仍应使用 `/mnt/user-data/...` 虚拟路径。
不要用模型或临时脚本手写、拼接、复制 `task-reports.json`。
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Thin CLI for the full AgentFX task-report conversion."""
from __future__ import annotations
import sys
from pathlib import Path
LIB_DIR = Path(__file__).resolve().parents[2] / "task-report-lib"
if str(LIB_DIR) not in sys.path:
sys.path.insert(0, str(LIB_DIR))
from convert_lib import cli_main # noqa: E402
if __name__ == "__main__":
sys.exit(cli_main(group="all"))
@@ -0,0 +1,22 @@
---
name: task-report-enemy
description: 补跑任务研判“敌情”页:从原始检索 JSON 更新敌情关键事件、敌情对手叙事、敌情目标三类,并与已有 task-reports.json 自动合并。
allowed-tools: write_file, bash
---
# 任务研判敌情页补跑
仅在需要刷新敌情页时运行:
```bash
python /mnt/skills/public/task-report-enemy/scripts/convert.py --task-context /mnt/user-data/workspace/task-context.json
```
`task-context.json` 必须由 `write_file` 写入 `{taskId,taskName,taskContent}` JSON;任务
名称/内容不得拼入 shell。文件不存在时先按全量技能说明创建。
脚本更新 `敌情关键事件 JSON`、`敌情对手叙事 JSON`、`敌情目标 JSON`,保留现有文件
中的其他分类,并按固定顺序重新组装汇总文件。零命中时不会覆盖已有输出;按 stdout
的 `warnings` 提示可用重复的 `--hits <相对路径>` 重跑。
不要手工修改或拼接汇总 JSON。
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Thin CLI for the AgentFX enemy report page."""
from __future__ import annotations
import sys
from pathlib import Path
LIB_DIR = Path(__file__).resolve().parents[2] / "task-report-lib"
if str(LIB_DIR) not in sys.path:
sys.path.insert(0, str(LIB_DIR))
from convert_lib import cli_main # noqa: E402
if __name__ == "__main__":
sys.exit(cli_main(group="enemy"))
@@ -0,0 +1,22 @@
---
name: task-report-env
description: 补跑任务研判“环境”页:从原始检索 JSON 更新信息环境、人文环境两类,并与已有 task-reports.json 自动合并。
allowed-tools: write_file, bash
---
# 任务研判环境页补跑
仅在需要刷新环境页时运行:
```bash
python /mnt/skills/public/task-report-env/scripts/convert.py --task-context /mnt/user-data/workspace/task-context.json
```
`task-context.json` 必须由 `write_file` 写入 `{taskId,taskName,taskContent}` JSON;任务
名称/内容不得拼入 shell。文件不存在时先按全量技能说明创建。
脚本更新 `信息环境 JSON`、`人文环境 JSON`,保留现有文件中的其他分类,然后由同一
共享函数按 14 类固定顺序重新组装 `/mnt/user-data/outputs/task-reports.json`。零命中时
不会覆盖已有输出;可根据 stdout 的 `warnings` 用重复的 `--hits <相对路径>` 重跑。
不要手工修改或拼接汇总 JSON。
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Thin CLI for the AgentFX environment report page."""
from __future__ import annotations
import sys
from pathlib import Path
LIB_DIR = Path(__file__).resolve().parents[2] / "task-report-lib"
if str(LIB_DIR) not in sys.path:
sys.path.insert(0, str(LIB_DIR))
from convert_lib import cli_main # noqa: E402
if __name__ == "__main__":
sys.exit(cli_main(group="env"))
@@ -0,0 +1,23 @@
---
name: task-report-judge
description: 补跑任务研判“研判·决心·处置”页:更新条件限制、优劣势、风险应对、行动方案、处置建议、决心建议六类,并与已有 task-reports.json 自动合并。
allowed-tools: write_file, bash
---
# 任务研判研判页补跑
仅在需要刷新研判、决心与处置页时运行:
```bash
python /mnt/skills/public/task-report-judge/scripts/convert.py --task-context /mnt/user-data/workspace/task-context.json
```
`task-context.json` 必须由 `write_file` 写入 `{taskId,taskName,taskContent}` JSON;任务
名称/内容不得拼入 shell。文件不存在时先按全量技能说明创建。
脚本更新 `条件与限制 JSON`、`优劣势分析 JSON`、`风险及应对 JSON`、`行动方案 JSON`、
`处置建议 JSON`、`决心建议 JSON`,保留其他分类,并按固定顺序重新组装汇总文件。
零命中时不会覆盖已有输出;按 stdout 的 `warnings` 可用重复的 `--hits <相对路径>`
重跑。
不要手工修改或拼接汇总 JSON。
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Thin CLI for the AgentFX judgement and actions report page."""
from __future__ import annotations
import sys
from pathlib import Path
LIB_DIR = Path(__file__).resolve().parents[2] / "task-report-lib"
if str(LIB_DIR) not in sys.path:
sys.path.insert(0, str(LIB_DIR))
from convert_lib import cli_main # noqa: E402
if __name__ == "__main__":
sys.exit(cli_main(group="judge"))
@@ -0,0 +1,9 @@
{
"required_by": [
"task-report-build",
"task-report-enemy",
"task-report-our",
"task-report-env",
"task-report-judge"
]
}
@@ -0,0 +1,7 @@
# task-report-lib
`task-report-build` 与四个分页技能共用的纯标准库引擎(`convert_lib.py`)。
本目录**没有** `SKILL.md`,不会出现在技能列表里。运行时由各技能的 `scripts/convert.py` 按相对路径或 `/mnt/skills/public/task-report-lib` 加载。
`GROUP_CATEGORIES["all"]` 一次填 14 类;`enemy` / `our` / `env` / `judge` 只填对应页。`resolve_hit_files` 会尝试虚拟绝对路径、去掉 `/mnt/user-data/workspace/` 前缀的相对写法、以及末级目录名,避免沙箱里 `isdir` 为真但读不到文件。
@@ -0,0 +1,821 @@
#!/usr/bin/env python3
"""Shared, standard-library-only converter for the AgentFX report skills.
The model writes raw ``web_search`` JSON into ``/mnt/user-data/workspace/hits``.
This module turns those files into the 14 records consumed by the task report
API. It deliberately performs only deterministic extraction and placement:
it never invents evidence or conclusions that were absent from the search
payloads.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
import tempfile
from collections.abc import Iterable, Mapping, Sequence
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
DEFAULT_HITS_DIR = "/mnt/user-data/workspace/hits"
DEFAULT_OUTPUT = "/mnt/user-data/outputs/task-reports.json"
DEFAULT_TASK_CONTEXT = "/mnt/user-data/workspace/task-context.json"
MAX_EVIDENCE_PER_CATEGORY = 12
EVIDENCE_MARKER = "[检索证据]"
CATEGORY_TYPES: list[str] = [
"信息环境 JSON",
"人文环境 JSON",
"敌情关键事件 JSON",
"敌情对手叙事 JSON",
"敌情目标 JSON",
"我情口径 JSON",
"我情叙事 JSON",
"我情上级要求 JSON",
"条件与限制 JSON",
"优劣势分析 JSON",
"风险及应对 JSON",
"行动方案 JSON",
"处置建议 JSON",
"决心建议 JSON",
]
GROUP_CATEGORIES: dict[str, tuple[str, ...]] = {
"all": tuple(CATEGORY_TYPES),
"env": ("信息环境 JSON", "人文环境 JSON"),
"enemy": ("敌情关键事件 JSON", "敌情对手叙事 JSON", "敌情目标 JSON"),
"our": ("我情口径 JSON", "我情叙事 JSON", "我情上级要求 JSON"),
"judge": (
"条件与限制 JSON",
"优劣势分析 JSON",
"风险及应对 JSON",
"行动方案 JSON",
"处置建议 JSON",
"决心建议 JSON",
),
}
_CATEGORY_KEYWORDS: dict[str, tuple[str, ...]] = {
"信息环境 JSON": ("舆情", "传播", "媒体", "网络", "信息", "话题", "平台"),
"人文环境 JSON": ("人文", "人口", "文化", "社会", "宗教", "民族", "民众"),
"敌情关键事件 JSON": ("事件", "通报", "发生", "行动", "进展", "冲突", "对手"),
"敌情对手叙事 JSON": ("对手", "声称", "表态", "叙事", "声明", "指责", "回应"),
"敌情目标 JSON": ("目标", "意图", "计划", "企图", "目的", "战略"),
"我情口径 JSON": ("口径", "发布", "回应", "通报", "立场", "发言"),
"我情叙事 JSON": ("叙事", "主张", "说明", "宣传", "解读", "观点"),
"我情上级要求 JSON": ("要求", "部署", "指示", "政策", "规定", "通知"),
"条件与限制 JSON": ("条件", "限制", "约束", "资源", "时间", "法律", "边界"),
"优劣势分析 JSON": ("优势", "劣势", "能力", "短板", "机会", "挑战"),
"风险及应对 JSON": ("风险", "威胁", "预警", "应对", "防范", "处置"),
"行动方案 JSON": ("方案", "行动", "措施", "步骤", "计划", "实施"),
"处置建议 JSON": ("建议", "处置", "协调", "措施", "响应", "改进"),
"决心建议 JSON": ("决心", "建议", "研判", "选择", "优先", "方向"),
}
_CONTAINER_KEYS: tuple[str, ...] = (
"results",
"items",
"hits",
"documents",
"records",
"entries",
"data",
)
_TITLE_KEYS: tuple[str, ...] = ("title", "name", "headline", "subject")
_CONTENT_KEYS: tuple[str, ...] = (
"content",
"snippet",
"summary",
"description",
"text",
"body",
)
_URL_KEYS: tuple[str, ...] = ("url", "link", "href", "source_url", "sourceUrl")
_DATE_KEYS: tuple[str, ...] = (
"published_at",
"publishedAt",
"publish_time",
"publishTime",
"date",
"time",
)
_ID_KEYS: tuple[str, ...] = ("id", "uuid", "recUuid", "doc_id", "document_id")
_QUERY_KEYS: tuple[str, ...] = ("query", "keyword", "keywords", "search_query")
class PathConfinementError(ValueError):
"""Raised when a converter path escapes the current thread user-data root."""
def _absolute(path: Path) -> Path:
"""Return a normalized absolute path without requiring it to exist."""
return Path(os.path.abspath(os.fspath(path)))
def discover_user_data_root(cwd: str | os.PathLike[str] | None = None) -> Path | None:
"""Find the host directory mounted as ``/mnt/user-data``.
Sandbox bash starts in the thread ``workspace`` directory on Windows. A
virtual path can therefore resolve to a real drive-root ``\\mnt`` path yet
still not refer to the thread. Walking from cwd is the reliable mapping.
"""
current = _absolute(Path(cwd) if cwd is not None else Path.cwd()).resolve(strict=False)
for candidate in (current, *current.parents):
if candidate.name.casefold() == "user-data" and (candidate / "workspace").is_dir():
return candidate
return None
def _require_user_data_root(cwd: str | os.PathLike[str] | None = None) -> Path:
root = discover_user_data_root(cwd)
if root is None:
raise PathConfinementError(
"无法从当前工作目录识别 /mnt/user-data;拒绝访问检索或输出路径"
)
return root.resolve(strict=False)
def _confine_to_user_data(path: Path, root: Path) -> Path:
"""Canonicalize ``path`` and require it to remain below ``root``."""
canonical_root = root.resolve(strict=False)
canonical_path = path.resolve(strict=False)
try:
common = Path(os.path.commonpath((canonical_root, canonical_path)))
except ValueError as exc:
raise PathConfinementError(
f"路径不在当前线程 user-data 内:{path}"
) from exc
if os.path.normcase(os.fspath(common)) != os.path.normcase(os.fspath(canonical_root)):
raise PathConfinementError(f"路径不在当前线程 user-data 内:{path}")
return canonical_path
def _virtual_user_data_rest(path: str | os.PathLike[str]) -> tuple[str, ...] | None:
normalized = os.fspath(path).replace("\\", "/").rstrip("/")
prefix = "/mnt/user-data"
if normalized == prefix:
return ()
if normalized.startswith(prefix + "/"):
return tuple(part for part in normalized[len(prefix) + 1 :].split("/") if part)
return None
def resolve_sandbox_path(
path: str | os.PathLike[str],
*,
cwd: str | os.PathLike[str] | None = None,
) -> Path:
"""Map and confine a path to the current thread's canonical user-data root."""
current = _absolute(Path(cwd) if cwd is not None else Path.cwd())
rest = _virtual_user_data_rest(path)
user_data_root = _require_user_data_root(current)
if rest is not None:
return _confine_to_user_data(user_data_root.joinpath(*rest), user_data_root)
raw = Path(path).expanduser()
candidate = raw if raw.is_absolute() else current / raw
return _confine_to_user_data(candidate, user_data_root)
def _path_key(path: Path) -> str:
return os.path.normcase(os.path.normpath(os.fspath(_absolute(path))))
def _candidate_paths(
raw: str | os.PathLike[str],
*,
cwd: str | os.PathLike[str] | None = None,
) -> list[Path]:
"""Return confined mapped, stripped-relative and basename candidates."""
current = _absolute(Path(cwd) if cwd is not None else Path.cwd())
root = _require_user_data_root(current)
rest = _virtual_user_data_rest(raw)
if rest is None:
return [resolve_sandbox_path(raw, cwd=current)]
candidates: list[Path] = [_confine_to_user_data(root.joinpath(*rest), root)]
if rest:
for candidate in (current.joinpath(*rest), current / rest[-1]):
try:
candidates.append(_confine_to_user_data(candidate, root))
except PathConfinementError:
continue
unique: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
key = _path_key(candidate)
if key not in seen:
seen.add(key)
unique.append(candidate)
return unique
def _json_files(candidate: Path, *, root: Path) -> list[Path]:
if candidate.is_file() and candidate.suffix.casefold() == ".json":
return [_confine_to_user_data(candidate, root)]
if candidate.is_dir():
return sorted(
(
_confine_to_user_data(item, root)
for item in candidate.iterdir()
if item.is_file() and item.suffix.casefold() == ".json"
),
key=lambda item: item.name.casefold(),
)
return []
def resolve_hit_files(
hits_dir: str | os.PathLike[str] = DEFAULT_HITS_DIR,
*,
hits: Sequence[str | os.PathLike[str]] | None = None,
cwd: str | os.PathLike[str] | None = None,
) -> tuple[list[Path], list[str]]:
"""Resolve hit files, continuing past an existing-but-empty virtual path."""
requested: Sequence[str | os.PathLike[str]] = hits if hits else (hits_dir,)
resolved: list[Path] = []
warnings: list[str] = []
seen_files: set[str] = set()
root = _require_user_data_root(cwd)
for raw in requested:
candidates = _candidate_paths(raw, cwd=cwd)
selected: list[Path] = []
for candidate in candidates:
selected = _json_files(candidate, root=root)
if selected:
break
if not selected:
attempts = "、".join(os.fspath(candidate) for candidate in candidates)
warnings.append(f"未找到检索 JSON:{raw};已尝试:{attempts}")
continue
for path in selected:
key = _path_key(path)
if key not in seen_files:
seen_files.add(key)
resolved.append(path)
return resolved, warnings
def load_task_context(
path: str | os.PathLike[str] = DEFAULT_TASK_CONTEXT,
*,
cwd: str | os.PathLike[str] | None = None,
) -> dict[str, str]:
"""Load task metadata as JSON data from a confined, fixed-path file."""
context_path = resolve_sandbox_path(path, cwd=cwd)
if not context_path.is_file():
raise ValueError(f"找不到任务上下文 JSON:{context_path}")
try:
payload = json.loads(context_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ValueError(f"任务上下文 JSON 无法读取:{exc}") from exc
if not isinstance(payload, Mapping):
raise ValueError("任务上下文必须是 JSON 对象")
task_id = payload.get("taskId", payload.get("task_id"))
task_name = payload.get("taskName", payload.get("task_name", ""))
task_content = payload.get("taskContent", payload.get("task_content", ""))
if task_id is None or not str(task_id).strip():
raise ValueError("任务上下文缺少 taskId")
if not isinstance(task_name, (str, int, float, bool)) or not isinstance(
task_content, (str, int, float, bool)
):
raise ValueError("taskName/taskContent 必须是字符串或标量")
return {
"task_id": str(task_id).strip(),
"task_name": str(task_name),
"task_content": str(task_content),
}
def _first_text(value: Mapping[str, Any], keys: Iterable[str]) -> str:
for key in keys:
candidate = value.get(key)
if candidate is None or isinstance(candidate, (dict, list, tuple)):
continue
text = str(candidate).strip()
if text:
return text
return ""
def _looks_like_hit(value: Mapping[str, Any]) -> bool:
searchable = (*_TITLE_KEYS, *_CONTENT_KEYS, *_URL_KEYS)
return any(key in value and value.get(key) not in (None, "") for key in searchable)
def _extract_items(payload: Any) -> list[Mapping[str, Any]]:
if isinstance(payload, list):
return [item for item in payload if isinstance(item, Mapping)]
if not isinstance(payload, Mapping):
return []
for key in _CONTAINER_KEYS:
nested = payload.get(key)
if isinstance(nested, list):
items = [item for item in nested if isinstance(item, Mapping)]
if items:
return items
if isinstance(nested, Mapping):
items = _extract_items(nested)
if items:
return items
return [payload] if _looks_like_hit(payload) else []
def _normalize_hit(
item: Mapping[str, Any],
*,
query: str,
source_file: Path,
) -> dict[str, str] | None:
title = _first_text(item, _TITLE_KEYS)
content = _first_text(item, _CONTENT_KEYS)
url = _first_text(item, _URL_KEYS)
published_at = _first_text(item, _DATE_KEYS)
source_id = _first_text(item, _ID_KEYS)
item_query = _first_text(item, _QUERY_KEYS) or query
if not any((title, content, url)):
return None
return {
"title": title,
"content": content,
"url": url,
"publishedAt": published_at,
"sourceId": source_id,
"query": item_query,
"sourceFile": source_file.name,
}
def load_evidence(hit_files: Sequence[Path]) -> tuple[list[dict[str, str]], list[str]]:
"""Read heterogeneous search payloads and return deduplicated evidence."""
evidence: list[dict[str, str]] = []
warnings: list[str] = []
seen: set[str] = set()
for hit_file in hit_files:
try:
payload = json.loads(hit_file.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
warnings.append(f"跳过无法读取的检索 JSON {hit_file.name}:{exc}")
continue
query = _first_text(payload, _QUERY_KEYS) if isinstance(payload, Mapping) else ""
items = _extract_items(payload)
if not items:
warnings.append(f"检索 JSON 未包含可识别结果:{hit_file.name}")
continue
for item in items:
normalized = _normalize_hit(item, query=query, source_file=hit_file)
if normalized is None:
continue
signature = "\x1f".join(
normalized[key].casefold() for key in ("url", "title", "content")
)
if signature in seen:
continue
seen.add(signature)
evidence.append(normalized)
return evidence, warnings
def _evidence_for_category(
category: str,
evidence: Sequence[dict[str, str]],
) -> list[dict[str, str]]:
keywords = _CATEGORY_KEYWORDS[category]
scored: list[tuple[int, int, dict[str, str]]] = []
for index, item in enumerate(evidence):
haystack = " ".join(item.values()).casefold()
score = sum(haystack.count(keyword.casefold()) for keyword in keywords)
scored.append((score, index, item))
relevant = [entry for entry in scored if entry[0] > 0]
selected = relevant if relevant else scored
selected.sort(key=lambda entry: (-entry[0], entry[1]))
return [dict(entry[2]) for entry in selected[:MAX_EVIDENCE_PER_CATEGORY]]
def _now_iso() -> str:
return datetime.now(timezone(timedelta(hours=8))).isoformat(timespec="seconds")
def _record_id(task_id: str, category: str) -> str:
digest = hashlib.sha256(f"{task_id}\x1f{category}".encode()).hexdigest()[:12]
return f"agentfx-{digest}"
def _clip(value: str, limit: int = 1200) -> str:
normalized = " ".join(value.split())
return normalized if len(normalized) <= limit else normalized[: limit - 1] + "…"
def _evidence_title(item: Mapping[str, str]) -> str:
return _clip(item.get("title") or item.get("query") or item.get("sourceFile") or "检索条目", 180)
def _evidence_text(item: Mapping[str, str]) -> str:
parts = [_evidence_title(item)]
if item.get("content"):
parts.append(_clip(item["content"]))
if item.get("url"):
parts.append(f"来源:{item['url']}")
return f"{EVIDENCE_MARKER} " + ";".join(parts)
def _evidence_uuid(item: Mapping[str, str], index: int) -> str:
source = "\x1f".join(
(item.get("sourceId", ""), item.get("url", ""), item.get("title", ""), str(index))
)
return hashlib.sha256(source.encode()).hexdigest()[:24]
def _category_payload(
*,
category: str,
task_id: str,
task_name: str,
task_content: str,
evidence: Sequence[dict[str, str]],
timestamp: str,
) -> object:
"""Build the exact legacy shapes consumed by the six dashboard adapters."""
selected = _evidence_for_category(category, evidence)
lines = [_evidence_text(item) for item in selected]
if category == "信息环境 JSON":
return {"type": 1, "检索证据与信息环境": lines}
if category == "人文环境 JSON":
return {"type": 2, "检索证据与人文环境": lines}
if category == "敌情关键事件 JSON":
events = [
{
"recUuid": item.get("sourceId") or _evidence_uuid(item, index),
"date": item.get("publishedAt", ""),
"publish_time": item.get("publishedAt", ""),
"link": item.get("url", ""),
"title": _evidence_title(item),
"content": _evidence_text(item),
}
for index, item in enumerate(selected)
]
return [{"topic": f"{EVIDENCE_MARKER} 待核验事件线索", "count": len(events), "events": events}]
if category == "敌情对手叙事 JSON":
return [
{
"summary": _evidence_text(item),
"narrator": item.get("url") or item.get("sourceFile") or "检索来源待核验",
"event_summary": _evidence_text(item),
"narrative_topic_types": "检索证据",
"event_name": _evidence_title(item),
"topic": _evidence_title(item),
"intent_of_the_opponent": f"{EVIDENCE_MARKER} 未推断意图,需人工复核",
"id": _evidence_uuid(item, index),
"entity": item.get("url") or item.get("sourceFile") or "检索来源待核验",
"topicType": "检索证据",
"intention": f"{EVIDENCE_MARKER} 未推断意图,需人工复核",
}
for index, item in enumerate(selected)
]
if category == "敌情目标 JSON":
return {
"organization": [
{
"eid": _evidence_uuid(item, index),
"name": f"{EVIDENCE_MARKER} {_evidence_title(item)}",
"etype": "evidence",
"text": "检索证据来源",
"reason": _evidence_text(item),
"taskId": task_id,
}
for index, item in enumerate(selected)
],
"human": [],
}
if category == "我情口径 JSON":
return {
"selfSpeech": [
{
"trendSpeechTitle": _evidence_title(item),
"trendSpeechTitleMini": _evidence_title(item),
"trendSpeechLike": _evidence_text(item),
"trendSpeechContent": _evidence_text(item),
"narrativeDirection": f"{EVIDENCE_MARKER} 仅供材料核验,不代表既定口径",
"narrativeConstraints": "不得超出已检索材料形成事实判断",
"trendSpeechTime": item.get("publishedAt", ""),
"esId": _evidence_uuid(item, index),
"taskId": task_id,
}
for index, item in enumerate(selected)
],
"selfConsistents": [],
}
if category == "我情叙事 JSON":
return [
{
"标题": _evidence_title(item),
"意图": f"{EVIDENCE_MARKER} 复核公开材料,不预设研判结论",
"标签": [item.get("query") or "检索证据"],
"内容": _evidence_text(item),
}
for item in selected
]
if category == "我情上级要求 JSON":
context = _clip(task_content) if task_content else "任务上下文未提供额外要求"
return f"{EVIDENCE_MARKER} 任务上下文:{context}\n仅依据已检索材料复核,不补造事实。"
if category == "条件与限制 JSON":
return {
"证据约束": lines,
"研判限制": [f"{EVIDENCE_MARKER} 当前输出仅整理检索结果,结论需人工核验。"],
}
if category == "优劣势分析 JSON":
return {
"优势": [
{"title": f"{EVIDENCE_MARKER} 待核验优势线索", "content": lines[0]}
],
"劣势": [
{
"title": f"{EVIDENCE_MARKER} 待核验劣势线索",
"content": lines[min(1, len(lines) - 1)],
}
],
}
if category == "风险及应对 JSON":
return {
"风险分析": [f"{EVIDENCE_MARKER} 信息完整性风险:{line}" for line in lines],
"应对方案": [
f"{EVIDENCE_MARKER} 证据复核建议:核对来源、时间与原文后再形成结论。"
],
}
if category == "行动方案 JSON":
digest = hashlib.sha256(f"{task_id}\x1faction-plan".encode()).hexdigest()
return [
{
"trendPlanDesc": f"{EVIDENCE_MARKER} 仅用于检索证据复核,不包含行动结论。",
"createTime": timestamp,
"esId": digest[:24],
"trendPlanName": "检索证据复核方案",
"updateTime": timestamp,
"id": int(digest[:8], 16),
"trendPlanGoal": "\n".join(lines),
"trendPlanAction": 0,
"taskId": task_id,
}
]
if category == "处置建议 JSON":
return {
"目标": f"{EVIDENCE_MARKER} 核验检索证据并形成可追溯结论。",
"md": "",
"处置建议总结": f"{EVIDENCE_MARKER} 当前仅建议完成来源复核,未形成业务处置结论。",
"处置建议": [
{
"建议内容": f"复核检索条目:{_evidence_title(item)}",
"处置方式与步骤": _evidence_text(item),
"口径基调": "客观、可核验",
"预期效果": "确认该材料是否足以支撑后续研判",
"处置主体": {"主责单位": "报告复核人员", "配合单位": []},
"立场与原则": f"{EVIDENCE_MARKER} 不超出原始来源作事实推断",
}
for item in selected[:3]
],
}
if category == "决心建议 JSON":
targets = [
{
"目标名称": f"{EVIDENCE_MARKER} {_evidence_title(item)}",
"目标描述": _evidence_text(item),
"选择理由": f"{EVIDENCE_MARKER} 该条目来自本轮检索,需核验后再决定用途",
"潜在影响": f"{EVIDENCE_MARKER} 尚未评估,需人工研判",
"推荐依据": item.get("url") or _evidence_text(item),
}
for item in selected[:3]
]
return {
"决心建议": {
"任务标题": task_name,
"任务简介": task_content,
"作战目的": [f"{EVIDENCE_MARKER} 完成来源核验后再形成业务结论"],
"打击目标": targets,
},
"实施要点": [f"{EVIDENCE_MARKER} 核对来源链接、发布时间与正文一致性"],
"md": "",
"关键战情": {},
"决心建议总结": f"{EVIDENCE_MARKER} 当前输出为证据候选整理,不构成行动建议。",
}
raise ValueError(f"不支持的报告分类:{category}")
def build_records(
*,
categories: Sequence[str],
task_id: str,
task_name: str,
task_content: str,
evidence: Sequence[dict[str, str]],
) -> list[dict[str, str]]:
"""Build records only from observed evidence; callers reject an empty set."""
timestamp = _now_iso()
records: list[dict[str, str]] = []
for category in categories:
content = _category_payload(
category=category,
task_id=task_id,
task_name=task_name,
task_content=task_content,
evidence=evidence,
timestamp=timestamp,
)
records.append(
{
"id": _record_id(task_id, category),
"taskId": task_id,
"createTime": timestamp,
"updateTime": timestamp,
"sessionId": "agentfx-convert",
"contentJson": json.dumps(content, ensure_ascii=False, separators=(",", ":")),
"categoryType": category,
}
)
return records
def _load_existing_records(path: Path, warnings: list[str]) -> list[dict[str, Any]] | None:
if not path.is_file():
return []
try:
payload = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
warnings.append(f"现有报告无法解析,已拒绝分页覆盖:{exc}")
return None
if isinstance(payload, Mapping):
payload = payload.get("data", payload.get("records"))
if not isinstance(payload, list):
warnings.append("现有报告不是数组,已拒绝分页覆盖")
return None
return [dict(item) for item in payload if isinstance(item, Mapping)]
def assemble_records(
existing: Sequence[Mapping[str, Any]],
replacements: Sequence[Mapping[str, Any]],
) -> list[dict[str, Any]]:
"""Replace converted categories and return records in dashboard order."""
by_category: dict[str, dict[str, Any]] = {}
for item in (*existing, *replacements):
category = str(item.get("categoryType", ""))
if category in CATEGORY_TYPES:
by_category[category] = dict(item)
return [by_category[category] for category in CATEGORY_TYPES if category in by_category]
def _write_json_atomic(path: Path, payload: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.",
suffix=".tmp",
dir=path.parent,
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as handle:
json.dump(payload, handle, ensure_ascii=False, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary_name, path)
except BaseException:
try:
os.unlink(temporary_name)
except OSError:
pass
raise
def convert_reports(
*,
group: str,
task_id: str,
task_name: str = "",
task_content: str = "",
hits_dir: str | os.PathLike[str] = DEFAULT_HITS_DIR,
hits: Sequence[str | os.PathLike[str]] | None = None,
output: str | os.PathLike[str] = DEFAULT_OUTPUT,
cwd: str | os.PathLike[str] | None = None,
) -> dict[str, object]:
"""Convert search JSON and atomically merge the selected dashboard page."""
warnings: list[str] = []
result: dict[str, object] = {
"success": False,
"hits": 0,
"output": os.fspath(output),
"warnings": warnings,
}
try:
output_path = resolve_sandbox_path(output, cwd=cwd)
except PathConfinementError as exc:
warnings.append(str(exc))
return result
result["output"] = os.fspath(output_path)
normalized_group = group.strip().casefold()
if normalized_group not in GROUP_CATEGORIES:
warnings.append(f"未知分类组:{group}")
return result
normalized_task_id = task_id.strip()
if not normalized_task_id:
warnings.append("--task-id 不能为空")
return result
try:
hit_files, path_warnings = resolve_hit_files(hits_dir, hits=hits, cwd=cwd)
except PathConfinementError as exc:
warnings.append(str(exc))
return result
warnings.extend(path_warnings)
evidence, read_warnings = load_evidence(hit_files)
warnings.extend(read_warnings)
result["hits"] = len(evidence)
if not evidence:
warnings.append("没有可用检索结果;未生成或覆盖 task-reports.json,避免编造证据")
return result
replacements = build_records(
categories=GROUP_CATEGORIES[normalized_group],
task_id=normalized_task_id,
task_name=task_name,
task_content=task_content,
evidence=evidence,
)
existing = [] if normalized_group == "all" else _load_existing_records(output_path, warnings)
if existing is None:
return result
existing_task_ids = {
str(record.get("taskId", "")).strip()
for record in existing
if str(record.get("categoryType", "")) in CATEGORY_TYPES
}
if existing_task_ids and existing_task_ids != {normalized_task_id}:
found = "、".join(sorted(task_id or "(缺失)" for task_id in existing_task_ids))
warnings.append(
f"现有报告任务 {found} 与当前任务 {normalized_task_id} 不一致,已拒绝分页合并"
)
return result
assembled = assemble_records(existing, replacements)
_write_json_atomic(output_path, assembled)
result["success"] = True
return result
def cli_main(*, group: str) -> int:
parser = argparse.ArgumentParser(description="把 web_search JSON 转换为任务研判分类记录")
parser.add_argument("--task-id", default="", help="任务 id(兼容旧调用)")
parser.add_argument("--task-name", default="", help="任务名称")
parser.add_argument("--task-content", default="", help="任务内容")
parser.add_argument(
"--task-context",
default="",
help=f"任务上下文 JSON(推荐固定使用 {DEFAULT_TASK_CONTEXT})",
)
parser.add_argument("--hits-dir", default=DEFAULT_HITS_DIR, help="检索 JSON 目录")
parser.add_argument(
"--hits",
action="append",
default=None,
help="显式检索 JSON 文件或目录;可重复传入",
)
parser.add_argument("--output", default=DEFAULT_OUTPUT, help="汇总 JSON 输出路径")
args = parser.parse_args()
try:
if args.task_context:
context = load_task_context(args.task_context)
args.task_id = context["task_id"]
args.task_name = context["task_name"]
args.task_content = context["task_content"]
result = convert_reports(
group=group,
task_id=args.task_id,
task_name=args.task_name,
task_content=args.task_content,
hits_dir=args.hits_dir,
hits=args.hits,
output=args.output,
)
except Exception as exc: # noqa: BLE001 - CLI must always return a machine-readable line.
result = {
"success": False,
"hits": 0,
"output": os.fspath(args.output),
"warnings": [f"转换失败:{exc}"],
}
try:
sys.stdout.reconfigure(encoding="utf-8")
except (AttributeError, OSError):
pass
print(json.dumps(result, ensure_ascii=False, separators=(",", ":")))
return 0 if result["success"] else 1
if __name__ == "__main__":
sys.exit(cli_main(group="all"))
@@ -0,0 +1,22 @@
---
name: task-report-our
description: 补跑任务研判“我情”页:从原始检索 JSON 更新我情口径、我情叙事、我情上级要求三类,并与已有 task-reports.json 自动合并。
allowed-tools: write_file, bash
---
# 任务研判我情页补跑
仅在需要刷新我情页时运行:
```bash
python /mnt/skills/public/task-report-our/scripts/convert.py --task-context /mnt/user-data/workspace/task-context.json
```
`task-context.json` 必须由 `write_file` 写入 `{taskId,taskName,taskContent}` JSON;任务
名称/内容不得拼入 shell。文件不存在时先按全量技能说明创建。
脚本更新 `我情口径 JSON`、`我情叙事 JSON`、`我情上级要求 JSON`,保留现有文件中的
其他分类,并按固定顺序重新组装汇总文件。零命中时不会覆盖已有输出;按 stdout 的
`warnings` 提示可用重复的 `--hits <相对路径>` 重跑。
不要手工修改或拼接汇总 JSON。
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Thin CLI for the AgentFX own-side report page."""
from __future__ import annotations
import sys
from pathlib import Path
LIB_DIR = Path(__file__).resolve().parents[2] / "task-report-lib"
if str(LIB_DIR) not in sys.path:
sys.path.insert(0, str(LIB_DIR))
from convert_lib import cli_main # noqa: E402
if __name__ == "__main__":
sys.exit(cli_main(group="our"))